Subversion Repositories Kolibri OS

Rev

Rev 8760 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /* DO NOT EDIT!
  2. ** This file is automatically generated by the script in the canonical
  3. ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
  4. ** code from various constituent source files of SQLite into this single
  5. ** "shell.c" file used to implement the SQLite command-line shell.
  6. **
  7. ** Most of the code found below comes from the "src/shell.c.in" file in
  8. ** the canonical SQLite source tree.  That main file contains "INCLUDE"
  9. ** lines that specify other files in the canonical source tree that are
  10. ** inserted to getnerate this complete program source file.
  11. **
  12. ** The code from multiple files is combined into this single "shell.c"
  13. ** source file to help make the command-line program easier to compile.
  14. **
  15. ** To modify this program, get a copy of the canonical SQLite source tree,
  16. ** edit the src/shell.c.in" and/or some of the other files that are included
  17. ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
  18. */
  19. /*
  20. ** 2001 September 15
  21. **
  22. ** The author disclaims copyright to this source code.  In place of
  23. ** a legal notice, here is a blessing:
  24. **
  25. **    May you do good and not evil.
  26. **    May you find forgiveness for yourself and forgive others.
  27. **    May you share freely, never taking more than you give.
  28. **
  29. *************************************************************************
  30. ** This file contains code to implement the "sqlite" command line
  31. ** utility for accessing SQLite databases.
  32. */
  33. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  34. /* This needs to come before any includes for MSVC compiler */
  35. #define _CRT_SECURE_NO_WARNINGS
  36. #endif
  37.  
  38. /*
  39. ** Determine if we are dealing with WinRT, which provides only a subset of
  40. ** the full Win32 API.
  41. */
  42. #if !defined(SQLITE_OS_WINRT)
  43. # define SQLITE_OS_WINRT 0
  44. #endif
  45.  
  46. /*
  47. ** Warning pragmas copied from msvc.h in the core.
  48. */
  49. #if defined(_MSC_VER)
  50. #pragma warning(disable : 4054)
  51. #pragma warning(disable : 4055)
  52. #pragma warning(disable : 4100)
  53. #pragma warning(disable : 4127)
  54. #pragma warning(disable : 4130)
  55. #pragma warning(disable : 4152)
  56. #pragma warning(disable : 4189)
  57. #pragma warning(disable : 4206)
  58. #pragma warning(disable : 4210)
  59. #pragma warning(disable : 4232)
  60. #pragma warning(disable : 4244)
  61. #pragma warning(disable : 4305)
  62. #pragma warning(disable : 4306)
  63. #pragma warning(disable : 4702)
  64. #pragma warning(disable : 4706)
  65. #endif /* defined(_MSC_VER) */
  66.  
  67. /*
  68. ** No support for loadable extensions in VxWorks.
  69. */
  70. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  71. # define SQLITE_OMIT_LOAD_EXTENSION 1
  72. #endif
  73.  
  74. /*
  75. ** Enable large-file support for fopen() and friends on unix.
  76. */
  77. #ifndef SQLITE_DISABLE_LFS
  78. # define _LARGE_FILE       1
  79. # ifndef _FILE_OFFSET_BITS
  80. #   define _FILE_OFFSET_BITS 64
  81. # endif
  82. # define _LARGEFILE_SOURCE 1
  83. #endif
  84.  
  85. #include <stdlib.h>
  86. #include <string.h>
  87. #include <stdio.h>
  88. #include <assert.h>
  89. #include "sqlite3.h"
  90. typedef sqlite3_int64 i64;
  91. typedef sqlite3_uint64 u64;
  92. typedef unsigned char u8;
  93. #if SQLITE_USER_AUTHENTICATION
  94. # include "sqlite3userauth.h"
  95. #endif
  96. #include <ctype.h>
  97. #include <stdarg.h>
  98.  
  99. #if !defined(_WIN32) && !defined(WIN32)
  100. # include <signal.h>
  101. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  102. #  include <pwd.h>
  103. # endif
  104. #endif
  105. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  106. # include <unistd.h>
  107. # include <dirent.h>
  108. # define GETPID getpid
  109. # if defined(__MINGW32__)
  110. #  define DIRENT dirent
  111. #  ifndef S_ISLNK
  112. #   define S_ISLNK(mode) (0)
  113. #  endif
  114. # endif
  115. #else
  116. # define GETPID (int)GetCurrentProcessId
  117. #endif
  118. #include <sys/types.h>
  119. #include <sys/stat.h>
  120.  
  121. #if HAVE_READLINE
  122. # include <readline/readline.h>
  123. # include <readline/history.h>
  124. #endif
  125.  
  126. #if HAVE_EDITLINE
  127. # include <editline/readline.h>
  128. #endif
  129.  
  130. #if HAVE_EDITLINE || HAVE_READLINE
  131.  
  132. # define shell_add_history(X) add_history(X)
  133. # define shell_read_history(X) read_history(X)
  134. # define shell_write_history(X) write_history(X)
  135. # define shell_stifle_history(X) stifle_history(X)
  136. # define shell_readline(X) readline(X)
  137.  
  138. #elif HAVE_LINENOISE
  139.  
  140. # include "linenoise.h"
  141. # define shell_add_history(X) linenoiseHistoryAdd(X)
  142. # define shell_read_history(X) linenoiseHistoryLoad(X)
  143. # define shell_write_history(X) linenoiseHistorySave(X)
  144. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  145. # define shell_readline(X) linenoise(X)
  146.  
  147. #else
  148.  
  149. # define shell_read_history(X)
  150. # define shell_write_history(X)
  151. # define shell_stifle_history(X)
  152.  
  153. # define SHELL_USE_LOCAL_GETLINE 1
  154. #endif
  155.  
  156.  
  157. #if defined(_WIN32) || defined(WIN32)
  158. # if SQLITE_OS_WINRT
  159. #  define SQLITE_OMIT_POPEN 1
  160. # else
  161. #  include <io.h>
  162. #  include <fcntl.h>
  163. #  define isatty(h) _isatty(h)
  164. #  ifndef access
  165. #   define access(f,m) _access((f),(m))
  166. #  endif
  167. #  ifndef unlink
  168. #   define unlink _unlink
  169. #  endif
  170. #  ifndef strdup
  171. #   define strdup _strdup
  172. #  endif
  173. #  undef popen
  174. #  define popen _popen
  175. #  undef pclose
  176. #  define pclose _pclose
  177. # endif
  178. #else
  179.  /* Make sure isatty() has a prototype. */
  180.  extern int isatty(int);
  181.  
  182. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  183.   /* popen and pclose are not C89 functions and so are
  184.   ** sometimes omitted from the <stdio.h> header */
  185.    extern FILE *popen(const char*,const char*);
  186.    extern int pclose(FILE*);
  187. # else
  188. #  define SQLITE_OMIT_POPEN 1
  189. # endif
  190. #endif
  191.  
  192. #if defined(_WIN32_WCE)
  193. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  194.  * thus we always assume that we have a console. That can be
  195.  * overridden with the -batch command line option.
  196.  */
  197. #define isatty(x) 1
  198. #endif
  199.  
  200. /* ctype macros that work with signed characters */
  201. #define IsSpace(X)  isspace((unsigned char)X)
  202. #define IsDigit(X)  isdigit((unsigned char)X)
  203. #define ToLower(X)  (char)tolower((unsigned char)X)
  204.  
  205. #if defined(_WIN32) || defined(WIN32)
  206. #if SQLITE_OS_WINRT
  207. #include <intrin.h>
  208. #endif
  209. //#include <windows.h>
  210.  
  211. #define stderr stdout
  212.  
  213. /* string conversion routines only needed on Win32 */
  214. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  215. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  216. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  217. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  218. #endif
  219.  
  220. /* On Windows, we normally run with output mode of TEXT so that \n characters
  221. ** are automatically translated into \r\n.  However, this behavior needs
  222. ** to be disabled in some cases (ex: when generating CSV output and when
  223. ** rendering quoted strings that contain \n characters).  The following
  224. ** routines take care of that.
  225. */
  226. #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
  227. static void setBinaryMode(FILE *file, int isOutput){
  228.   if( isOutput ) fflush(file);
  229.   _setmode(_fileno(file), _O_BINARY);
  230. }
  231. static void setTextMode(FILE *file, int isOutput){
  232.   if( isOutput ) fflush(file);
  233.   _setmode(_fileno(file), _O_TEXT);
  234. }
  235. #else
  236. # define setBinaryMode(X,Y)
  237. # define setTextMode(X,Y)
  238. #endif
  239.  
  240.  
  241. /* True if the timer is enabled */
  242. static int enableTimer = 0;
  243.  
  244. /* Return the current wall-clock time */
  245. static sqlite3_int64 timeOfDay(void){
  246.   static sqlite3_vfs *clockVfs = 0;
  247.   sqlite3_int64 t;
  248.   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  249.   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  250.     clockVfs->xCurrentTimeInt64(clockVfs, &t);
  251.   }else{
  252.     double r;
  253.     clockVfs->xCurrentTime(clockVfs, &r);
  254.     t = (sqlite3_int64)(r*86400000.0);
  255.   }
  256.   return t;
  257. }
  258.  
  259. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  260. #include <sys/time.h>
  261. #include <sys/resource.h>
  262.  
  263. /* VxWorks does not support getrusage() as far as we can determine */
  264. #if defined(_WRS_KERNEL) || defined(__RTP__)
  265. struct rusage {
  266.   struct timeval ru_utime; /* user CPU time used */
  267.   struct timeval ru_stime; /* system CPU time used */
  268. };
  269. #define getrusage(A,B) memset(B,0,sizeof(*B))
  270. #endif
  271.  
  272. #ifdef _KOLIBRI
  273. #define getrusage(A,B) memset(B,0,sizeof(*B))
  274. #endif
  275.  
  276. /* Saved resource information for the beginning of an operation */
  277. static struct rusage sBegin;  /* CPU time at start */
  278. static sqlite3_int64 iBegin;  /* Wall-clock time at start */
  279.  
  280. /*
  281. ** Begin timing an operation
  282. */
  283. static void beginTimer(void){
  284.   if( enableTimer ){
  285.     getrusage(RUSAGE_SELF, &sBegin);
  286.     iBegin = timeOfDay();
  287.   }
  288. }
  289.  
  290. /* Return the difference of two time_structs in seconds */
  291. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  292.   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  293.          (double)(pEnd->tv_sec - pStart->tv_sec);
  294. }
  295.  
  296. /*
  297. ** Print the timing results.
  298. */
  299. static void endTimer(void){
  300.   if( enableTimer ){
  301.     sqlite3_int64 iEnd = timeOfDay();
  302.     struct rusage sEnd;
  303.     getrusage(RUSAGE_SELF, &sEnd);
  304.     printf("Run Time: real %.3f user %f sys %f\n",
  305.        (iEnd - iBegin)*0.001,
  306.        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  307.        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  308.   }
  309. }
  310.  
  311. #define BEGIN_TIMER beginTimer()
  312. #define END_TIMER endTimer()
  313. #define HAS_TIMER 1
  314.  
  315. #elif (defined(_WIN32) || defined(WIN32))
  316.  
  317. /* Saved resource information for the beginning of an operation */
  318. static HANDLE hProcess;
  319. static FILETIME ftKernelBegin;
  320. static FILETIME ftUserBegin;
  321. static sqlite3_int64 ftWallBegin;
  322. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  323.                                     LPFILETIME, LPFILETIME);
  324. static GETPROCTIMES getProcessTimesAddr = NULL;
  325.  
  326. /*
  327. ** Check to see if we have timer support.  Return 1 if necessary
  328. ** support found (or found previously).
  329. */
  330. static int hasTimer(void){
  331.   if( getProcessTimesAddr ){
  332.     return 1;
  333.   } else {
  334. #if !SQLITE_OS_WINRT
  335.     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  336.     ** versions. See if the version we are running on has it, and if it
  337.     ** does, save off a pointer to it and the current process handle.
  338.     */
  339.     hProcess = GetCurrentProcess();
  340.     if( hProcess ){
  341.       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  342.       if( NULL != hinstLib ){
  343.         getProcessTimesAddr =
  344.             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  345.         if( NULL != getProcessTimesAddr ){
  346.           return 1;
  347.         }
  348.         FreeLibrary(hinstLib);
  349.       }
  350.     }
  351. #endif
  352.   }
  353.   return 0;
  354. }
  355.  
  356. /*
  357. ** Begin timing an operation
  358. */
  359. static void beginTimer(void){
  360.   if( enableTimer && getProcessTimesAddr ){
  361.     FILETIME ftCreation, ftExit;
  362.     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  363.                         &ftKernelBegin,&ftUserBegin);
  364.     ftWallBegin = timeOfDay();
  365.   }
  366. }
  367.  
  368. /* Return the difference of two FILETIME structs in seconds */
  369. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  370.   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  371.   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  372.   return (double) ((i64End - i64Start) / 10000000.0);
  373. }
  374.  
  375. /*
  376. ** Print the timing results.
  377. */
  378. static void endTimer(void){
  379.   if( enableTimer && getProcessTimesAddr){
  380.     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  381.     sqlite3_int64 ftWallEnd = timeOfDay();
  382.     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  383.     printf("Run Time: real %.3f user %f sys %f\n",
  384.        (ftWallEnd - ftWallBegin)*0.001,
  385.        timeDiff(&ftUserBegin, &ftUserEnd),
  386.        timeDiff(&ftKernelBegin, &ftKernelEnd));
  387.   }
  388. }
  389.  
  390. #define BEGIN_TIMER beginTimer()
  391. #define END_TIMER endTimer()
  392. #define HAS_TIMER hasTimer()
  393.  
  394. #else
  395. #define BEGIN_TIMER
  396. #define END_TIMER
  397. #define HAS_TIMER 0
  398. #endif
  399.  
  400. /*
  401. ** Used to prevent warnings about unused parameters
  402. */
  403. #define UNUSED_PARAMETER(x) (void)(x)
  404.  
  405. /*
  406. ** Number of elements in an array
  407. */
  408. #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
  409.  
  410. /*
  411. ** If the following flag is set, then command execution stops
  412. ** at an error if we are not interactive.
  413. */
  414. static int bail_on_error = 0;
  415.  
  416. /*
  417. ** Threat stdin as an interactive input if the following variable
  418. ** is true.  Otherwise, assume stdin is connected to a file or pipe.
  419. */
  420. static int stdin_is_interactive = 1;
  421.  
  422. /*
  423. ** On Windows systems we have to know if standard output is a console
  424. ** in order to translate UTF-8 into MBCS.  The following variable is
  425. ** true if translation is required.
  426. */
  427. static int stdout_is_console = 1;
  428.  
  429. /*
  430. ** The following is the open SQLite database.  We make a pointer
  431. ** to this database a static variable so that it can be accessed
  432. ** by the SIGINT handler to interrupt database processing.
  433. */
  434. static sqlite3 *globalDb = 0;
  435.  
  436. /*
  437. ** True if an interrupt (Control-C) has been received.
  438. */
  439. static volatile int seenInterrupt = 0;
  440.  
  441. #ifdef SQLITE_DEBUG
  442. /*
  443. ** Out-of-memory simulator variables
  444. */
  445. static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
  446. static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
  447. static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
  448. #endif /* SQLITE_DEBUG */
  449.  
  450. /*
  451. ** This is the name of our program. It is set in main(), used
  452. ** in a number of other places, mostly for error messages.
  453. */
  454. static char *Argv0;
  455.  
  456. /*
  457. ** Prompt strings. Initialized in main. Settable with
  458. **   .prompt main continue
  459. */
  460. static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
  461. static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
  462.  
  463. /*
  464. ** Render output like fprintf().  Except, if the output is going to the
  465. ** console and if this is running on a Windows machine, translate the
  466. ** output from UTF-8 into MBCS.
  467. */
  468. #if defined(_WIN32) || defined(WIN32)
  469. void utf8_printf(FILE *out, const char *zFormat, ...){
  470.   va_list ap;
  471.   va_start(ap, zFormat);
  472.   if( stdout_is_console && (out==stdout || out==stderr) ){
  473.     char *z1 = sqlite3_vmprintf(zFormat, ap);
  474.     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  475.     sqlite3_free(z1);
  476.     fputs(z2, out);
  477.     sqlite3_free(z2);
  478.   }else{
  479.     vfprintf(out, zFormat, ap);
  480.   }
  481.   va_end(ap);
  482. }
  483. #elif !defined(utf8_printf)
  484. # define utf8_printf fprintf
  485. #endif
  486.  
  487. /*
  488. ** Render output like fprintf().  This should not be used on anything that
  489. ** includes string formatting (e.g. "%s").
  490. */
  491. #if !defined(raw_printf)
  492. # define raw_printf fprintf
  493. #endif
  494.  
  495. /* Indicate out-of-memory and exit. */
  496. static void shell_out_of_memory(void){
  497.   raw_printf(stderr,"Error: out of memory\n");
  498.   exit(1);
  499. }
  500.  
  501. #ifdef SQLITE_DEBUG
  502. /* This routine is called when a simulated OOM occurs.  It is broken
  503. ** out as a separate routine to make it easy to set a breakpoint on
  504. ** the OOM
  505. */
  506. void shellOomFault(void){
  507.   if( oomRepeat>0 ){
  508.     oomRepeat--;
  509.   }else{
  510.     oomCounter--;
  511.   }
  512. }
  513. #endif /* SQLITE_DEBUG */
  514.  
  515. #ifdef SQLITE_DEBUG
  516. /* This routine is a replacement malloc() that is used to simulate
  517. ** Out-Of-Memory (OOM) errors for testing purposes.
  518. */
  519. static void *oomMalloc(int nByte){
  520.   if( oomCounter ){
  521.     if( oomCounter==1 ){
  522.       shellOomFault();
  523.       return 0;
  524.     }else{
  525.       oomCounter--;
  526.     }
  527.   }
  528.   return defaultMalloc(nByte);
  529. }
  530. #endif /* SQLITE_DEBUG */
  531.  
  532. #ifdef SQLITE_DEBUG
  533. /* Register the OOM simulator.  This must occur before any memory
  534. ** allocations */
  535. static void registerOomSimulator(void){
  536.   sqlite3_mem_methods mem;
  537.   sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
  538.   defaultMalloc = mem.xMalloc;
  539.   mem.xMalloc = oomMalloc;
  540.   sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
  541. }
  542. #endif
  543.  
  544. /*
  545. ** Write I/O traces to the following stream.
  546. */
  547. #ifdef SQLITE_ENABLE_IOTRACE
  548. static FILE *iotrace = 0;
  549. #endif
  550.  
  551. /*
  552. ** This routine works like printf in that its first argument is a
  553. ** format string and subsequent arguments are values to be substituted
  554. ** in place of % fields.  The result of formatting this string
  555. ** is written to iotrace.
  556. */
  557. #ifdef SQLITE_ENABLE_IOTRACE
  558. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  559.   va_list ap;
  560.   char *z;
  561.   if( iotrace==0 ) return;
  562.   va_start(ap, zFormat);
  563.   z = sqlite3_vmprintf(zFormat, ap);
  564.   va_end(ap);
  565.   utf8_printf(iotrace, "%s", z);
  566.   sqlite3_free(z);
  567. }
  568. #endif
  569.  
  570. /*
  571. ** Output string zUtf to stream pOut as w characters.  If w is negative,
  572. ** then right-justify the text.  W is the width in UTF-8 characters, not
  573. ** in bytes.  This is different from the %*.*s specification in printf
  574. ** since with %*.*s the width is measured in bytes, not characters.
  575. */
  576. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  577.   int i;
  578.   int n;
  579.   int aw = w<0 ? -w : w;
  580.   for(i=n=0; zUtf[i]; i++){
  581.     if( (zUtf[i]&0xc0)!=0x80 ){
  582.       n++;
  583.       if( n==aw ){
  584.         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  585.         break;
  586.       }
  587.     }
  588.   }
  589.   if( n>=aw ){
  590.     utf8_printf(pOut, "%.*s", i, zUtf);
  591.   }else if( w<0 ){
  592.     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  593.   }else{
  594.     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  595.   }
  596. }
  597.  
  598.  
  599. /*
  600. ** Determines if a string is a number of not.
  601. */
  602. static int isNumber(const char *z, int *realnum){
  603.   if( *z=='-' || *z=='+' ) z++;
  604.   if( !IsDigit(*z) ){
  605.     return 0;
  606.   }
  607.   z++;
  608.   if( realnum ) *realnum = 0;
  609.   while( IsDigit(*z) ){ z++; }
  610.   if( *z=='.' ){
  611.     z++;
  612.     if( !IsDigit(*z) ) return 0;
  613.     while( IsDigit(*z) ){ z++; }
  614.     if( realnum ) *realnum = 1;
  615.   }
  616.   if( *z=='e' || *z=='E' ){
  617.     z++;
  618.     if( *z=='+' || *z=='-' ) z++;
  619.     if( !IsDigit(*z) ) return 0;
  620.     while( IsDigit(*z) ){ z++; }
  621.     if( realnum ) *realnum = 1;
  622.   }
  623.   return *z==0;
  624. }
  625.  
  626. /*
  627. ** Compute a string length that is limited to what can be stored in
  628. ** lower 30 bits of a 32-bit signed integer.
  629. */
  630. static int strlen30(const char *z){
  631.   const char *z2 = z;
  632.   while( *z2 ){ z2++; }
  633.   return 0x3fffffff & (int)(z2 - z);
  634. }
  635.  
  636. /*
  637. ** Return the length of a string in characters.  Multibyte UTF8 characters
  638. ** count as a single character.
  639. */
  640. static int strlenChar(const char *z){
  641.   int n = 0;
  642.   while( *z ){
  643.     if( (0xc0&*(z++))!=0x80 ) n++;
  644.   }
  645.   return n;
  646. }
  647.  
  648. /*
  649. ** Return true if zFile does not exist or if it is not an ordinary file.
  650. */
  651. #ifdef _WIN32
  652. # define notNormalFile(X) 0
  653. #else
  654. static int notNormalFile(const char *zFile){
  655.   struct stat x;
  656.   int rc;
  657.   memset(&x, 0, sizeof(x));
  658.   rc = stat(zFile, &x);
  659.   return rc || !S_ISREG(x.st_mode);
  660. }
  661. #endif
  662.  
  663. /*
  664. ** This routine reads a line of text from FILE in, stores
  665. ** the text in memory obtained from malloc() and returns a pointer
  666. ** to the text.  NULL is returned at end of file, or if malloc()
  667. ** fails.
  668. **
  669. ** If zLine is not NULL then it is a malloced buffer returned from
  670. ** a previous call to this routine that may be reused.
  671. */
  672. static char *local_getline(char *zLine, FILE *in){
  673.   int nLine = zLine==0 ? 0 : 100;
  674.   int n = 0;
  675.  
  676.   while( 1 ){
  677.     if( n+100>nLine ){
  678.       nLine = nLine*2 + 100;
  679.       zLine = realloc(zLine, nLine);
  680.       if( zLine==0 ) shell_out_of_memory();
  681.     }
  682.     if( fgets(&zLine[n], nLine - n, in)==0 ){
  683.       if( n==0 ){
  684.         free(zLine);
  685.         return 0;
  686.       }
  687.       zLine[n] = 0;
  688.       break;
  689.     }
  690.     while( zLine[n] ) n++;
  691.     if( n>0 && zLine[n-1]=='\n' ){
  692.       n--;
  693.       if( n>0 && zLine[n-1]=='\r' ) n--;
  694.       zLine[n] = 0;
  695.       break;
  696.     }
  697.   }
  698. #if defined(_WIN32) || defined(WIN32)
  699.   /* For interactive input on Windows systems, translate the
  700.   ** multi-byte characterset characters into UTF-8. */
  701.   if( stdin_is_interactive && in==stdin ){
  702.     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  703.     if( zTrans ){
  704.       int nTrans = strlen30(zTrans)+1;
  705.       if( nTrans>nLine ){
  706.         zLine = realloc(zLine, nTrans);
  707.         if( zLine==0 ) shell_out_of_memory();
  708.       }
  709.       memcpy(zLine, zTrans, nTrans);
  710.       sqlite3_free(zTrans);
  711.     }
  712.   }
  713. #endif /* defined(_WIN32) || defined(WIN32) */
  714.   return zLine;
  715. }
  716.  
  717. /*
  718. ** Retrieve a single line of input text.
  719. **
  720. ** If in==0 then read from standard input and prompt before each line.
  721. ** If isContinuation is true, then a continuation prompt is appropriate.
  722. ** If isContinuation is zero, then the main prompt should be used.
  723. **
  724. ** If zPrior is not NULL then it is a buffer from a prior call to this
  725. ** routine that can be reused.
  726. **
  727. ** The result is stored in space obtained from malloc() and must either
  728. ** be freed by the caller or else passed back into this routine via the
  729. ** zPrior argument for reuse.
  730. */
  731. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  732.   char *zPrompt;
  733.   char *zResult;
  734.   if( in!=0 ){
  735.     zResult = local_getline(zPrior, in);
  736.   }else{
  737.     zPrompt = isContinuation ? continuePrompt : mainPrompt;
  738. #if SHELL_USE_LOCAL_GETLINE
  739.     printf("%s", zPrompt);
  740.     fflush(stdout);
  741.     zResult = local_getline(zPrior, stdin);
  742. #else
  743.     free(zPrior);
  744.     zResult = shell_readline(zPrompt);
  745.     if( zResult && *zResult ) shell_add_history(zResult);
  746. #endif
  747.   }
  748.   return zResult;
  749. }
  750.  
  751.  
  752. /*
  753. ** Return the value of a hexadecimal digit.  Return -1 if the input
  754. ** is not a hex digit.
  755. */
  756. static int hexDigitValue(char c){
  757.   if( c>='0' && c<='9' ) return c - '0';
  758.   if( c>='a' && c<='f' ) return c - 'a' + 10;
  759.   if( c>='A' && c<='F' ) return c - 'A' + 10;
  760.   return -1;
  761. }
  762.  
  763. /*
  764. ** Interpret zArg as an integer value, possibly with suffixes.
  765. */
  766. static sqlite3_int64 integerValue(const char *zArg){
  767.   sqlite3_int64 v = 0;
  768.   static const struct { char *zSuffix; int iMult; } aMult[] = {
  769.     { "KiB", 1024 },
  770.     { "MiB", 1024*1024 },
  771.     { "GiB", 1024*1024*1024 },
  772.     { "KB",  1000 },
  773.     { "MB",  1000000 },
  774.     { "GB",  1000000000 },
  775.     { "K",   1000 },
  776.     { "M",   1000000 },
  777.     { "G",   1000000000 },
  778.   };
  779.   int i;
  780.   int isNeg = 0;
  781.   if( zArg[0]=='-' ){
  782.     isNeg = 1;
  783.     zArg++;
  784.   }else if( zArg[0]=='+' ){
  785.     zArg++;
  786.   }
  787.   if( zArg[0]=='0' && zArg[1]=='x' ){
  788.     int x;
  789.     zArg += 2;
  790.     while( (x = hexDigitValue(zArg[0]))>=0 ){
  791.       v = (v<<4) + x;
  792.       zArg++;
  793.     }
  794.   }else{
  795.     while( IsDigit(zArg[0]) ){
  796.       v = v*10 + zArg[0] - '0';
  797.       zArg++;
  798.     }
  799.   }
  800.   for(i=0; i<ArraySize(aMult); i++){
  801.     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  802.       v *= aMult[i].iMult;
  803.       break;
  804.     }
  805.   }
  806.   return isNeg? -v : v;
  807. }
  808.  
  809. /*
  810. ** A variable length string to which one can append text.
  811. */
  812. typedef struct ShellText ShellText;
  813. struct ShellText {
  814.   char *z;
  815.   int n;
  816.   int nAlloc;
  817. };
  818.  
  819. /*
  820. ** Initialize and destroy a ShellText object
  821. */
  822. static void initText(ShellText *p){
  823.   memset(p, 0, sizeof(*p));
  824. }
  825. static void freeText(ShellText *p){
  826.   free(p->z);
  827.   initText(p);
  828. }
  829.  
  830. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  831. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  832. ** added to zIn, and the result returned in memory obtained from malloc().
  833. ** zIn, if it was not NULL, is freed.
  834. **
  835. ** If the third argument, quote, is not '\0', then it is used as a
  836. ** quote character for zAppend.
  837. */
  838. static void appendText(ShellText *p, char const *zAppend, char quote){
  839.   int len;
  840.   int i;
  841.   int nAppend = strlen30(zAppend);
  842.  
  843.   len = nAppend+p->n+1;
  844.   if( quote ){
  845.     len += 2;
  846.     for(i=0; i<nAppend; i++){
  847.       if( zAppend[i]==quote ) len++;
  848.     }
  849.   }
  850.  
  851.   if( p->n+len>=p->nAlloc ){
  852.     p->nAlloc = p->nAlloc*2 + len + 20;
  853.     p->z = realloc(p->z, p->nAlloc);
  854.     if( p->z==0 ) shell_out_of_memory();
  855.   }
  856.  
  857.   if( quote ){
  858.     char *zCsr = p->z+p->n;
  859.     *zCsr++ = quote;
  860.     for(i=0; i<nAppend; i++){
  861.       *zCsr++ = zAppend[i];
  862.       if( zAppend[i]==quote ) *zCsr++ = quote;
  863.     }
  864.     *zCsr++ = quote;
  865.     p->n = (int)(zCsr - p->z);
  866.     *zCsr = '\0';
  867.   }else{
  868.     memcpy(p->z+p->n, zAppend, nAppend);
  869.     p->n += nAppend;
  870.     p->z[p->n] = '\0';
  871.   }
  872. }
  873.  
  874. /*
  875. ** Attempt to determine if identifier zName needs to be quoted, either
  876. ** because it contains non-alphanumeric characters, or because it is an
  877. ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
  878. ** that quoting is required.
  879. **
  880. ** Return '"' if quoting is required.  Return 0 if no quoting is required.
  881. */
  882. static char quoteChar(const char *zName){
  883.   int i;
  884.   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  885.   for(i=0; zName[i]; i++){
  886.     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  887.   }
  888.   return sqlite3_keyword_check(zName, i) ? '"' : 0;
  889. }
  890.  
  891. /*
  892. ** Construct a fake object name and column list to describe the structure
  893. ** of the view, virtual table, or table valued function zSchema.zName.
  894. */
  895. static char *shellFakeSchema(
  896.   sqlite3 *db,            /* The database connection containing the vtab */
  897.   const char *zSchema,    /* Schema of the database holding the vtab */
  898.   const char *zName       /* The name of the virtual table */
  899. ){
  900.   sqlite3_stmt *pStmt = 0;
  901.   char *zSql;
  902.   ShellText s;
  903.   char cQuote;
  904.   char *zDiv = "(";
  905.   int nRow = 0;
  906.  
  907.   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  908.                          zSchema ? zSchema : "main", zName);
  909.   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  910.   sqlite3_free(zSql);
  911.   initText(&s);
  912.   if( zSchema ){
  913.     cQuote = quoteChar(zSchema);
  914.     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  915.     appendText(&s, zSchema, cQuote);
  916.     appendText(&s, ".", 0);
  917.   }
  918.   cQuote = quoteChar(zName);
  919.   appendText(&s, zName, cQuote);
  920.   while( sqlite3_step(pStmt)==SQLITE_ROW ){
  921.     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  922.     nRow++;
  923.     appendText(&s, zDiv, 0);
  924.     zDiv = ",";
  925.     cQuote = quoteChar(zCol);
  926.     appendText(&s, zCol, cQuote);
  927.   }
  928.   appendText(&s, ")", 0);
  929.   sqlite3_finalize(pStmt);
  930.   if( nRow==0 ){
  931.     freeText(&s);
  932.     s.z = 0;
  933.   }
  934.   return s.z;
  935. }
  936.  
  937. /*
  938. ** SQL function:  shell_module_schema(X)
  939. **
  940. ** Return a fake schema for the table-valued function or eponymous virtual
  941. ** table X.
  942. */
  943. static void shellModuleSchema(
  944.   sqlite3_context *pCtx,
  945.   int nVal,
  946.   sqlite3_value **apVal
  947. ){
  948.   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
  949.   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
  950.   UNUSED_PARAMETER(nVal);
  951.   if( zFake ){
  952.     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  953.                         -1, sqlite3_free);
  954.     free(zFake);
  955.   }
  956. }
  957.  
  958. /*
  959. ** SQL function:  shell_add_schema(S,X)
  960. **
  961. ** Add the schema name X to the CREATE statement in S and return the result.
  962. ** Examples:
  963. **
  964. **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
  965. **
  966. ** Also works on
  967. **
  968. **    CREATE INDEX
  969. **    CREATE UNIQUE INDEX
  970. **    CREATE VIEW
  971. **    CREATE TRIGGER
  972. **    CREATE VIRTUAL TABLE
  973. **
  974. ** This UDF is used by the .schema command to insert the schema name of
  975. ** attached databases into the middle of the sqlite_schema.sql field.
  976. */
  977. static void shellAddSchemaName(
  978.   sqlite3_context *pCtx,
  979.   int nVal,
  980.   sqlite3_value **apVal
  981. ){
  982.   static const char *aPrefix[] = {
  983.      "TABLE",
  984.      "INDEX",
  985.      "UNIQUE INDEX",
  986.      "VIEW",
  987.      "TRIGGER",
  988.      "VIRTUAL TABLE"
  989.   };
  990.   int i = 0;
  991.   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  992.   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  993.   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  994.   sqlite3 *db = sqlite3_context_db_handle(pCtx);
  995.   UNUSED_PARAMETER(nVal);
  996.   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  997.     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
  998.       int n = strlen30(aPrefix[i]);
  999.       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  1000.         char *z = 0;
  1001.         char *zFake = 0;
  1002.         if( zSchema ){
  1003.           char cQuote = quoteChar(zSchema);
  1004.           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  1005.             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  1006.           }else{
  1007.             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  1008.           }
  1009.         }
  1010.         if( zName
  1011.          && aPrefix[i][0]=='V'
  1012.          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  1013.         ){
  1014.           if( z==0 ){
  1015.             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  1016.           }else{
  1017.             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  1018.           }
  1019.           free(zFake);
  1020.         }
  1021.         if( z ){
  1022.           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  1023.           return;
  1024.         }
  1025.       }
  1026.     }
  1027.   }
  1028.   sqlite3_result_value(pCtx, apVal[0]);
  1029. }
  1030.  
  1031. /*
  1032. ** The source code for several run-time loadable extensions is inserted
  1033. ** below by the ../tool/mkshellc.tcl script.  Before processing that included
  1034. ** code, we need to override some macros to make the included program code
  1035. ** work here in the middle of this regular program.
  1036. */
  1037. #define SQLITE_EXTENSION_INIT1
  1038. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  1039.  
  1040. #if defined(_WIN32) && defined(_MSC_VER)
  1041. /************************* Begin test_windirent.h ******************/
  1042. /*
  1043. ** 2015 November 30
  1044. **
  1045. ** The author disclaims copyright to this source code.  In place of
  1046. ** a legal notice, here is a blessing:
  1047. **
  1048. **    May you do good and not evil.
  1049. **    May you find forgiveness for yourself and forgive others.
  1050. **    May you share freely, never taking more than you give.
  1051. **
  1052. *************************************************************************
  1053. ** This file contains declarations for most of the opendir() family of
  1054. ** POSIX functions on Win32 using the MSVCRT.
  1055. */
  1056.  
  1057. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  1058. #define SQLITE_WINDIRENT_H
  1059.  
  1060. /*
  1061. ** We need several data types from the Windows SDK header.
  1062. */
  1063.  
  1064. #ifndef WIN32_LEAN_AND_MEAN
  1065. #define WIN32_LEAN_AND_MEAN
  1066. #endif
  1067.  
  1068. //#include "windows.h"
  1069.  
  1070. /*
  1071. ** We need several support functions from the SQLite core.
  1072. */
  1073.  
  1074. /* #include "sqlite3.h" */
  1075.  
  1076. /*
  1077. ** We need several things from the ANSI and MSVCRT headers.
  1078. */
  1079.  
  1080. #include <stdio.h>
  1081. #include <stdlib.h>
  1082. #include <errno.h>
  1083. #include <io.h>
  1084. #include <limits.h>
  1085. #include <sys/types.h>
  1086. #include <sys/stat.h>
  1087.  
  1088. /*
  1089. ** We may need several defines that should have been in "sys/stat.h".
  1090. */
  1091.  
  1092. #ifndef S_ISREG
  1093. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  1094. #endif
  1095.  
  1096. #ifndef S_ISDIR
  1097. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  1098. #endif
  1099.  
  1100. #ifndef S_ISLNK
  1101. #define S_ISLNK(mode) (0)
  1102. #endif
  1103.  
  1104. /*
  1105. ** We may need to provide the "mode_t" type.
  1106. */
  1107.  
  1108. #ifndef MODE_T_DEFINED
  1109.   #define MODE_T_DEFINED
  1110.   typedef unsigned short mode_t;
  1111. #endif
  1112.  
  1113. /*
  1114. ** We may need to provide the "ino_t" type.
  1115. */
  1116.  
  1117. #ifndef INO_T_DEFINED
  1118.   #define INO_T_DEFINED
  1119.   typedef unsigned short ino_t;
  1120. #endif
  1121.  
  1122. /*
  1123. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  1124. */
  1125.  
  1126. #ifndef NAME_MAX
  1127. #  ifdef FILENAME_MAX
  1128. #    define NAME_MAX (FILENAME_MAX)
  1129. #  else
  1130. #    define NAME_MAX (260)
  1131. #  endif
  1132. #endif
  1133.  
  1134. /*
  1135. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  1136. */
  1137.  
  1138. #ifndef NULL_INTPTR_T
  1139. #  define NULL_INTPTR_T ((intptr_t)(0))
  1140. #endif
  1141.  
  1142. #ifndef BAD_INTPTR_T
  1143. #  define BAD_INTPTR_T ((intptr_t)(-1))
  1144. #endif
  1145.  
  1146. /*
  1147. ** We need to provide the necessary structures and related types.
  1148. */
  1149.  
  1150. #ifndef DIRENT_DEFINED
  1151. #define DIRENT_DEFINED
  1152. typedef struct DIRENT DIRENT;
  1153. typedef DIRENT *LPDIRENT;
  1154. struct DIRENT {
  1155.   ino_t d_ino;               /* Sequence number, do not use. */
  1156.   unsigned d_attributes;     /* Win32 file attributes. */
  1157.   char d_name[NAME_MAX + 1]; /* Name within the directory. */
  1158. };
  1159. #endif
  1160.  
  1161. #ifndef DIR_DEFINED
  1162. #define DIR_DEFINED
  1163. typedef struct DIR DIR;
  1164. typedef DIR *LPDIR;
  1165. struct DIR {
  1166.   intptr_t d_handle; /* Value returned by "_findfirst". */
  1167.   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
  1168.   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
  1169. };
  1170. #endif
  1171.  
  1172. /*
  1173. ** Provide a macro, for use by the implementation, to determine if a
  1174. ** particular directory entry should be skipped over when searching for
  1175. ** the next directory entry that should be returned by the readdir() or
  1176. ** readdir_r() functions.
  1177. */
  1178.  
  1179. #ifndef is_filtered
  1180. #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  1181. #endif
  1182.  
  1183. /*
  1184. ** Provide the function prototype for the POSIX compatiable getenv()
  1185. ** function.  This function is not thread-safe.
  1186. */
  1187.  
  1188. extern const char *windirent_getenv(const char *name);
  1189.  
  1190. /*
  1191. ** Finally, we can provide the function prototypes for the opendir(),
  1192. ** readdir(), readdir_r(), and closedir() POSIX functions.
  1193. */
  1194.  
  1195. extern LPDIR opendir(const char *dirname);
  1196. extern LPDIRENT readdir(LPDIR dirp);
  1197. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  1198. extern INT closedir(LPDIR dirp);
  1199.  
  1200. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1201.  
  1202. /************************* End test_windirent.h ********************/
  1203. /************************* Begin test_windirent.c ******************/
  1204. /*
  1205. ** 2015 November 30
  1206. **
  1207. ** The author disclaims copyright to this source code.  In place of
  1208. ** a legal notice, here is a blessing:
  1209. **
  1210. **    May you do good and not evil.
  1211. **    May you find forgiveness for yourself and forgive others.
  1212. **    May you share freely, never taking more than you give.
  1213. **
  1214. *************************************************************************
  1215. ** This file contains code to implement most of the opendir() family of
  1216. ** POSIX functions on Win32 using the MSVCRT.
  1217. */
  1218.  
  1219. #if defined(_WIN32) && defined(_MSC_VER)
  1220. /* #include "test_windirent.h" */
  1221.  
  1222. /*
  1223. ** Implementation of the POSIX getenv() function using the Win32 API.
  1224. ** This function is not thread-safe.
  1225. */
  1226. const char *windirent_getenv(
  1227.   const char *name
  1228. ){
  1229.   static char value[32768]; /* Maximum length, per MSDN */
  1230.   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1231.   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1232.  
  1233.   memset(value, 0, sizeof(value));
  1234.   dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1235.   if( dwRet==0 || dwRet>dwSize ){
  1236.     /*
  1237.     ** The function call to GetEnvironmentVariableA() failed -OR-
  1238.     ** the buffer is not large enough.  Either way, return NULL.
  1239.     */
  1240.     return 0;
  1241.   }else{
  1242.     /*
  1243.     ** The function call to GetEnvironmentVariableA() succeeded
  1244.     ** -AND- the buffer contains the entire value.
  1245.     */
  1246.     return value;
  1247.   }
  1248. }
  1249.  
  1250. /*
  1251. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1252. */
  1253. LPDIR opendir(
  1254.   const char *dirname
  1255. ){
  1256.   struct _finddata_t data;
  1257.   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1258.   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1259.  
  1260.   if( dirp==NULL ) return NULL;
  1261.   memset(dirp, 0, sizeof(DIR));
  1262.  
  1263.   /* TODO: Remove this if Unix-style root paths are not used. */
  1264.   if( sqlite3_stricmp(dirname, "/")==0 ){
  1265.     dirname = windirent_getenv("SystemDrive");
  1266.   }
  1267.  
  1268.   memset(&data, 0, sizeof(struct _finddata_t));
  1269.   _snprintf(data.name, namesize, "%s\\*", dirname);
  1270.   dirp->d_handle = _findfirst(data.name, &data);
  1271.  
  1272.   if( dirp->d_handle==BAD_INTPTR_T ){
  1273.     closedir(dirp);
  1274.     return NULL;
  1275.   }
  1276.  
  1277.   /* TODO: Remove this block to allow hidden and/or system files. */
  1278.   if( is_filtered(data) ){
  1279. next:
  1280.  
  1281.     memset(&data, 0, sizeof(struct _finddata_t));
  1282.     if( _findnext(dirp->d_handle, &data)==-1 ){
  1283.       closedir(dirp);
  1284.       return NULL;
  1285.     }
  1286.  
  1287.     /* TODO: Remove this block to allow hidden and/or system files. */
  1288.     if( is_filtered(data) ) goto next;
  1289.   }
  1290.  
  1291.   dirp->d_first.d_attributes = data.attrib;
  1292.   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1293.   dirp->d_first.d_name[NAME_MAX] = '\0';
  1294.  
  1295.   return dirp;
  1296. }
  1297.  
  1298. /*
  1299. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1300. */
  1301. LPDIRENT readdir(
  1302.   LPDIR dirp
  1303. ){
  1304.   struct _finddata_t data;
  1305.  
  1306.   if( dirp==NULL ) return NULL;
  1307.  
  1308.   if( dirp->d_first.d_ino==0 ){
  1309.     dirp->d_first.d_ino++;
  1310.     dirp->d_next.d_ino++;
  1311.  
  1312.     return &dirp->d_first;
  1313.   }
  1314.  
  1315. next:
  1316.  
  1317.   memset(&data, 0, sizeof(struct _finddata_t));
  1318.   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1319.  
  1320.   /* TODO: Remove this block to allow hidden and/or system files. */
  1321.   if( is_filtered(data) ) goto next;
  1322.  
  1323.   dirp->d_next.d_ino++;
  1324.   dirp->d_next.d_attributes = data.attrib;
  1325.   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1326.   dirp->d_next.d_name[NAME_MAX] = '\0';
  1327.  
  1328.   return &dirp->d_next;
  1329. }
  1330.  
  1331. /*
  1332. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1333. */
  1334. INT readdir_r(
  1335.   LPDIR dirp,
  1336.   LPDIRENT entry,
  1337.   LPDIRENT *result
  1338. ){
  1339.   struct _finddata_t data;
  1340.  
  1341.   if( dirp==NULL ) return EBADF;
  1342.  
  1343.   if( dirp->d_first.d_ino==0 ){
  1344.     dirp->d_first.d_ino++;
  1345.     dirp->d_next.d_ino++;
  1346.  
  1347.     entry->d_ino = dirp->d_first.d_ino;
  1348.     entry->d_attributes = dirp->d_first.d_attributes;
  1349.     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1350.     entry->d_name[NAME_MAX] = '\0';
  1351.  
  1352.     *result = entry;
  1353.     return 0;
  1354.   }
  1355.  
  1356. next:
  1357.  
  1358.   memset(&data, 0, sizeof(struct _finddata_t));
  1359.   if( _findnext(dirp->d_handle, &data)==-1 ){
  1360.     *result = NULL;
  1361.     return ENOENT;
  1362.   }
  1363.  
  1364.   /* TODO: Remove this block to allow hidden and/or system files. */
  1365.   if( is_filtered(data) ) goto next;
  1366.  
  1367.   entry->d_ino = (ino_t)-1; /* not available */
  1368.   entry->d_attributes = data.attrib;
  1369.   strncpy(entry->d_name, data.name, NAME_MAX);
  1370.   entry->d_name[NAME_MAX] = '\0';
  1371.  
  1372.   *result = entry;
  1373.   return 0;
  1374. }
  1375.  
  1376. /*
  1377. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1378. */
  1379. INT closedir(
  1380.   LPDIR dirp
  1381. ){
  1382.   INT result = 0;
  1383.  
  1384.   if( dirp==NULL ) return EINVAL;
  1385.  
  1386.   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1387.     result = _findclose(dirp->d_handle);
  1388.   }
  1389.  
  1390.   sqlite3_free(dirp);
  1391.   return result;
  1392. }
  1393.  
  1394. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1395.  
  1396. /************************* End test_windirent.c ********************/
  1397. #define dirent DIRENT
  1398. #endif
  1399. /************************* Begin ../ext/misc/shathree.c ******************/
  1400. /*
  1401. ** 2017-03-08
  1402. **
  1403. ** The author disclaims copyright to this source code.  In place of
  1404. ** a legal notice, here is a blessing:
  1405. **
  1406. **    May you do good and not evil.
  1407. **    May you find forgiveness for yourself and forgive others.
  1408. **    May you share freely, never taking more than you give.
  1409. **
  1410. ******************************************************************************
  1411. **
  1412. ** This SQLite extension implements functions that compute SHA3 hashes.
  1413. ** Two SQL functions are implemented:
  1414. **
  1415. **     sha3(X,SIZE)
  1416. **     sha3_query(Y,SIZE)
  1417. **
  1418. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1419. ** X is NULL.
  1420. **
  1421. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  1422. ** and returns a hash of their results.
  1423. **
  1424. ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
  1425. ** is used.  If SIZE is included it must be one of the integers 224, 256,
  1426. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1427. */
  1428. /* #include "sqlite3ext.h" */
  1429. SQLITE_EXTENSION_INIT1
  1430. #include <assert.h>
  1431. #include <string.h>
  1432. #include <stdarg.h>
  1433.  
  1434. #ifndef SQLITE_AMALGAMATION
  1435. /* typedef sqlite3_uint64 u64; */
  1436. #endif /* SQLITE_AMALGAMATION */
  1437.  
  1438. /******************************************************************************
  1439. ** The Hash Engine
  1440. */
  1441. /*
  1442. ** Macros to determine whether the machine is big or little endian,
  1443. ** and whether or not that determination is run-time or compile-time.
  1444. **
  1445. ** For best performance, an attempt is made to guess at the byte-order
  1446. ** using C-preprocessor macros.  If that is unsuccessful, or if
  1447. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1448. ** at run-time.
  1449. */
  1450. #ifndef SHA3_BYTEORDER
  1451. # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
  1452.      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
  1453.      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
  1454.      defined(__arm__)
  1455. #   define SHA3_BYTEORDER    1234
  1456. # elif defined(sparc)    || defined(__ppc__)
  1457. #   define SHA3_BYTEORDER    4321
  1458. # else
  1459. #   define SHA3_BYTEORDER 0
  1460. # endif
  1461. #endif
  1462.  
  1463.  
  1464. /*
  1465. ** State structure for a SHA3 hash in progress
  1466. */
  1467. typedef struct SHA3Context SHA3Context;
  1468. struct SHA3Context {
  1469.   union {
  1470.     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
  1471.     unsigned char x[1600];    /* ... or 1600 bytes */
  1472.   } u;
  1473.   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
  1474.   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
  1475.   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
  1476. };
  1477.  
  1478. /*
  1479. ** A single step of the Keccak mixing function for a 1600-bit state
  1480. */
  1481. static void KeccakF1600Step(SHA3Context *p){
  1482.   int i;
  1483.   u64 b0, b1, b2, b3, b4;
  1484.   u64 c0, c1, c2, c3, c4;
  1485.   u64 d0, d1, d2, d3, d4;
  1486.   static const u64 RC[] = {
  1487.     0x0000000000000001ULL,  0x0000000000008082ULL,
  1488.     0x800000000000808aULL,  0x8000000080008000ULL,
  1489.     0x000000000000808bULL,  0x0000000080000001ULL,
  1490.     0x8000000080008081ULL,  0x8000000000008009ULL,
  1491.     0x000000000000008aULL,  0x0000000000000088ULL,
  1492.     0x0000000080008009ULL,  0x000000008000000aULL,
  1493.     0x000000008000808bULL,  0x800000000000008bULL,
  1494.     0x8000000000008089ULL,  0x8000000000008003ULL,
  1495.     0x8000000000008002ULL,  0x8000000000000080ULL,
  1496.     0x000000000000800aULL,  0x800000008000000aULL,
  1497.     0x8000000080008081ULL,  0x8000000000008080ULL,
  1498.     0x0000000080000001ULL,  0x8000000080008008ULL
  1499.   };
  1500. # define a00 (p->u.s[0])
  1501. # define a01 (p->u.s[1])
  1502. # define a02 (p->u.s[2])
  1503. # define a03 (p->u.s[3])
  1504. # define a04 (p->u.s[4])
  1505. # define a10 (p->u.s[5])
  1506. # define a11 (p->u.s[6])
  1507. # define a12 (p->u.s[7])
  1508. # define a13 (p->u.s[8])
  1509. # define a14 (p->u.s[9])
  1510. # define a20 (p->u.s[10])
  1511. # define a21 (p->u.s[11])
  1512. # define a22 (p->u.s[12])
  1513. # define a23 (p->u.s[13])
  1514. # define a24 (p->u.s[14])
  1515. # define a30 (p->u.s[15])
  1516. # define a31 (p->u.s[16])
  1517. # define a32 (p->u.s[17])
  1518. # define a33 (p->u.s[18])
  1519. # define a34 (p->u.s[19])
  1520. # define a40 (p->u.s[20])
  1521. # define a41 (p->u.s[21])
  1522. # define a42 (p->u.s[22])
  1523. # define a43 (p->u.s[23])
  1524. # define a44 (p->u.s[24])
  1525. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1526.  
  1527.   for(i=0; i<24; i+=4){
  1528.     c0 = a00^a10^a20^a30^a40;
  1529.     c1 = a01^a11^a21^a31^a41;
  1530.     c2 = a02^a12^a22^a32^a42;
  1531.     c3 = a03^a13^a23^a33^a43;
  1532.     c4 = a04^a14^a24^a34^a44;
  1533.     d0 = c4^ROL64(c1, 1);
  1534.     d1 = c0^ROL64(c2, 1);
  1535.     d2 = c1^ROL64(c3, 1);
  1536.     d3 = c2^ROL64(c4, 1);
  1537.     d4 = c3^ROL64(c0, 1);
  1538.  
  1539.     b0 = (a00^d0);
  1540.     b1 = ROL64((a11^d1), 44);
  1541.     b2 = ROL64((a22^d2), 43);
  1542.     b3 = ROL64((a33^d3), 21);
  1543.     b4 = ROL64((a44^d4), 14);
  1544.     a00 =   b0 ^((~b1)&  b2 );
  1545.     a00 ^= RC[i];
  1546.     a11 =   b1 ^((~b2)&  b3 );
  1547.     a22 =   b2 ^((~b3)&  b4 );
  1548.     a33 =   b3 ^((~b4)&  b0 );
  1549.     a44 =   b4 ^((~b0)&  b1 );
  1550.  
  1551.     b2 = ROL64((a20^d0), 3);
  1552.     b3 = ROL64((a31^d1), 45);
  1553.     b4 = ROL64((a42^d2), 61);
  1554.     b0 = ROL64((a03^d3), 28);
  1555.     b1 = ROL64((a14^d4), 20);
  1556.     a20 =   b0 ^((~b1)&  b2 );
  1557.     a31 =   b1 ^((~b2)&  b3 );
  1558.     a42 =   b2 ^((~b3)&  b4 );
  1559.     a03 =   b3 ^((~b4)&  b0 );
  1560.     a14 =   b4 ^((~b0)&  b1 );
  1561.  
  1562.     b4 = ROL64((a40^d0), 18);
  1563.     b0 = ROL64((a01^d1), 1);
  1564.     b1 = ROL64((a12^d2), 6);
  1565.     b2 = ROL64((a23^d3), 25);
  1566.     b3 = ROL64((a34^d4), 8);
  1567.     a40 =   b0 ^((~b1)&  b2 );
  1568.     a01 =   b1 ^((~b2)&  b3 );
  1569.     a12 =   b2 ^((~b3)&  b4 );
  1570.     a23 =   b3 ^((~b4)&  b0 );
  1571.     a34 =   b4 ^((~b0)&  b1 );
  1572.  
  1573.     b1 = ROL64((a10^d0), 36);
  1574.     b2 = ROL64((a21^d1), 10);
  1575.     b3 = ROL64((a32^d2), 15);
  1576.     b4 = ROL64((a43^d3), 56);
  1577.     b0 = ROL64((a04^d4), 27);
  1578.     a10 =   b0 ^((~b1)&  b2 );
  1579.     a21 =   b1 ^((~b2)&  b3 );
  1580.     a32 =   b2 ^((~b3)&  b4 );
  1581.     a43 =   b3 ^((~b4)&  b0 );
  1582.     a04 =   b4 ^((~b0)&  b1 );
  1583.  
  1584.     b3 = ROL64((a30^d0), 41);
  1585.     b4 = ROL64((a41^d1), 2);
  1586.     b0 = ROL64((a02^d2), 62);
  1587.     b1 = ROL64((a13^d3), 55);
  1588.     b2 = ROL64((a24^d4), 39);
  1589.     a30 =   b0 ^((~b1)&  b2 );
  1590.     a41 =   b1 ^((~b2)&  b3 );
  1591.     a02 =   b2 ^((~b3)&  b4 );
  1592.     a13 =   b3 ^((~b4)&  b0 );
  1593.     a24 =   b4 ^((~b0)&  b1 );
  1594.  
  1595.     c0 = a00^a20^a40^a10^a30;
  1596.     c1 = a11^a31^a01^a21^a41;
  1597.     c2 = a22^a42^a12^a32^a02;
  1598.     c3 = a33^a03^a23^a43^a13;
  1599.     c4 = a44^a14^a34^a04^a24;
  1600.     d0 = c4^ROL64(c1, 1);
  1601.     d1 = c0^ROL64(c2, 1);
  1602.     d2 = c1^ROL64(c3, 1);
  1603.     d3 = c2^ROL64(c4, 1);
  1604.     d4 = c3^ROL64(c0, 1);
  1605.  
  1606.     b0 = (a00^d0);
  1607.     b1 = ROL64((a31^d1), 44);
  1608.     b2 = ROL64((a12^d2), 43);
  1609.     b3 = ROL64((a43^d3), 21);
  1610.     b4 = ROL64((a24^d4), 14);
  1611.     a00 =   b0 ^((~b1)&  b2 );
  1612.     a00 ^= RC[i+1];
  1613.     a31 =   b1 ^((~b2)&  b3 );
  1614.     a12 =   b2 ^((~b3)&  b4 );
  1615.     a43 =   b3 ^((~b4)&  b0 );
  1616.     a24 =   b4 ^((~b0)&  b1 );
  1617.  
  1618.     b2 = ROL64((a40^d0), 3);
  1619.     b3 = ROL64((a21^d1), 45);
  1620.     b4 = ROL64((a02^d2), 61);
  1621.     b0 = ROL64((a33^d3), 28);
  1622.     b1 = ROL64((a14^d4), 20);
  1623.     a40 =   b0 ^((~b1)&  b2 );
  1624.     a21 =   b1 ^((~b2)&  b3 );
  1625.     a02 =   b2 ^((~b3)&  b4 );
  1626.     a33 =   b3 ^((~b4)&  b0 );
  1627.     a14 =   b4 ^((~b0)&  b1 );
  1628.  
  1629.     b4 = ROL64((a30^d0), 18);
  1630.     b0 = ROL64((a11^d1), 1);
  1631.     b1 = ROL64((a42^d2), 6);
  1632.     b2 = ROL64((a23^d3), 25);
  1633.     b3 = ROL64((a04^d4), 8);
  1634.     a30 =   b0 ^((~b1)&  b2 );
  1635.     a11 =   b1 ^((~b2)&  b3 );
  1636.     a42 =   b2 ^((~b3)&  b4 );
  1637.     a23 =   b3 ^((~b4)&  b0 );
  1638.     a04 =   b4 ^((~b0)&  b1 );
  1639.  
  1640.     b1 = ROL64((a20^d0), 36);
  1641.     b2 = ROL64((a01^d1), 10);
  1642.     b3 = ROL64((a32^d2), 15);
  1643.     b4 = ROL64((a13^d3), 56);
  1644.     b0 = ROL64((a44^d4), 27);
  1645.     a20 =   b0 ^((~b1)&  b2 );
  1646.     a01 =   b1 ^((~b2)&  b3 );
  1647.     a32 =   b2 ^((~b3)&  b4 );
  1648.     a13 =   b3 ^((~b4)&  b0 );
  1649.     a44 =   b4 ^((~b0)&  b1 );
  1650.  
  1651.     b3 = ROL64((a10^d0), 41);
  1652.     b4 = ROL64((a41^d1), 2);
  1653.     b0 = ROL64((a22^d2), 62);
  1654.     b1 = ROL64((a03^d3), 55);
  1655.     b2 = ROL64((a34^d4), 39);
  1656.     a10 =   b0 ^((~b1)&  b2 );
  1657.     a41 =   b1 ^((~b2)&  b3 );
  1658.     a22 =   b2 ^((~b3)&  b4 );
  1659.     a03 =   b3 ^((~b4)&  b0 );
  1660.     a34 =   b4 ^((~b0)&  b1 );
  1661.  
  1662.     c0 = a00^a40^a30^a20^a10;
  1663.     c1 = a31^a21^a11^a01^a41;
  1664.     c2 = a12^a02^a42^a32^a22;
  1665.     c3 = a43^a33^a23^a13^a03;
  1666.     c4 = a24^a14^a04^a44^a34;
  1667.     d0 = c4^ROL64(c1, 1);
  1668.     d1 = c0^ROL64(c2, 1);
  1669.     d2 = c1^ROL64(c3, 1);
  1670.     d3 = c2^ROL64(c4, 1);
  1671.     d4 = c3^ROL64(c0, 1);
  1672.  
  1673.     b0 = (a00^d0);
  1674.     b1 = ROL64((a21^d1), 44);
  1675.     b2 = ROL64((a42^d2), 43);
  1676.     b3 = ROL64((a13^d3), 21);
  1677.     b4 = ROL64((a34^d4), 14);
  1678.     a00 =   b0 ^((~b1)&  b2 );
  1679.     a00 ^= RC[i+2];
  1680.     a21 =   b1 ^((~b2)&  b3 );
  1681.     a42 =   b2 ^((~b3)&  b4 );
  1682.     a13 =   b3 ^((~b4)&  b0 );
  1683.     a34 =   b4 ^((~b0)&  b1 );
  1684.  
  1685.     b2 = ROL64((a30^d0), 3);
  1686.     b3 = ROL64((a01^d1), 45);
  1687.     b4 = ROL64((a22^d2), 61);
  1688.     b0 = ROL64((a43^d3), 28);
  1689.     b1 = ROL64((a14^d4), 20);
  1690.     a30 =   b0 ^((~b1)&  b2 );
  1691.     a01 =   b1 ^((~b2)&  b3 );
  1692.     a22 =   b2 ^((~b3)&  b4 );
  1693.     a43 =   b3 ^((~b4)&  b0 );
  1694.     a14 =   b4 ^((~b0)&  b1 );
  1695.  
  1696.     b4 = ROL64((a10^d0), 18);
  1697.     b0 = ROL64((a31^d1), 1);
  1698.     b1 = ROL64((a02^d2), 6);
  1699.     b2 = ROL64((a23^d3), 25);
  1700.     b3 = ROL64((a44^d4), 8);
  1701.     a10 =   b0 ^((~b1)&  b2 );
  1702.     a31 =   b1 ^((~b2)&  b3 );
  1703.     a02 =   b2 ^((~b3)&  b4 );
  1704.     a23 =   b3 ^((~b4)&  b0 );
  1705.     a44 =   b4 ^((~b0)&  b1 );
  1706.  
  1707.     b1 = ROL64((a40^d0), 36);
  1708.     b2 = ROL64((a11^d1), 10);
  1709.     b3 = ROL64((a32^d2), 15);
  1710.     b4 = ROL64((a03^d3), 56);
  1711.     b0 = ROL64((a24^d4), 27);
  1712.     a40 =   b0 ^((~b1)&  b2 );
  1713.     a11 =   b1 ^((~b2)&  b3 );
  1714.     a32 =   b2 ^((~b3)&  b4 );
  1715.     a03 =   b3 ^((~b4)&  b0 );
  1716.     a24 =   b4 ^((~b0)&  b1 );
  1717.  
  1718.     b3 = ROL64((a20^d0), 41);
  1719.     b4 = ROL64((a41^d1), 2);
  1720.     b0 = ROL64((a12^d2), 62);
  1721.     b1 = ROL64((a33^d3), 55);
  1722.     b2 = ROL64((a04^d4), 39);
  1723.     a20 =   b0 ^((~b1)&  b2 );
  1724.     a41 =   b1 ^((~b2)&  b3 );
  1725.     a12 =   b2 ^((~b3)&  b4 );
  1726.     a33 =   b3 ^((~b4)&  b0 );
  1727.     a04 =   b4 ^((~b0)&  b1 );
  1728.  
  1729.     c0 = a00^a30^a10^a40^a20;
  1730.     c1 = a21^a01^a31^a11^a41;
  1731.     c2 = a42^a22^a02^a32^a12;
  1732.     c3 = a13^a43^a23^a03^a33;
  1733.     c4 = a34^a14^a44^a24^a04;
  1734.     d0 = c4^ROL64(c1, 1);
  1735.     d1 = c0^ROL64(c2, 1);
  1736.     d2 = c1^ROL64(c3, 1);
  1737.     d3 = c2^ROL64(c4, 1);
  1738.     d4 = c3^ROL64(c0, 1);
  1739.  
  1740.     b0 = (a00^d0);
  1741.     b1 = ROL64((a01^d1), 44);
  1742.     b2 = ROL64((a02^d2), 43);
  1743.     b3 = ROL64((a03^d3), 21);
  1744.     b4 = ROL64((a04^d4), 14);
  1745.     a00 =   b0 ^((~b1)&  b2 );
  1746.     a00 ^= RC[i+3];
  1747.     a01 =   b1 ^((~b2)&  b3 );
  1748.     a02 =   b2 ^((~b3)&  b4 );
  1749.     a03 =   b3 ^((~b4)&  b0 );
  1750.     a04 =   b4 ^((~b0)&  b1 );
  1751.  
  1752.     b2 = ROL64((a10^d0), 3);
  1753.     b3 = ROL64((a11^d1), 45);
  1754.     b4 = ROL64((a12^d2), 61);
  1755.     b0 = ROL64((a13^d3), 28);
  1756.     b1 = ROL64((a14^d4), 20);
  1757.     a10 =   b0 ^((~b1)&  b2 );
  1758.     a11 =   b1 ^((~b2)&  b3 );
  1759.     a12 =   b2 ^((~b3)&  b4 );
  1760.     a13 =   b3 ^((~b4)&  b0 );
  1761.     a14 =   b4 ^((~b0)&  b1 );
  1762.  
  1763.     b4 = ROL64((a20^d0), 18);
  1764.     b0 = ROL64((a21^d1), 1);
  1765.     b1 = ROL64((a22^d2), 6);
  1766.     b2 = ROL64((a23^d3), 25);
  1767.     b3 = ROL64((a24^d4), 8);
  1768.     a20 =   b0 ^((~b1)&  b2 );
  1769.     a21 =   b1 ^((~b2)&  b3 );
  1770.     a22 =   b2 ^((~b3)&  b4 );
  1771.     a23 =   b3 ^((~b4)&  b0 );
  1772.     a24 =   b4 ^((~b0)&  b1 );
  1773.  
  1774.     b1 = ROL64((a30^d0), 36);
  1775.     b2 = ROL64((a31^d1), 10);
  1776.     b3 = ROL64((a32^d2), 15);
  1777.     b4 = ROL64((a33^d3), 56);
  1778.     b0 = ROL64((a34^d4), 27);
  1779.     a30 =   b0 ^((~b1)&  b2 );
  1780.     a31 =   b1 ^((~b2)&  b3 );
  1781.     a32 =   b2 ^((~b3)&  b4 );
  1782.     a33 =   b3 ^((~b4)&  b0 );
  1783.     a34 =   b4 ^((~b0)&  b1 );
  1784.  
  1785.     b3 = ROL64((a40^d0), 41);
  1786.     b4 = ROL64((a41^d1), 2);
  1787.     b0 = ROL64((a42^d2), 62);
  1788.     b1 = ROL64((a43^d3), 55);
  1789.     b2 = ROL64((a44^d4), 39);
  1790.     a40 =   b0 ^((~b1)&  b2 );
  1791.     a41 =   b1 ^((~b2)&  b3 );
  1792.     a42 =   b2 ^((~b3)&  b4 );
  1793.     a43 =   b3 ^((~b4)&  b0 );
  1794.     a44 =   b4 ^((~b0)&  b1 );
  1795.   }
  1796. }
  1797.  
  1798. /*
  1799. ** Initialize a new hash.  iSize determines the size of the hash
  1800. ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
  1801. ** can be zero to use the default hash size of 256 bits.
  1802. */
  1803. static void SHA3Init(SHA3Context *p, int iSize){
  1804.   memset(p, 0, sizeof(*p));
  1805.   if( iSize>=128 && iSize<=512 ){
  1806.     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1807.   }else{
  1808.     p->nRate = (1600 - 2*256)/8;
  1809.   }
  1810. #if SHA3_BYTEORDER==1234
  1811.   /* Known to be little-endian at compile-time. No-op */
  1812. #elif SHA3_BYTEORDER==4321
  1813.   p->ixMask = 7;  /* Big-endian */
  1814. #else
  1815.   {
  1816.     static unsigned int one = 1;
  1817.     if( 1==*(unsigned char*)&one ){
  1818.       /* Little endian.  No byte swapping. */
  1819.       p->ixMask = 0;
  1820.     }else{
  1821.       /* Big endian.  Byte swap. */
  1822.       p->ixMask = 7;
  1823.     }
  1824.   }
  1825. #endif
  1826. }
  1827.  
  1828. /*
  1829. ** Make consecutive calls to the SHA3Update function to add new content
  1830. ** to the hash
  1831. */
  1832. static void SHA3Update(
  1833.   SHA3Context *p,
  1834.   const unsigned char *aData,
  1835.   unsigned int nData
  1836. ){
  1837.   unsigned int i = 0;
  1838. #if SHA3_BYTEORDER==1234
  1839.   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1840.     for(; i+7<nData; i+=8){
  1841.       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1842.       p->nLoaded += 8;
  1843.       if( p->nLoaded>=p->nRate ){
  1844.         KeccakF1600Step(p);
  1845.         p->nLoaded = 0;
  1846.       }
  1847.     }
  1848.   }
  1849. #endif
  1850.   for(; i<nData; i++){
  1851. #if SHA3_BYTEORDER==1234
  1852.     p->u.x[p->nLoaded] ^= aData[i];
  1853. #elif SHA3_BYTEORDER==4321
  1854.     p->u.x[p->nLoaded^0x07] ^= aData[i];
  1855. #else
  1856.     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1857. #endif
  1858.     p->nLoaded++;
  1859.     if( p->nLoaded==p->nRate ){
  1860.       KeccakF1600Step(p);
  1861.       p->nLoaded = 0;
  1862.     }
  1863.   }
  1864. }
  1865.  
  1866. /*
  1867. ** After all content has been added, invoke SHA3Final() to compute
  1868. ** the final hash.  The function returns a pointer to the binary
  1869. ** hash value.
  1870. */
  1871. static unsigned char *SHA3Final(SHA3Context *p){
  1872.   unsigned int i;
  1873.   if( p->nLoaded==p->nRate-1 ){
  1874.     const unsigned char c1 = 0x86;
  1875.     SHA3Update(p, &c1, 1);
  1876.   }else{
  1877.     const unsigned char c2 = 0x06;
  1878.     const unsigned char c3 = 0x80;
  1879.     SHA3Update(p, &c2, 1);
  1880.     p->nLoaded = p->nRate - 1;
  1881.     SHA3Update(p, &c3, 1);
  1882.   }
  1883.   for(i=0; i<p->nRate; i++){
  1884.     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1885.   }
  1886.   return &p->u.x[p->nRate];
  1887. }
  1888. /* End of the hashing logic
  1889. *****************************************************************************/
  1890.  
  1891. /*
  1892. ** Implementation of the sha3(X,SIZE) function.
  1893. **
  1894. ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
  1895. ** size is 256.  If X is a BLOB, it is hashed as is.  
  1896. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1897. ** and the string is hashed without the trailing 0x00 terminator.  The hash
  1898. ** of a NULL value is NULL.
  1899. */
  1900. static void sha3Func(
  1901.   sqlite3_context *context,
  1902.   int argc,
  1903.   sqlite3_value **argv
  1904. ){
  1905.   SHA3Context cx;
  1906.   int eType = sqlite3_value_type(argv[0]);
  1907.   int nByte = sqlite3_value_bytes(argv[0]);
  1908.   int iSize;
  1909.   if( argc==1 ){
  1910.     iSize = 256;
  1911.   }else{
  1912.     iSize = sqlite3_value_int(argv[1]);
  1913.     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1914.       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1915.                                     "384 512", -1);
  1916.       return;
  1917.     }
  1918.   }
  1919.   if( eType==SQLITE_NULL ) return;
  1920.   SHA3Init(&cx, iSize);
  1921.   if( eType==SQLITE_BLOB ){
  1922.     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1923.   }else{
  1924.     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1925.   }
  1926.   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1927. }
  1928.  
  1929. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1930. ** of 50 bytes and add it to the hash.
  1931. */
  1932. static void hash_step_vformat(
  1933.   SHA3Context *p,                 /* Add content to this context */
  1934.   const char *zFormat,
  1935.   ...
  1936. ){
  1937.   va_list ap;
  1938.   int n;
  1939.   char zBuf[50];
  1940.   va_start(ap, zFormat);
  1941.   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1942.   va_end(ap);
  1943.   n = (int)strlen(zBuf);
  1944.   SHA3Update(p, (unsigned char*)zBuf, n);
  1945. }
  1946.  
  1947. /*
  1948. ** Implementation of the sha3_query(SQL,SIZE) function.
  1949. **
  1950. ** This function compiles and runs the SQL statement(s) given in the
  1951. ** argument. The results are hashed using a SIZE-bit SHA3.  The default
  1952. ** size is 256.
  1953. **
  1954. ** The format of the byte stream that is hashed is summarized as follows:
  1955. **
  1956. **       S<n>:<sql>
  1957. **       R
  1958. **       N
  1959. **       I<int>
  1960. **       F<ieee-float>
  1961. **       B<size>:<bytes>
  1962. **       T<size>:<text>
  1963. **
  1964. ** <sql> is the original SQL text for each statement run and <n> is
  1965. ** the size of that text.  The SQL text is UTF-8.  A single R character
  1966. ** occurs before the start of each row.  N means a NULL value.
  1967. ** I mean an 8-byte little-endian integer <int>.  F is a floating point
  1968. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1969. ** B means blobs of <size> bytes.  T means text rendered as <size>
  1970. ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
  1971. ** text integers.
  1972. **
  1973. ** For each SQL statement in the X input, there is one S segment.  Each
  1974. ** S segment is followed by zero or more R segments, one for each row in the
  1975. ** result set.  After each R, there are one or more N, I, F, B, or T segments,
  1976. ** one for each column in the result set.  Segments are concatentated directly
  1977. ** with no delimiters of any kind.
  1978. */
  1979. static void sha3QueryFunc(
  1980.   sqlite3_context *context,
  1981.   int argc,
  1982.   sqlite3_value **argv
  1983. ){
  1984.   sqlite3 *db = sqlite3_context_db_handle(context);
  1985.   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1986.   sqlite3_stmt *pStmt = 0;
  1987.   int nCol;                   /* Number of columns in the result set */
  1988.   int i;                      /* Loop counter */
  1989.   int rc;
  1990.   int n;
  1991.   const char *z;
  1992.   SHA3Context cx;
  1993.   int iSize;
  1994.  
  1995.   if( argc==1 ){
  1996.     iSize = 256;
  1997.   }else{
  1998.     iSize = sqlite3_value_int(argv[1]);
  1999.     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  2000.       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  2001.                                     "384 512", -1);
  2002.       return;
  2003.     }
  2004.   }
  2005.   if( zSql==0 ) return;
  2006.   SHA3Init(&cx, iSize);
  2007.   while( zSql[0] ){
  2008.     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  2009.     if( rc ){
  2010.       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  2011.                                    zSql, sqlite3_errmsg(db));
  2012.       sqlite3_finalize(pStmt);
  2013.       sqlite3_result_error(context, zMsg, -1);
  2014.       sqlite3_free(zMsg);
  2015.       return;
  2016.     }
  2017.     if( !sqlite3_stmt_readonly(pStmt) ){
  2018.       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  2019.       sqlite3_finalize(pStmt);
  2020.       sqlite3_result_error(context, zMsg, -1);
  2021.       sqlite3_free(zMsg);
  2022.       return;
  2023.     }
  2024.     nCol = sqlite3_column_count(pStmt);
  2025.     z = sqlite3_sql(pStmt);
  2026.     if( z ){
  2027.       n = (int)strlen(z);
  2028.       hash_step_vformat(&cx,"S%d:",n);
  2029.       SHA3Update(&cx,(unsigned char*)z,n);
  2030.     }
  2031.  
  2032.     /* Compute a hash over the result of the query */
  2033.     while( SQLITE_ROW==sqlite3_step(pStmt) ){
  2034.       SHA3Update(&cx,(const unsigned char*)"R",1);
  2035.       for(i=0; i<nCol; i++){
  2036.         switch( sqlite3_column_type(pStmt,i) ){
  2037.           case SQLITE_NULL: {
  2038.             SHA3Update(&cx, (const unsigned char*)"N",1);
  2039.             break;
  2040.           }
  2041.           case SQLITE_INTEGER: {
  2042.             sqlite3_uint64 u;
  2043.             int j;
  2044.             unsigned char x[9];
  2045.             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  2046.             memcpy(&u, &v, 8);
  2047.             for(j=8; j>=1; j--){
  2048.               x[j] = u & 0xff;
  2049.               u >>= 8;
  2050.             }
  2051.             x[0] = 'I';
  2052.             SHA3Update(&cx, x, 9);
  2053.             break;
  2054.           }
  2055.           case SQLITE_FLOAT: {
  2056.             sqlite3_uint64 u;
  2057.             int j;
  2058.             unsigned char x[9];
  2059.             double r = sqlite3_column_double(pStmt,i);
  2060.             memcpy(&u, &r, 8);
  2061.             for(j=8; j>=1; j--){
  2062.               x[j] = u & 0xff;
  2063.               u >>= 8;
  2064.             }
  2065.             x[0] = 'F';
  2066.             SHA3Update(&cx,x,9);
  2067.             break;
  2068.           }
  2069.           case SQLITE_TEXT: {
  2070.             int n2 = sqlite3_column_bytes(pStmt, i);
  2071.             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  2072.             hash_step_vformat(&cx,"T%d:",n2);
  2073.             SHA3Update(&cx, z2, n2);
  2074.             break;
  2075.           }
  2076.           case SQLITE_BLOB: {
  2077.             int n2 = sqlite3_column_bytes(pStmt, i);
  2078.             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  2079.             hash_step_vformat(&cx,"B%d:",n2);
  2080.             SHA3Update(&cx, z2, n2);
  2081.             break;
  2082.           }
  2083.         }
  2084.       }
  2085.     }
  2086.     sqlite3_finalize(pStmt);
  2087.   }
  2088.   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  2089. }
  2090.  
  2091.  
  2092. #ifdef _WIN32
  2093.  
  2094. #endif
  2095. int sqlite3_shathree_init(
  2096.   sqlite3 *db,
  2097.   char **pzErrMsg,
  2098.   const sqlite3_api_routines *pApi
  2099. ){
  2100.   int rc = SQLITE_OK;
  2101.   SQLITE_EXTENSION_INIT2(pApi);
  2102.   (void)pzErrMsg;  /* Unused parameter */
  2103.   rc = sqlite3_create_function(db, "sha3", 1,
  2104.                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  2105.                       0, sha3Func, 0, 0);
  2106.   if( rc==SQLITE_OK ){
  2107.     rc = sqlite3_create_function(db, "sha3", 2,
  2108.                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  2109.                       0, sha3Func, 0, 0);
  2110.   }
  2111.   if( rc==SQLITE_OK ){
  2112.     rc = sqlite3_create_function(db, "sha3_query", 1,
  2113.                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
  2114.                       0, sha3QueryFunc, 0, 0);
  2115.   }
  2116.   if( rc==SQLITE_OK ){
  2117.     rc = sqlite3_create_function(db, "sha3_query", 2,
  2118.                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
  2119.                       0, sha3QueryFunc, 0, 0);
  2120.   }
  2121.   return rc;
  2122. }
  2123.  
  2124. /************************* End ../ext/misc/shathree.c ********************/
  2125. /************************* Begin ../ext/misc/fileio.c ******************/
  2126. /*
  2127. ** 2014-06-13
  2128. **
  2129. ** The author disclaims copyright to this source code.  In place of
  2130. ** a legal notice, here is a blessing:
  2131. **
  2132. **    May you do good and not evil.
  2133. **    May you find forgiveness for yourself and forgive others.
  2134. **    May you share freely, never taking more than you give.
  2135. **
  2136. ******************************************************************************
  2137. **
  2138. ** This SQLite extension implements SQL functions readfile() and
  2139. ** writefile(), and eponymous virtual type "fsdir".
  2140. **
  2141. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  2142. **
  2143. **   If neither of the optional arguments is present, then this UDF
  2144. **   function writes blob DATA to file FILE. If successful, the number
  2145. **   of bytes written is returned. If an error occurs, NULL is returned.
  2146. **
  2147. **   If the first option argument - MODE - is present, then it must
  2148. **   be passed an integer value that corresponds to a POSIX mode
  2149. **   value (file type + permissions, as returned in the stat.st_mode
  2150. **   field by the stat() system call). Three types of files may
  2151. **   be written/created:
  2152. **
  2153. **     regular files:  (mode & 0170000)==0100000
  2154. **     symbolic links: (mode & 0170000)==0120000
  2155. **     directories:    (mode & 0170000)==0040000
  2156. **
  2157. **   For a directory, the DATA is ignored. For a symbolic link, it is
  2158. **   interpreted as text and used as the target of the link. For a
  2159. **   regular file, it is interpreted as a blob and written into the
  2160. **   named file. Regardless of the type of file, its permissions are
  2161. **   set to (mode & 0777) before returning.
  2162. **
  2163. **   If the optional MTIME argument is present, then it is interpreted
  2164. **   as an integer - the number of seconds since the unix epoch. The
  2165. **   modification-time of the target file is set to this value before
  2166. **   returning.
  2167. **
  2168. **   If three or more arguments are passed to this function and an
  2169. **   error is encountered, an exception is raised.
  2170. **
  2171. ** READFILE(FILE):
  2172. **
  2173. **   Read and return the contents of file FILE (type blob) from disk.
  2174. **
  2175. ** FSDIR:
  2176. **
  2177. **   Used as follows:
  2178. **
  2179. **     SELECT * FROM fsdir($path [, $dir]);
  2180. **
  2181. **   Parameter $path is an absolute or relative pathname. If the file that it
  2182. **   refers to does not exist, it is an error. If the path refers to a regular
  2183. **   file or symbolic link, it returns a single row. Or, if the path refers
  2184. **   to a directory, it returns one row for the directory, and one row for each
  2185. **   file within the hierarchy rooted at $path.
  2186. **
  2187. **   Each row has the following columns:
  2188. **
  2189. **     name:  Path to file or directory (text value).
  2190. **     mode:  Value of stat.st_mode for directory entry (an integer).
  2191. **     mtime: Value of stat.st_mtime for directory entry (an integer).
  2192. **     data:  For a regular file, a blob containing the file data. For a
  2193. **            symlink, a text value containing the text of the link. For a
  2194. **            directory, NULL.
  2195. **
  2196. **   If a non-NULL value is specified for the optional $dir parameter and
  2197. **   $path is a relative path, then $path is interpreted relative to $dir.
  2198. **   And the paths returned in the "name" column of the table are also
  2199. **   relative to directory $dir.
  2200. */
  2201. /* #include "sqlite3ext.h" */
  2202. SQLITE_EXTENSION_INIT1
  2203. #include <stdio.h>
  2204. #include <string.h>
  2205. #include <assert.h>
  2206.  
  2207. #include <sys/types.h>
  2208. #include <sys/stat.h>
  2209. #include <fcntl.h>
  2210. #if !defined(_WIN32) && !defined(WIN32)
  2211. #  include <unistd.h>
  2212. #  include <dirent.h>
  2213. #  include <utime.h>
  2214. #  include <sys/time.h>
  2215. #else
  2216. #  include "windows.h"
  2217. #  include <io.h>
  2218. #  include <direct.h>
  2219. /* #  include "test_windirent.h" */
  2220. #  define dirent DIRENT
  2221. #  ifndef chmod
  2222. #    define chmod _chmod
  2223. #  endif
  2224. #  ifndef stat
  2225. #    define stat _stat
  2226. #  endif
  2227. #  define mkdir(path,mode) _mkdir(path)
  2228. #  define lstat(path,buf) stat(path,buf)
  2229. #endif
  2230. #include <time.h>
  2231. #include <errno.h>
  2232.  
  2233.  
  2234. /*
  2235. ** Structure of the fsdir() table-valued function
  2236. */
  2237.                  /*    0    1    2     3    4           5             */
  2238. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  2239. #define FSDIR_COLUMN_NAME     0     /* Name of the file */
  2240. #define FSDIR_COLUMN_MODE     1     /* Access mode */
  2241. #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
  2242. #define FSDIR_COLUMN_DATA     3     /* File content */
  2243. #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
  2244. #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
  2245.  
  2246.  
  2247. /*
  2248. ** Set the result stored by context ctx to a blob containing the
  2249. ** contents of file zName.  Or, leave the result unchanged (NULL)
  2250. ** if the file does not exist or is unreadable.
  2251. **
  2252. ** If the file exceeds the SQLite blob size limit, through an
  2253. ** SQLITE_TOOBIG error.
  2254. **
  2255. ** Throw an SQLITE_IOERR if there are difficulties pulling the file
  2256. ** off of disk.
  2257. */
  2258. static void readFileContents(sqlite3_context *ctx, const char *zName){
  2259.   FILE *in;
  2260.   sqlite3_int64 nIn;
  2261.   void *pBuf;
  2262.   sqlite3 *db;
  2263.   int mxBlob;
  2264.  
  2265.   in = fopen(zName, "rb");
  2266.   if( in==0 ){
  2267.     /* File does not exist or is unreadable. Leave the result set to NULL. */
  2268.     return;
  2269.   }
  2270.   fseek(in, 0, SEEK_END);
  2271.   nIn = ftell(in);
  2272.   rewind(in);
  2273.   db = sqlite3_context_db_handle(ctx);
  2274.   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
  2275.   if( nIn>mxBlob ){
  2276.     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
  2277.     fclose(in);
  2278.     return;
  2279.   }
  2280.   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
  2281.   if( pBuf==0 ){
  2282.     sqlite3_result_error_nomem(ctx);
  2283.     fclose(in);
  2284.     return;
  2285.   }
  2286.   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
  2287.     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
  2288.   }else{
  2289.     sqlite3_result_error_code(ctx, SQLITE_IOERR);
  2290.     sqlite3_free(pBuf);
  2291.   }
  2292.   fclose(in);
  2293. }
  2294.  
  2295. /*
  2296. ** Implementation of the "readfile(X)" SQL function.  The entire content
  2297. ** of the file named X is read and returned as a BLOB.  NULL is returned
  2298. ** if the file does not exist or is unreadable.
  2299. */
  2300. static void readfileFunc(
  2301.   sqlite3_context *context,
  2302.   int argc,
  2303.   sqlite3_value **argv
  2304. ){
  2305.   const char *zName;
  2306.   (void)(argc);  /* Unused parameter */
  2307.   zName = (const char*)sqlite3_value_text(argv[0]);
  2308.   if( zName==0 ) return;
  2309.   readFileContents(context, zName);
  2310. }
  2311.  
  2312. /*
  2313. ** Set the error message contained in context ctx to the results of
  2314. ** vprintf(zFmt, ...).
  2315. */
  2316. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  2317.   char *zMsg = 0;
  2318.   va_list ap;
  2319.   va_start(ap, zFmt);
  2320.   zMsg = sqlite3_vmprintf(zFmt, ap);
  2321.   sqlite3_result_error(ctx, zMsg, -1);
  2322.   sqlite3_free(zMsg);
  2323.   va_end(ap);
  2324. }
  2325.  
  2326. #if defined(_WIN32)
  2327. /*
  2328. ** This function is designed to convert a Win32 FILETIME structure into the
  2329. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  2330. */
  2331. static sqlite3_uint64 fileTimeToUnixTime(
  2332.   LPFILETIME pFileTime
  2333. ){
  2334.   SYSTEMTIME epochSystemTime;
  2335.   ULARGE_INTEGER epochIntervals;
  2336.   FILETIME epochFileTime;
  2337.   ULARGE_INTEGER fileIntervals;
  2338.  
  2339.   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  2340.   epochSystemTime.wYear = 1970;
  2341.   epochSystemTime.wMonth = 1;
  2342.   epochSystemTime.wDay = 1;
  2343.   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  2344.   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  2345.   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  2346.  
  2347.   fileIntervals.LowPart = pFileTime->dwLowDateTime;
  2348.   fileIntervals.HighPart = pFileTime->dwHighDateTime;
  2349.  
  2350.   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  2351. }
  2352.  
  2353. /*
  2354. ** This function attempts to normalize the time values found in the stat()
  2355. ** buffer to UTC.  This is necessary on Win32, where the runtime library
  2356. ** appears to return these values as local times.
  2357. */
  2358. static void statTimesToUtc(
  2359.   const char *zPath,
  2360.   struct stat *pStatBuf
  2361. ){
  2362.   HANDLE hFindFile;
  2363.   WIN32_FIND_DATAW fd;
  2364.   LPWSTR zUnicodeName;
  2365.   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2366.   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  2367.   if( zUnicodeName ){
  2368.     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  2369.     hFindFile = FindFirstFileW(zUnicodeName, &fd);
  2370.     if( hFindFile!=NULL ){
  2371.       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  2372.       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  2373.       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  2374.       FindClose(hFindFile);
  2375.     }
  2376.     sqlite3_free(zUnicodeName);
  2377.   }
  2378. }
  2379. #endif
  2380.  
  2381. /*
  2382. ** This function is used in place of stat().  On Windows, special handling
  2383. ** is required in order for the included time to be returned as UTC.  On all
  2384. ** other systems, this function simply calls stat().
  2385. */
  2386. static int fileStat(
  2387.   const char *zPath,
  2388.   struct stat *pStatBuf
  2389. ){
  2390. #if defined(_WIN32)
  2391.   int rc = stat(zPath, pStatBuf);
  2392.   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2393.   return rc;
  2394. #else
  2395.   return stat(zPath, pStatBuf);
  2396. #endif
  2397. }
  2398.  
  2399. /*
  2400. ** This function is used in place of lstat().  On Windows, special handling
  2401. ** is required in order for the included time to be returned as UTC.  On all
  2402. ** other systems, this function simply calls lstat().
  2403. */
  2404. static int fileLinkStat(
  2405.   const char *zPath,
  2406.   struct stat *pStatBuf
  2407. ){
  2408. #if defined(_WIN32)
  2409.   int rc = lstat(zPath, pStatBuf);
  2410.   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2411.   return rc;
  2412. #else
  2413.   return lstat(zPath, pStatBuf);
  2414. #endif
  2415. }
  2416.  
  2417. /*
  2418. ** Argument zFile is the name of a file that will be created and/or written
  2419. ** by SQL function writefile(). This function ensures that the directory
  2420. ** zFile will be written to exists, creating it if required. The permissions
  2421. ** for any path components created by this function are set in accordance
  2422. ** with the current umask.
  2423. **
  2424. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  2425. ** SQLITE_OK is returned if the directory is successfully created, or
  2426. ** SQLITE_ERROR otherwise.
  2427. */
  2428. static int makeDirectory(
  2429.   const char *zFile
  2430. ){
  2431.   char *zCopy = sqlite3_mprintf("%s", zFile);
  2432.   int rc = SQLITE_OK;
  2433.  
  2434.   if( zCopy==0 ){
  2435.     rc = SQLITE_NOMEM;
  2436.   }else{
  2437.     int nCopy = (int)strlen(zCopy);
  2438.     int i = 1;
  2439.  
  2440.     while( rc==SQLITE_OK ){
  2441.       struct stat sStat;
  2442.       int rc2;
  2443.  
  2444.       for(; zCopy[i]!='/' && i<nCopy; i++);
  2445.       if( i==nCopy ) break;
  2446.       zCopy[i] = '\0';
  2447.  
  2448.       rc2 = fileStat(zCopy, &sStat);
  2449.       if( rc2!=0 ){
  2450.         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
  2451.       }else{
  2452.         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  2453.       }
  2454.       zCopy[i] = '/';
  2455.       i++;
  2456.     }
  2457.  
  2458.     sqlite3_free(zCopy);
  2459.   }
  2460.  
  2461.   return rc;
  2462. }
  2463.  
  2464. /*
  2465. ** This function does the work for the writefile() UDF. Refer to
  2466. ** header comments at the top of this file for details.
  2467. */
  2468. static int writeFile(
  2469.   sqlite3_context *pCtx,          /* Context to return bytes written in */
  2470.   const char *zFile,              /* File to write */
  2471.   sqlite3_value *pData,           /* Data to write */
  2472.   mode_t mode,                    /* MODE parameter passed to writefile() */
  2473.   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
  2474. ){
  2475. #if !defined(_WIN32) && !defined(WIN32) && !defined (_KOLIBRI)
  2476.  
  2477.     if( S_ISLNK(mode) ){
  2478.     const char *zTo = (const char*)sqlite3_value_text(pData);
  2479.     if( symlink(zTo, zFile)<0 ) return 1;
  2480.   }else
  2481. #endif
  2482.   {
  2483.     if( S_ISDIR(mode) ){
  2484.       if( mkdir(zFile, mode) ){
  2485.         /* The mkdir() call to create the directory failed. This might not
  2486.         ** be an error though - if there is already a directory at the same
  2487.         ** path and either the permissions already match or can be changed
  2488.         ** to do so using chmod(), it is not an error.  */
  2489.         struct stat sStat;
  2490.         if( errno!=EEXIST
  2491.          || 0!=fileStat(zFile, &sStat)
  2492.          || !S_ISDIR(sStat.st_mode)
  2493.          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  2494.         ){
  2495.           return 1;
  2496.         }
  2497.       }
  2498.     }else{
  2499.       sqlite3_int64 nWrite = 0;
  2500.       const char *z;
  2501.       int rc = 0;
  2502.       FILE *out = fopen(zFile, "wb");
  2503.       if( out==0 ) return 1;
  2504.       z = (const char*)sqlite3_value_blob(pData);
  2505.       if( z ){
  2506.         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  2507.         nWrite = sqlite3_value_bytes(pData);
  2508.         if( nWrite!=n ){
  2509.           rc = 1;
  2510.         }
  2511.       }
  2512.       fclose(out);
  2513.       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  2514.         rc = 1;
  2515.       }
  2516.       if( rc ) return 2;
  2517.       sqlite3_result_int64(pCtx, nWrite);
  2518.     }
  2519.   }
  2520.  
  2521.   if( mtime>=0 ){
  2522. #if defined(_WIN32)
  2523. #if !SQLITE_OS_WINRT
  2524.     /* Windows */
  2525.     FILETIME lastAccess;
  2526.     FILETIME lastWrite;
  2527.     SYSTEMTIME currentTime;
  2528.     LONGLONG intervals;
  2529.     HANDLE hFile;
  2530.     LPWSTR zUnicodeName;
  2531.     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2532.  
  2533.     GetSystemTime(&currentTime);
  2534.     SystemTimeToFileTime(&currentTime, &lastAccess);
  2535.     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  2536.     lastWrite.dwLowDateTime = (DWORD)intervals;
  2537.     lastWrite.dwHighDateTime = intervals >> 32;
  2538.     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  2539.     if( zUnicodeName==0 ){
  2540.       return 1;
  2541.     }
  2542.     hFile = CreateFileW(
  2543.       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  2544.       FILE_FLAG_BACKUP_SEMANTICS, NULL
  2545.     );
  2546.     sqlite3_free(zUnicodeName);
  2547.     if( hFile!=INVALID_HANDLE_VALUE ){
  2548.       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  2549.       CloseHandle(hFile);
  2550.       return !bResult;
  2551.     }else{
  2552.       return 1;
  2553.     }
  2554. #endif
  2555. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  2556.     /* Recent unix */
  2557.     struct timespec times[2];
  2558.     times[0].tv_nsec = times[1].tv_nsec = 0;
  2559.     times[0].tv_sec = time(0);
  2560.     times[1].tv_sec = mtime;
  2561.     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  2562.       return 1;
  2563.     }
  2564.    
  2565.  
  2566. #elif !defined(_KOLIBRI)
  2567.     /* Legacy unix */
  2568.     struct timeval times[2];
  2569.     times[0].tv_usec = times[1].tv_usec = 0;
  2570.     times[0].tv_sec = time(0);
  2571.     times[1].tv_sec = mtime;
  2572.     if( utimes(zFile, times) ){
  2573.       return 1;
  2574.     }
  2575. #endif
  2576.   }
  2577.  
  2578.   return 0;
  2579. }
  2580.  
  2581. /*
  2582. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
  2583. ** Refer to header comments at the top of this file for details.
  2584. */
  2585. static void writefileFunc(
  2586.   sqlite3_context *context,
  2587.   int argc,
  2588.   sqlite3_value **argv
  2589. ){
  2590.   const char *zFile;
  2591.   mode_t mode = 0;
  2592.   int res;
  2593.   sqlite3_int64 mtime = -1;
  2594.  
  2595.   if( argc<2 || argc>4 ){
  2596.     sqlite3_result_error(context,
  2597.         "wrong number of arguments to function writefile()", -1
  2598.     );
  2599.     return;
  2600.   }
  2601.  
  2602.   zFile = (const char*)sqlite3_value_text(argv[0]);
  2603.   if( zFile==0 ) return;
  2604.   if( argc>=3 ){
  2605.     mode = (mode_t)sqlite3_value_int(argv[2]);
  2606.   }
  2607.   if( argc==4 ){
  2608.     mtime = sqlite3_value_int64(argv[3]);
  2609.   }
  2610.  
  2611.   res = writeFile(context, zFile, argv[1], mode, mtime);
  2612.   if( res==1 && errno==ENOENT ){
  2613.     if( makeDirectory(zFile)==SQLITE_OK ){
  2614.       res = writeFile(context, zFile, argv[1], mode, mtime);
  2615.     }
  2616.   }
  2617.  
  2618.   if( argc>2 && res!=0 ){
  2619.     if( S_ISLNK(mode) ){
  2620.       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  2621.     }else if( S_ISDIR(mode) ){
  2622.       ctxErrorMsg(context, "failed to create directory: %s", zFile);
  2623.     }else{
  2624.       ctxErrorMsg(context, "failed to write file: %s", zFile);
  2625.     }
  2626.   }
  2627. }
  2628.  
  2629. /*
  2630. ** SQL function:   lsmode(MODE)
  2631. **
  2632. ** Given a numberic st_mode from stat(), convert it into a human-readable
  2633. ** text string in the style of "ls -l".
  2634. */
  2635. static void lsModeFunc(
  2636.   sqlite3_context *context,
  2637.   int argc,
  2638.   sqlite3_value **argv
  2639. ){
  2640.   int i;
  2641.   int iMode = sqlite3_value_int(argv[0]);
  2642.   char z[16];
  2643.   (void)argc;
  2644.   if( S_ISLNK(iMode) ){
  2645.     z[0] = 'l';
  2646.   }else if( S_ISREG(iMode) ){
  2647.     z[0] = '-';
  2648.   }else if( S_ISDIR(iMode) ){
  2649.     z[0] = 'd';
  2650.   }else{
  2651.     z[0] = '?';
  2652.   }
  2653.   for(i=0; i<3; i++){
  2654.     int m = (iMode >> ((2-i)*3));
  2655.     char *a = &z[1 + i*3];
  2656.     a[0] = (m & 0x4) ? 'r' : '-';
  2657.     a[1] = (m & 0x2) ? 'w' : '-';
  2658.     a[2] = (m & 0x1) ? 'x' : '-';
  2659.   }
  2660.   z[10] = '\0';
  2661.   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  2662. }
  2663.  
  2664. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2665.  
  2666. /*
  2667. ** Cursor type for recursively iterating through a directory structure.
  2668. */
  2669. typedef struct fsdir_cursor fsdir_cursor;
  2670. typedef struct FsdirLevel FsdirLevel;
  2671.  
  2672. struct FsdirLevel {
  2673.   DIR *pDir;                 /* From opendir() */
  2674.   char *zDir;                /* Name of directory (nul-terminated) */
  2675. };
  2676.  
  2677. struct fsdir_cursor {
  2678.   sqlite3_vtab_cursor base;  /* Base class - must be first */
  2679.  
  2680.   int nLvl;                  /* Number of entries in aLvl[] array */
  2681.   int iLvl;                  /* Index of current entry */
  2682.   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
  2683.  
  2684.   const char *zBase;
  2685.   int nBase;
  2686.  
  2687.   struct stat sStat;         /* Current lstat() results */
  2688.   char *zPath;               /* Path to current entry */
  2689.   sqlite3_int64 iRowid;      /* Current rowid */
  2690. };
  2691.  
  2692. typedef struct fsdir_tab fsdir_tab;
  2693. struct fsdir_tab {
  2694.   sqlite3_vtab base;         /* Base class - must be first */
  2695. };
  2696.  
  2697. /*
  2698. ** Construct a new fsdir virtual table object.
  2699. */
  2700. static int fsdirConnect(
  2701.   sqlite3 *db,
  2702.   void *pAux,
  2703.   int argc, const char *const*argv,
  2704.   sqlite3_vtab **ppVtab,
  2705.   char **pzErr
  2706. ){
  2707.   fsdir_tab *pNew = 0;
  2708.   int rc;
  2709.   (void)pAux;
  2710.   (void)argc;
  2711.   (void)argv;
  2712.   (void)pzErr;
  2713.   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  2714.   if( rc==SQLITE_OK ){
  2715.     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  2716.     if( pNew==0 ) return SQLITE_NOMEM;
  2717.     memset(pNew, 0, sizeof(*pNew));
  2718.     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  2719.   }
  2720.   *ppVtab = (sqlite3_vtab*)pNew;
  2721.   return rc;
  2722. }
  2723.  
  2724. /*
  2725. ** This method is the destructor for fsdir vtab objects.
  2726. */
  2727. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  2728.   sqlite3_free(pVtab);
  2729.   return SQLITE_OK;
  2730. }
  2731.  
  2732. /*
  2733. ** Constructor for a new fsdir_cursor object.
  2734. */
  2735. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2736.   fsdir_cursor *pCur;
  2737.   (void)p;
  2738.   pCur = sqlite3_malloc( sizeof(*pCur) );
  2739.   if( pCur==0 ) return SQLITE_NOMEM;
  2740.   memset(pCur, 0, sizeof(*pCur));
  2741.   pCur->iLvl = -1;
  2742.   *ppCursor = &pCur->base;
  2743.   return SQLITE_OK;
  2744. }
  2745.  
  2746. /*
  2747. ** Reset a cursor back to the state it was in when first returned
  2748. ** by fsdirOpen().
  2749. */
  2750. static void fsdirResetCursor(fsdir_cursor *pCur){
  2751.   int i;
  2752.   for(i=0; i<=pCur->iLvl; i++){
  2753.     FsdirLevel *pLvl = &pCur->aLvl[i];
  2754.     if( pLvl->pDir ) closedir(pLvl->pDir);
  2755.     sqlite3_free(pLvl->zDir);
  2756.   }
  2757.   sqlite3_free(pCur->zPath);
  2758.   sqlite3_free(pCur->aLvl);
  2759.   pCur->aLvl = 0;
  2760.   pCur->zPath = 0;
  2761.   pCur->zBase = 0;
  2762.   pCur->nBase = 0;
  2763.   pCur->nLvl = 0;
  2764.   pCur->iLvl = -1;
  2765.   pCur->iRowid = 1;
  2766. }
  2767.  
  2768. /*
  2769. ** Destructor for an fsdir_cursor.
  2770. */
  2771. static int fsdirClose(sqlite3_vtab_cursor *cur){
  2772.   fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2773.  
  2774.   fsdirResetCursor(pCur);
  2775.   sqlite3_free(pCur);
  2776.   return SQLITE_OK;
  2777. }
  2778.  
  2779. /*
  2780. ** Set the error message for the virtual table associated with cursor
  2781. ** pCur to the results of vprintf(zFmt, ...).
  2782. */
  2783. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  2784.   va_list ap;
  2785.   va_start(ap, zFmt);
  2786.   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  2787.   va_end(ap);
  2788. }
  2789.  
  2790.  
  2791. /*
  2792. ** Advance an fsdir_cursor to its next row of output.
  2793. */
  2794. static int fsdirNext(sqlite3_vtab_cursor *cur){
  2795.   fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2796.   mode_t m = pCur->sStat.st_mode;
  2797.  
  2798.   pCur->iRowid++;
  2799.   if( S_ISDIR(m) ){
  2800.     /* Descend into this directory */
  2801.     int iNew = pCur->iLvl + 1;
  2802.     FsdirLevel *pLvl;
  2803.     if( iNew>=pCur->nLvl ){
  2804.       int nNew = iNew+1;
  2805.       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
  2806.       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
  2807.       if( aNew==0 ) return SQLITE_NOMEM;
  2808.       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  2809.       pCur->aLvl = aNew;
  2810.       pCur->nLvl = nNew;
  2811.     }
  2812.     pCur->iLvl = iNew;
  2813.     pLvl = &pCur->aLvl[iNew];
  2814.    
  2815.     pLvl->zDir = pCur->zPath;
  2816.     pCur->zPath = 0;
  2817.     pLvl->pDir = opendir(pLvl->zDir);
  2818.     if( pLvl->pDir==0 ){
  2819.       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  2820.       return SQLITE_ERROR;
  2821.     }
  2822.   }
  2823.  
  2824.   while( pCur->iLvl>=0 ){
  2825.     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  2826.     struct dirent *pEntry = readdir(pLvl->pDir);
  2827.     if( pEntry ){
  2828.       if( pEntry->d_name[0]=='.' ){
  2829.        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  2830.        if( pEntry->d_name[1]=='\0' ) continue;
  2831.       }
  2832.       sqlite3_free(pCur->zPath);
  2833.       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  2834.       if( pCur->zPath==0 ) return SQLITE_NOMEM;
  2835.       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2836.         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2837.         return SQLITE_ERROR;
  2838.       }
  2839.       return SQLITE_OK;
  2840.     }
  2841.     closedir(pLvl->pDir);
  2842.     sqlite3_free(pLvl->zDir);
  2843.     pLvl->pDir = 0;
  2844.     pLvl->zDir = 0;
  2845.     pCur->iLvl--;
  2846.   }
  2847.  
  2848.   /* EOF */
  2849.   sqlite3_free(pCur->zPath);
  2850.   pCur->zPath = 0;
  2851.   return SQLITE_OK;
  2852. }
  2853.  
  2854. /*
  2855. ** Return values of columns for the row at which the series_cursor
  2856. ** is currently pointing.
  2857. */
  2858. static int fsdirColumn(
  2859.   sqlite3_vtab_cursor *cur,   /* The cursor */
  2860.   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
  2861.   int i                       /* Which column to return */
  2862. ){
  2863.   fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2864.   switch( i ){
  2865.     case FSDIR_COLUMN_NAME: {
  2866.       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2867.       break;
  2868.     }
  2869.  
  2870.     case FSDIR_COLUMN_MODE:
  2871.       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2872.       break;
  2873.  
  2874.     case FSDIR_COLUMN_MTIME:
  2875.       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2876.       break;
  2877.  
  2878.     case FSDIR_COLUMN_DATA: {
  2879.       mode_t m = pCur->sStat.st_mode;
  2880.       if( S_ISDIR(m) ){
  2881.         sqlite3_result_null(ctx);
  2882. #if !defined(_WIN32) && !defined(WIN32) && !defined(_KOLIBRI)
  2883.       }else if( S_ISLNK(m) ){
  2884.         char aStatic[64];
  2885.         char *aBuf = aStatic;
  2886.         sqlite3_int64 nBuf = 64;
  2887.         int n;
  2888.  
  2889.         while( 1 ){
  2890.           n = readlink(pCur->zPath, aBuf, nBuf);
  2891.           if( n<nBuf ) break;
  2892.           if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2893.           nBuf = nBuf*2;
  2894.           aBuf = sqlite3_malloc64(nBuf);
  2895.           if( aBuf==0 ){
  2896.             sqlite3_result_error_nomem(ctx);
  2897.             return SQLITE_NOMEM;
  2898.           }
  2899.         }
  2900.  
  2901.         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2902.         if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2903. #endif
  2904.       }else{
  2905.         readFileContents(ctx, pCur->zPath);
  2906.       }