os_rtt.c 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651
  1. /*
  2. ** 2004 May 22
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. ******************************************************************************
  12. **
  13. ** This file contains code that is specific to Windows.
  14. */
  15. #include "sqliteInt.h"
  16. #if SQLITE_OS_RTT /* This file is used for rt-thread only */
  17. #include <rtthread.h>
  18. /*
  19. ** Include code that is common to all os_*.c files
  20. */
  21. #include "os_common.h"
  22. /*
  23. ** Compiling and using WAL mode requires several APIs that are not
  24. ** available in rt-thread.
  25. */
  26. #if !defined(SQLITE_OMIT_WAL)
  27. # error "WAL mode requires not support from the rt-thread, compile\
  28. with SQLITE_OMIT_WAL."
  29. #endif
  30. /*
  31. ** Are most of the rtt ANSI APIs available (i.e. with certain exceptions
  32. ** based on the sub-platform)?
  33. */
  34. #if !defined(SQLITE_RTT_NO_ANSI)
  35. # warning "please ensure rtt ANSI APIs is available, otherwise compile with\
  36. SQLITE_RTT_NO_ANSI"
  37. # define SQLITE_RTT_HAS_ANSI
  38. #endif
  39. /*
  40. ** Are most of the rtt Unicode APIs available (i.e. with certain exceptions
  41. ** based on the sub-platform)?
  42. */
  43. #if !defined(SQLITE_RTT_NO_WIDE)
  44. # error "rtt not support Unicode APIs"
  45. # define SQLITE_RTT_HAS_WIDE
  46. #endif
  47. /*
  48. ** Make sure at least one set of rtt APIs is available.
  49. */
  50. #if !defined(SQLITE_RTT_HAS_ANSI) && !defined(SQLITE_RTT_HAS_WIDE)
  51. # error "At least one of SQLITE_RTT_HAS_ANSI and SQLITE_RTT_HAS_WIDE\
  52. must be defined."
  53. #endif
  54. /*
  55. ** Maximum pathname length (in chars) for rtt. This should normally be
  56. ** MAX_PATH.
  57. */
  58. #ifndef SQLITE_RTT_MAX_PATH_CHARS
  59. # warning "default Maximum pathname length be 255, otherwise compile with\
  60. SQLITE_RTT_MAX_PATH_CHARS=?"
  61. # define SQLITE_RTT_MAX_PATH_CHARS (255)
  62. #endif
  63. /*
  64. ** Maximum supported path-length.
  65. */
  66. #define MAX_PATHNAME 512
  67. /*
  68. ** Returns non-zero if the character should be treated as a directory
  69. ** separator.
  70. */
  71. #ifndef rttIsDirSep
  72. # define rttIsDirSep(a) ((a) == '/')
  73. #endif
  74. /*
  75. ** This macro is used when a local variable is set to a value that is
  76. ** [sometimes] not used by the code (e.g. via conditional compilation).
  77. */
  78. #ifndef UNUSED_VARIABLE_VALUE
  79. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  80. #endif
  81. /*
  82. ** Returns the string that should be used as the directory separator.
  83. */
  84. #ifndef rttGetDirDep
  85. # define rttGetDirDep() "/"
  86. #endif
  87. /*
  88. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  89. ** portability layer.
  90. */
  91. typedef struct rttFile rttFile;
  92. struct rttFile {
  93. sqlite3_io_methods const *pMethod; /* Always the first entry */
  94. sqlite3_vfs *pVfs; /* The VFS that created this rttFile */
  95. int h; /* The file descriptor */
  96. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  97. unsigned char eFileLock; /* The type of lock held on this fd */
  98. int lastErrno; /* The unix errno from last I/O error */
  99. void *lockingContext; /* Locking style specific state */
  100. const char *zPath; /* Name of the file */
  101. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  102. #if SQLITE_ENABLE_LOCKING_STYLE
  103. int openFlags; /* The flags specified at open() */
  104. #endif
  105. #if SQLITE_ENABLE_LOCKING_STYLE
  106. unsigned fsFlags; /* cached details from statfs() */
  107. #endif
  108. #ifdef SQLITE_DEBUG
  109. /* The next group of variables are used to track whether or not the
  110. ** transaction counter in bytes 24-27 of database files are updated
  111. ** whenever any part of the database changes. An assertion fault will
  112. ** occur if a file is updated without also updating the transaction
  113. ** counter. This test is made to avoid new problems similar to the
  114. ** one described by ticket #3584.
  115. */
  116. unsigned char transCntrChng; /* True if the transaction counter changed */
  117. unsigned char dbUpdate; /* True if any part of database file changed */
  118. unsigned char inNormalWrite; /* True if in a normal write operation */
  119. #endif
  120. #ifdef SQLITE_TEST
  121. /* In test mode, increase the size of this structure a bit so that
  122. ** it is larger than the struct CrashFile defined in test6.c.
  123. */
  124. char aPadding[32];
  125. #endif
  126. };
  127. /*
  128. ** Allowed values for the rttFile.ctrlFlags bitmask:
  129. */
  130. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  131. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  132. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  133. #ifndef SQLITE_DISABLE_DIRSYNC
  134. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  135. #else
  136. # define UNIXFILE_DIRSYNC 0x00
  137. #endif
  138. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  139. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  140. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  141. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  142. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  143. /*
  144. ** The following variable is (normally) set once and never changes
  145. ** thereafter. It records whether the operating system is Win9x
  146. ** or WinNT.
  147. **
  148. ** 0: Operating system unknown.
  149. ** 1: Operating system is rtt.
  150. **
  151. ** In order to facilitate testing on a rtt system, the test fixture
  152. ** can manually set this value to 1 to emulate Win98 behavior.
  153. */
  154. #ifdef SQLITE_TEST
  155. int sqlite3_os_type = 0;
  156. #elif !SQLITE_OS_RTT && \
  157. defined(SQLITE_RTT_HAS_ANSI) && defined(SQLITE_RTT_HAS_WIDE)
  158. static int sqlite3_os_type = 0;
  159. #endif
  160. #ifndef SYSCALL
  161. # define SYSCALL sqlite3_syscall_ptr
  162. #endif
  163. #include <dfs_posix.h>
  164. static int _Access(const char *pathname, int mode)
  165. {
  166. int fd;
  167. fd = open(pathname, O_RDONLY, mode);
  168. if (fd >= 0)
  169. {
  170. close(fd);
  171. return 0;
  172. }
  173. return -1;
  174. }
  175. /*
  176. ** Invoke open(). Do so multiple times, until it either succeeds or
  177. ** fails for some reason other than EINTR.
  178. **
  179. ** If the file creation mode "m" is 0 then set it to the default for
  180. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  181. ** 0644) as modified by the system umask. If m is not 0, then
  182. ** make the file creation mode be exactly m ignoring the umask.
  183. **
  184. ** The m parameter will be non-zero only when creating -wal, -journal,
  185. ** and -shm files. We want those files to have *exactly* the same
  186. ** permissions as their original database, unadulterated by the umask.
  187. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  188. ** transaction crashes and leaves behind hot journals, then any
  189. ** process that is able to write to the database will also be able to
  190. ** recover the hot journals.
  191. */
  192. static int robust_open(const char *z, int f, mode_t m);
  193. /*
  194. ** Open a file descriptor to the directory containing file zFilename.
  195. ** If successful, *pFd is set to the opened file descriptor and
  196. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  197. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  198. ** value.
  199. **
  200. ** The directory file descriptor is used for only one thing - to
  201. ** fsync() a directory to make sure file creation and deletion events
  202. ** are flushed to disk. Such fsyncs are not needed on newer
  203. ** journaling filesystems, but are required on older filesystems.
  204. **
  205. ** This routine can be overridden using the xSetSysCall interface.
  206. ** The ability to override this routine was added in support of the
  207. ** chromium sandbox. Opening a directory is a security risk (we are
  208. ** told) so making it overrideable allows the chromium sandbox to
  209. ** replace this routine with a harmless no-op. To make this routine
  210. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  211. ** *pFd set to a negative number.
  212. **
  213. ** If SQLITE_OK is returned, the caller is responsible for closing
  214. ** the file descriptor *pFd using close().
  215. */
  216. static int openDirectory(const char *zFilename, int *pFd);
  217. /*
  218. ** Many system calls are accessed through pointer-to-functions so that
  219. ** they may be overridden at runtime to facilitate fault injection during
  220. ** testing and sandboxing. The following array holds the names and pointers
  221. ** to all overrideable system calls.
  222. */
  223. static struct rtt_syscall {
  224. const char *zName; /* Name of the system call */
  225. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  226. sqlite3_syscall_ptr pDefault; /* Default value */
  227. } aSyscall[] = {
  228. {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0},
  229. #define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent)
  230. { "open", (sqlite3_syscall_ptr)open, 0 },
  231. #define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent)
  232. { "close", (sqlite3_syscall_ptr)close, 0 },
  233. #define osClose ((int(*)(int))aSyscall[2].pCurrent)
  234. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  235. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  236. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  237. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  238. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  239. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  240. { "read", (sqlite3_syscall_ptr)read, 0 },
  241. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[6].pCurrent)
  242. { "write", (sqlite3_syscall_ptr)write, 0 },
  243. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[7].pCurrent)
  244. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  245. #define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent)
  246. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  247. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent)
  248. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  249. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent)
  250. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  251. #define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent)
  252. {"access", (sqlite3_syscall_ptr)_Access, 0 },
  253. #define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent)
  254. }; /* End of the overrideable system calls */
  255. /*
  256. ** Do not accept any file descriptor less than this value, in order to avoid
  257. ** opening database file using file descriptors that are commonly used for
  258. ** standard input, output, and error.
  259. */
  260. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  261. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  262. #endif
  263. /*
  264. ** Invoke open(). Do so multiple times, until it either succeeds or
  265. ** fails for some reason other than EINTR.
  266. **
  267. ** If the file creation mode "m" is 0 then set it to the default for
  268. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  269. ** 0644) as modified by the system umask. If m is not 0, then
  270. ** make the file creation mode be exactly m ignoring the umask.
  271. **
  272. ** The m parameter will be non-zero only when creating -wal, -journal,
  273. ** and -shm files. We want those files to have *exactly* the same
  274. ** permissions as their original database, unadulterated by the umask.
  275. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  276. ** transaction crashes and leaves behind hot journals, then any
  277. ** process that is able to write to the database will also be able to
  278. ** recover the hot journals.
  279. */
  280. static int robust_open(const char *z, int f, mode_t m){
  281. int fd;
  282. mode_t m2 = m ;
  283. while(1){
  284. #if defined(O_CLOEXEC)
  285. fd = osOpen(z,f|O_CLOEXEC,m2);
  286. #else
  287. fd = osOpen(z,f,m2);
  288. #endif
  289. if( fd<0 ){
  290. if( errno==EINTR ) continue;
  291. break;
  292. }
  293. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  294. osClose(fd);
  295. sqlite3_log(SQLITE_WARNING,
  296. "attempt to open \"%s\" as file descriptor %d", z, fd);
  297. fd = -1;
  298. if( osOpen("/dev/null", f, m)<0 ) break;
  299. }
  300. return fd;
  301. }
  302. /*
  303. ** Open a file descriptor to the directory containing file zFilename.
  304. ** If successful, *pFd is set to the opened file descriptor and
  305. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  306. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  307. ** value.
  308. **
  309. ** The directory file descriptor is used for only one thing - to
  310. ** fsync() a directory to make sure file creation and deletion events
  311. ** are flushed to disk. Such fsyncs are not needed on newer
  312. ** journaling filesystems, but are required on older filesystems.
  313. **
  314. ** This routine can be overridden using the xSetSysCall interface.
  315. ** The ability to override this routine was added in support of the
  316. ** chromium sandbox. Opening a directory is a security risk (we are
  317. ** told) so making it overrideable allows the chromium sandbox to
  318. ** replace this routine with a harmless no-op. To make this routine
  319. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  320. ** *pFd set to a negative number.
  321. **
  322. ** If SQLITE_OK is returned, the caller is responsible for closing
  323. ** the file descriptor *pFd using close().
  324. */
  325. static int openDirectory(const char *zFilename, int *pFd){
  326. int ii;
  327. int fd = -1;
  328. char zDirname[MAX_PATHNAME+1];
  329. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  330. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  331. if( ii>0 ){
  332. zDirname[ii] = '\0';
  333. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  334. if( fd>=0 ){
  335. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  336. }
  337. }
  338. *pFd = fd;
  339. return (fd>=0?SQLITE_OK:rttLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  340. }
  341. /*
  342. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  343. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  344. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  345. ** system call named zName.
  346. */
  347. static int rttSetSystemCall(
  348. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  349. const char *zName, /* Name of system call to override */
  350. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  351. ){
  352. unsigned int i;
  353. int rc = SQLITE_NOTFOUND;
  354. UNUSED_PARAMETER(pNotUsed);
  355. if( zName==0 ){
  356. /* If no zName is given, restore all system calls to their default
  357. ** settings and return NULL
  358. */
  359. rc = SQLITE_OK;
  360. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  361. if( aSyscall[i].pDefault ){
  362. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  363. }
  364. }
  365. }else{
  366. /* If zName is specified, operate on only the one system call
  367. ** specified.
  368. */
  369. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  370. if( strcmp(zName, aSyscall[i].zName)==0 ){
  371. if( aSyscall[i].pDefault==0 ){
  372. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  373. }
  374. rc = SQLITE_OK;
  375. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  376. aSyscall[i].pCurrent = pNewFunc;
  377. break;
  378. }
  379. }
  380. }
  381. return rc;
  382. }
  383. /*
  384. ** Return the value of a system call. Return NULL if zName is not a
  385. ** recognized system call name. NULL is also returned if the system call
  386. ** is currently undefined.
  387. */
  388. static sqlite3_syscall_ptr rttGetSystemCall(
  389. sqlite3_vfs *pNotUsed,
  390. const char *zName
  391. ){
  392. unsigned int i;
  393. UNUSED_PARAMETER(pNotUsed);
  394. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  395. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  396. }
  397. return 0;
  398. }
  399. /*
  400. ** Return the name of the first system call after zName. If zName==NULL
  401. ** then return the name of the first system call. Return NULL if zName
  402. ** is the last system call or if zName is not the name of a valid
  403. ** system call.
  404. */
  405. static const char *rttNextSystemCall(sqlite3_vfs *p, const char *zName){
  406. int i = -1;
  407. UNUSED_PARAMETER(p);
  408. if( zName ){
  409. for(i=0; i<ArraySize(aSyscall)-1; i++){
  410. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  411. }
  412. }
  413. for(i++; i<ArraySize(aSyscall); i++){
  414. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  415. }
  416. return 0;
  417. }
  418. /*
  419. ** The following routine suspends the current thread for at least ms
  420. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  421. */
  422. void sqlite3_rtt_sleep(int milliseconds){
  423. rt_tick_t sleep_tick;
  424. if (milliseconds <= 0)
  425. return;
  426. sleep_tick = rt_tick_from_millisecond(milliseconds);
  427. osSleep(sleep_tick);
  428. }
  429. /*
  430. ** Helper functions to obtain and relinquish the global mutex. The
  431. ** global mutex is used to protect the unixInodeInfo and
  432. ** vxworksFileId objects used by this file, all of which may be
  433. ** shared by multiple threads.
  434. **
  435. ** Function unixMutexHeld() is used to assert() that the global mutex
  436. ** is held when required. This function is only used as part of assert()
  437. ** statements. e.g.
  438. **
  439. ** unixEnterMutex()
  440. ** assert( unixMutexHeld() );
  441. ** unixEnterLeave()
  442. */
  443. static void rttEnterMutex(void){
  444. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  445. }
  446. static void rttLeaveMutex(void){
  447. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  448. }
  449. #ifdef SQLITE_DEBUG
  450. static int rttMutexHeld(void) {
  451. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  452. }
  453. #endif
  454. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  455. /*
  456. ** Helper function for printing out trace information from debugging
  457. ** binaries. This returns the string represetation of the supplied
  458. ** integer lock-type.
  459. */
  460. static const char *azFileLock(int eFileLock){
  461. switch( eFileLock ){
  462. case NO_LOCK: return "NONE";
  463. case SHARED_LOCK: return "SHARED";
  464. case RESERVED_LOCK: return "RESERVED";
  465. case PENDING_LOCK: return "PENDING";
  466. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  467. }
  468. return "ERROR";
  469. }
  470. #endif
  471. /*
  472. ** This routine translates a standard POSIX errno code into something
  473. ** useful to the clients of the sqlite3 functions. Specifically, it is
  474. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  475. ** and a variety of "please close the file descriptor NOW" errors into
  476. ** SQLITE_IOERR
  477. **
  478. ** Errors during initialization of locks, or file system support for locks,
  479. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  480. */
  481. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  482. switch (posixError) {
  483. #if 0
  484. /* At one point this code was not commented out. In theory, this branch
  485. ** should never be hit, as this function should only be called after
  486. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  487. ** the value of errno as the first argument. Since a system call has failed,
  488. ** errno should be non-zero.
  489. **
  490. ** Despite this, if errno really is zero, we still don't want to return
  491. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  492. ** propagated back to the caller. Commenting this branch out means errno==0
  493. ** will be handled by the "default:" case below.
  494. */
  495. case 0:
  496. return SQLITE_OK;
  497. #endif
  498. case EAGAIN:
  499. case ETIMEDOUT:
  500. case EBUSY:
  501. case EINTR:
  502. case ENOLCK:
  503. /* random NFS retry error, unless during file system support
  504. * introspection, in which it actually means what it says */
  505. return SQLITE_BUSY;
  506. case EACCES:
  507. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  508. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  509. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  510. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  511. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  512. return SQLITE_BUSY;
  513. }
  514. /* else fall through */
  515. case EPERM:
  516. return SQLITE_PERM;
  517. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  518. ** this module never makes such a call. And the code in SQLite itself
  519. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  520. ** this case is also commented out. If the system does set errno to EDEADLK,
  521. ** the default SQLITE_IOERR_XXX code will be returned. */
  522. #if 0
  523. case EDEADLK:
  524. return SQLITE_IOERR_BLOCKED;
  525. #endif
  526. #if EOPNOTSUPP!=ENOTSUP
  527. case EOPNOTSUPP:
  528. /* something went terribly awry, unless during file system support
  529. * introspection, in which it actually means what it says */
  530. #endif
  531. #ifdef ENOTSUP
  532. case ENOTSUP:
  533. /* invalid fd, unless during file system support introspection, in which
  534. * it actually means what it says */
  535. #endif
  536. case EIO:
  537. case EBADF:
  538. case EINVAL:
  539. case ENOTCONN:
  540. case ENODEV:
  541. case ENXIO:
  542. case ENOENT:
  543. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  544. case ESTALE:
  545. #endif
  546. case ENOSYS:
  547. /* these should force the client to close the file and reconnect */
  548. default:
  549. return sqliteIOErr;
  550. }
  551. }
  552. /*
  553. **
  554. ** This function - unixLogError_x(), is only ever called via the macro
  555. ** unixLogError().
  556. **
  557. ** It is invoked after an error occurs in an OS function and errno has been
  558. ** set. It logs a message using sqlite3_log() containing the current value of
  559. ** errno and, if possible, the human-readable equivalent from strerror() or
  560. ** strerror_r().
  561. **
  562. ** The first argument passed to the macro should be the error code that
  563. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  564. ** The two subsequent arguments should be the name of the OS function that
  565. ** failed (e.g. "unlink", "open") and the associated file-system path,
  566. ** if any.
  567. */
  568. #define rttLogError(a,b,c) rttLogErrorAtLine(a,b,c,__LINE__)
  569. static int rttLogErrorAtLine(
  570. int errcode, /* SQLite error code */
  571. const char *zFunc, /* Name of OS function that failed */
  572. const char *zPath, /* File path associated with error */
  573. int iLine /* Source line number where error occurred */
  574. ){
  575. char *zErr; /* Message from strerror() or equivalent */
  576. int iErrno = errno; /* Saved syscall error number */
  577. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  578. ** the strerror() function to obtain the human-readable error message
  579. ** equivalent to errno. Otherwise, use strerror_r().
  580. */
  581. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  582. char aErr[80];
  583. memset(aErr, 0, sizeof(aErr));
  584. zErr = aErr;
  585. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  586. ** assume that the system provides the GNU version of strerror_r() that
  587. ** returns a pointer to a buffer containing the error message. That pointer
  588. ** may point to aErr[], or it may point to some static storage somewhere.
  589. ** Otherwise, assume that the system provides the POSIX version of
  590. ** strerror_r(), which always writes an error message into aErr[].
  591. **
  592. ** If the code incorrectly assumes that it is the POSIX version that is
  593. ** available, the error message will often be an empty string. Not a
  594. ** huge problem. Incorrectly concluding that the GNU version is available
  595. ** could lead to a segfault though.
  596. */
  597. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  598. zErr =
  599. # endif
  600. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  601. #elif SQLITE_THREADSAFE
  602. /* This is a threadsafe build, but strerror_r() is not available. */
  603. zErr = "";
  604. #else
  605. /* Non-threadsafe build, use strerror(). */
  606. zErr = strerror(iErrno);
  607. #endif
  608. if( zPath==0 ) zPath = "";
  609. sqlite3_log(errcode,
  610. "os_rtt.c:%d: (%d) %s(%s) - %s",
  611. iLine, iErrno, zFunc, zPath, zErr
  612. );
  613. return errcode;
  614. }
  615. static int robust_ftruncate(int h, sqlite3_int64 sz){
  616. int rc;
  617. rc = -1;
  618. return rc;
  619. }
  620. /*
  621. ** Close a file descriptor.
  622. **
  623. ** We assume that close() almost always works, since it is only in a
  624. ** very sick application or on a very sick platform that it might fail.
  625. ** If it does fail, simply leak the file descriptor, but do log the
  626. ** error.
  627. **
  628. ** Note that it is not safe to retry close() after EINTR since the
  629. ** file descriptor might have already been reused by another thread.
  630. ** So we don't even try to recover from an EINTR. Just log the error
  631. ** and move on.
  632. */
  633. static void robust_close(rttFile *pFile, int h, int lineno){
  634. if( osClose(h) ){
  635. rttLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  636. pFile ? pFile->zPath : 0, lineno);
  637. }
  638. }
  639. /*
  640. ** Check a rttFile that is a database. Verify the following:
  641. **
  642. ** (1) There is exactly one hard link on the file
  643. ** (2) The file is not a symbolic link
  644. ** (3) The file has not been renamed or unlinked
  645. **
  646. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  647. */
  648. static void verifyDbFile(rttFile *pFile){
  649. struct stat buf;
  650. int rc;
  651. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  652. /* One or more of the following warnings have already been issued. Do not
  653. ** repeat them so as not to clutter the error log */
  654. return;
  655. }
  656. rc = osFstat(pFile->h, &buf);
  657. if( rc!=0 ){
  658. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  659. pFile->ctrlFlags |= UNIXFILE_WARNED;
  660. return;
  661. }
  662. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  663. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  664. pFile->ctrlFlags |= UNIXFILE_WARNED;
  665. return;
  666. }
  667. }
  668. /*
  669. ** This function performs the parts of the "close file" operation
  670. ** common to all locking schemes. It closes the directory and file
  671. ** handles, if they are valid, and sets all fields of the rttFile
  672. ** structure to 0.
  673. **
  674. ** It is *not* necessary to hold the mutex when this routine is called,
  675. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  676. ** vxworksReleaseFileId() routine.
  677. */
  678. static int closeRttFile(sqlite3_file *id){
  679. rttFile *pFile = (rttFile*)id;
  680. if( pFile->h>=0 ){
  681. robust_close(pFile, pFile->h, __LINE__);
  682. pFile->h = -1;
  683. }
  684. OSTRACE(("CLOSE %-3d\n", pFile->h));
  685. OpenCounter(-1);
  686. memset(pFile, 0, sizeof(rttFile));
  687. return SQLITE_OK;
  688. }
  689. /************** End of the posix advisory lock implementation *****************
  690. ******************************************************************************/
  691. /******************************************************************************
  692. ****************************** No-op Locking **********************************
  693. **
  694. ** Of the various locking implementations available, this is by far the
  695. ** simplest: locking is ignored. No attempt is made to lock the database
  696. ** file for reading or writing.
  697. **
  698. ** This locking mode is appropriate for use on read-only databases
  699. ** (ex: databases that are burned into CD-ROM, for example.) It can
  700. ** also be used if the application employs some external mechanism to
  701. ** prevent simultaneous access of the same database by two or more
  702. ** database connections. But there is a serious risk of database
  703. ** corruption if this locking mode is used in situations where multiple
  704. ** database connections are accessing the same database file at the same
  705. ** time and one or more of those connections are writing.
  706. */
  707. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  708. UNUSED_PARAMETER(NotUsed);
  709. *pResOut = 0;
  710. return SQLITE_OK;
  711. }
  712. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  713. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  714. return SQLITE_OK;
  715. }
  716. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  717. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  718. return SQLITE_OK;
  719. }
  720. /*
  721. ** Close the file.
  722. */
  723. static int nolockClose(sqlite3_file *id) {
  724. return closeRttFile(id);
  725. }
  726. /******************* End of the no-op lock implementation *********************
  727. ******************************************************************************/
  728. /******************************************************************************
  729. ************************* Begin dot-file Locking ******************************
  730. **
  731. ** The dotfile locking implementation uses the existence of separate lock
  732. ** files (really a directory) to control access to the database. This works
  733. ** on just about every filesystem imaginable. But there are serious downsides:
  734. **
  735. ** (1) There is zero concurrency. A single reader blocks all other
  736. ** connections from reading or writing the database.
  737. **
  738. ** (2) An application crash or power loss can leave stale lock files
  739. ** sitting around that need to be cleared manually.
  740. **
  741. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  742. ** other locking strategy is available.
  743. **
  744. ** Dotfile locking works by creating a subdirectory in the same directory as
  745. ** the database and with the same name but with a ".lock" extension added.
  746. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  747. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  748. */
  749. /*
  750. ** The file suffix added to the data base filename in order to create the
  751. ** lock directory.
  752. */
  753. #define DOTLOCK_SUFFIX ".lock"
  754. /*
  755. ** This routine checks if there is a RESERVED lock held on the specified
  756. ** file by this or any other process. If such a lock is held, set *pResOut
  757. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  758. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  759. **
  760. ** In dotfile locking, either a lock exists or it does not. So in this
  761. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  762. ** is held on the file and false if the file is unlocked.
  763. */
  764. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  765. int rc = SQLITE_OK;
  766. int reserved = 0;
  767. rttFile *pFile = (rttFile*)id;
  768. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  769. assert( pFile );
  770. /* Check if a thread in this process holds such a lock */
  771. if( pFile->eFileLock>SHARED_LOCK ){
  772. /* Either this connection or some other connection in the same process
  773. ** holds a lock on the file. No need to check further. */
  774. reserved = 1;
  775. }else{
  776. /* The lock is held if and only if the lockfile exists */
  777. const char *zLockFile = (const char*)pFile->lockingContext;
  778. reserved = 0;
  779. }
  780. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  781. *pResOut = reserved;
  782. return rc;
  783. }
  784. /*
  785. ** Lock the file with the lock specified by parameter eFileLock - one
  786. ** of the following:
  787. **
  788. ** (1) SHARED_LOCK
  789. ** (2) RESERVED_LOCK
  790. ** (3) PENDING_LOCK
  791. ** (4) EXCLUSIVE_LOCK
  792. **
  793. ** Sometimes when requesting one lock state, additional lock states
  794. ** are inserted in between. The locking might fail on one of the later
  795. ** transitions leaving the lock state different from what it started but
  796. ** still short of its goal. The following chart shows the allowed
  797. ** transitions and the inserted intermediate states:
  798. **
  799. ** UNLOCKED -> SHARED
  800. ** SHARED -> RESERVED
  801. ** SHARED -> (PENDING) -> EXCLUSIVE
  802. ** RESERVED -> (PENDING) -> EXCLUSIVE
  803. ** PENDING -> EXCLUSIVE
  804. **
  805. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  806. ** routine to lower a locking level.
  807. **
  808. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  809. ** But we track the other locking levels internally.
  810. */
  811. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  812. rttFile *pFile = (rttFile*)id;
  813. char *zLockFile = (char *)pFile->lockingContext;
  814. int rc = SQLITE_OK;
  815. /* If we have any lock, then the lock file already exists. All we have
  816. ** to do is adjust our internal record of the lock level.
  817. */
  818. if( pFile->eFileLock > NO_LOCK ){
  819. pFile->eFileLock = eFileLock;
  820. return SQLITE_OK;
  821. }
  822. /* grab an exclusive lock */
  823. rc = osMkdir(zLockFile, 0777);
  824. if( rc<0 ){
  825. /* failed to open/create the lock directory */
  826. int tErrno = errno;
  827. if( EEXIST == tErrno ){
  828. rc = SQLITE_BUSY;
  829. } else {
  830. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  831. if( IS_LOCK_ERROR(rc) ){
  832. pFile->lastErrno = tErrno;
  833. }
  834. }
  835. return rc;
  836. }
  837. /* got it, set the type and return ok */
  838. pFile->eFileLock = eFileLock;
  839. return rc;
  840. }
  841. /*
  842. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  843. ** must be either NO_LOCK or SHARED_LOCK.
  844. **
  845. ** If the locking level of the file descriptor is already at or below
  846. ** the requested locking level, this routine is a no-op.
  847. **
  848. ** When the locking level reaches NO_LOCK, delete the lock file.
  849. */
  850. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  851. rttFile *pFile = (rttFile*)id;
  852. char *zLockFile = (char *)pFile->lockingContext;
  853. int rc;
  854. assert( pFile );
  855. OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock,
  856. pFile->eFileLock, rt_thread_self()->name ));
  857. assert( eFileLock<=SHARED_LOCK );
  858. /* no-op if possible */
  859. if( pFile->eFileLock==eFileLock ){
  860. return SQLITE_OK;
  861. }
  862. /* To downgrade to shared, simply update our internal notion of the
  863. ** lock state. No need to mess with the file on disk.
  864. */
  865. if( eFileLock==SHARED_LOCK ){
  866. pFile->eFileLock = SHARED_LOCK;
  867. return SQLITE_OK;
  868. }
  869. /* To fully unlock the database, delete the lock file */
  870. assert( eFileLock==NO_LOCK );
  871. rc = osRmdir(zLockFile);
  872. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  873. if( rc<0 ){
  874. int tErrno = errno;
  875. rc = 0;
  876. if( ENOENT != tErrno ){
  877. rc = SQLITE_IOERR_UNLOCK;
  878. }
  879. if( IS_LOCK_ERROR(rc) ){
  880. pFile->lastErrno = tErrno;
  881. }
  882. return rc;
  883. }
  884. pFile->eFileLock = NO_LOCK;
  885. return SQLITE_OK;
  886. }
  887. /*
  888. ** Close a file. Make sure the lock has been released before closing.
  889. */
  890. static int dotlockClose(sqlite3_file *id) {
  891. int rc = SQLITE_OK;
  892. if( id ){
  893. rttFile *pFile = (rttFile*)id;
  894. dotlockUnlock(id, NO_LOCK);
  895. sqlite3_free(pFile->lockingContext);
  896. rc = closeRttFile(id);
  897. }
  898. return rc;
  899. }
  900. /****************** End of the dot-file lock implementation *******************
  901. ******************************************************************************/
  902. /******************************************************************************
  903. ************************** Begin flock Locking ********************************
  904. **
  905. ** Use the flock() system call to do file locking.
  906. **
  907. ** flock() locking is like dot-file locking in that the various
  908. ** fine-grain locking levels supported by SQLite are collapsed into
  909. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  910. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  911. ** still works when you do this, but concurrency is reduced since
  912. ** only a single process can be reading the database at a time.
  913. **
  914. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  915. ** compiling for VXWORKS.
  916. */
  917. #if SQLITE_ENABLE_LOCKING_STYLE
  918. #warning "rtt file lock not available"
  919. /*
  920. ** Retry flock() calls that fail with EINTR
  921. */
  922. static int robust_flock(int fd, int op){
  923. int rc = 0;
  924. return rc;
  925. }
  926. /*
  927. ** This routine checks if there is a RESERVED lock held on the specified
  928. ** file by this or any other process. If such a lock is held, set *pResOut
  929. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  930. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  931. */
  932. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  933. int rc = SQLITE_OK;
  934. int reserved = 0;
  935. rttFile *pFile = (rttFile*)id;
  936. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  937. assert( pFile );
  938. /* Check if a thread in this process holds such a lock */
  939. if( pFile->eFileLock>SHARED_LOCK ){
  940. reserved = 1;
  941. }
  942. /* Otherwise see if some other process holds it. */
  943. if( !reserved ){
  944. /* attempt to get the lock */
  945. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  946. if( !lrc ){
  947. /* got the lock, unlock it */
  948. lrc = robust_flock(pFile->h, LOCK_UN);
  949. if ( lrc ) {
  950. int tErrno = errno;
  951. /* unlock failed with an error */
  952. lrc = SQLITE_IOERR_UNLOCK;
  953. if( IS_LOCK_ERROR(lrc) ){
  954. pFile->lastErrno = tErrno;
  955. rc = lrc;
  956. }
  957. }
  958. } else {
  959. int tErrno = errno;
  960. reserved = 1;
  961. /* someone else might have it reserved */
  962. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  963. if( IS_LOCK_ERROR(lrc) ){
  964. pFile->lastErrno = tErrno;
  965. rc = lrc;
  966. }
  967. }
  968. }
  969. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  970. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  971. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  972. rc = SQLITE_OK;
  973. reserved=1;
  974. }
  975. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  976. *pResOut = reserved;
  977. return rc;
  978. }
  979. /*
  980. ** Lock the file with the lock specified by parameter eFileLock - one
  981. ** of the following:
  982. **
  983. ** (1) SHARED_LOCK
  984. ** (2) RESERVED_LOCK
  985. ** (3) PENDING_LOCK
  986. ** (4) EXCLUSIVE_LOCK
  987. **
  988. ** Sometimes when requesting one lock state, additional lock states
  989. ** are inserted in between. The locking might fail on one of the later
  990. ** transitions leaving the lock state different from what it started but
  991. ** still short of its goal. The following chart shows the allowed
  992. ** transitions and the inserted intermediate states:
  993. **
  994. ** UNLOCKED -> SHARED
  995. ** SHARED -> RESERVED
  996. ** SHARED -> (PENDING) -> EXCLUSIVE
  997. ** RESERVED -> (PENDING) -> EXCLUSIVE
  998. ** PENDING -> EXCLUSIVE
  999. **
  1000. ** flock() only really support EXCLUSIVE locks. We track intermediate
  1001. ** lock states in the sqlite3_file structure, but all locks SHARED or
  1002. ** above are really EXCLUSIVE locks and exclude all other processes from
  1003. ** access the file.
  1004. **
  1005. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  1006. ** routine to lower a locking level.
  1007. */
  1008. static int flockLock(sqlite3_file *id, int eFileLock) {
  1009. int rc = SQLITE_OK;
  1010. rttFile *pFile = (rttFile*)id;
  1011. assert( pFile );
  1012. /* if we already have a lock, it is exclusive.
  1013. ** Just adjust level and punt on outta here. */
  1014. if (pFile->eFileLock > NO_LOCK) {
  1015. pFile->eFileLock = eFileLock;
  1016. return SQLITE_OK;
  1017. }
  1018. /* grab an exclusive lock */
  1019. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  1020. int tErrno = errno;
  1021. /* didn't get, must be busy */
  1022. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  1023. if( IS_LOCK_ERROR(rc) ){
  1024. pFile->lastErrno = tErrno;
  1025. }
  1026. } else {
  1027. /* got it, set the type and return ok */
  1028. pFile->eFileLock = eFileLock;
  1029. }
  1030. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  1031. rc==SQLITE_OK ? "ok" : "failed"));
  1032. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  1033. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  1034. rc = SQLITE_BUSY;
  1035. }
  1036. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  1037. return rc;
  1038. }
  1039. /*
  1040. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  1041. ** must be either NO_LOCK or SHARED_LOCK.
  1042. **
  1043. ** If the locking level of the file descriptor is already at or below
  1044. ** the requested locking level, this routine is a no-op.
  1045. */
  1046. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  1047. rttFile *pFile = (rttFile*)id;
  1048. assert( pFile );
  1049. OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock,
  1050. pFile->eFileLock, rt_thread_self()->name));
  1051. assert( eFileLock<=SHARED_LOCK );
  1052. /* no-op if possible */
  1053. if( pFile->eFileLock==eFileLock ){
  1054. return SQLITE_OK;
  1055. }
  1056. /* shared can just be set because we always have an exclusive */
  1057. if (eFileLock==SHARED_LOCK) {
  1058. pFile->eFileLock = eFileLock;
  1059. return SQLITE_OK;
  1060. }
  1061. /* no, really, unlock. */
  1062. if( robust_flock(pFile->h, LOCK_UN) ){
  1063. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  1064. return SQLITE_OK;
  1065. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  1066. return SQLITE_IOERR_UNLOCK;
  1067. }else{
  1068. pFile->eFileLock = NO_LOCK;
  1069. return SQLITE_OK;
  1070. }
  1071. }
  1072. /*
  1073. ** Close a file.
  1074. */
  1075. static int flockClose(sqlite3_file *id) {
  1076. int rc = SQLITE_OK;
  1077. if( id ){
  1078. flockUnlock(id, NO_LOCK);
  1079. rc = closeRttFile(id);
  1080. }
  1081. return rc;
  1082. }
  1083. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  1084. /******************* End of the flock lock implementation *********************
  1085. ******************************************************************************/
  1086. /******************************************************************************
  1087. **************** Non-locking sqlite3_file methods *****************************
  1088. **
  1089. ** The next division contains implementations for all methods of the
  1090. ** sqlite3_file object other than the locking methods. The locking
  1091. ** methods were defined in divisions above (one locking method per
  1092. ** division). Those methods that are common to all locking modes
  1093. ** are gather together into this division.
  1094. */
  1095. /*
  1096. ** Seek to the offset passed as the second argument, then read cnt
  1097. ** bytes into pBuf. Return the number of bytes actually read.
  1098. **
  1099. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  1100. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  1101. ** one system to another. Since SQLite does not define USE_PREAD
  1102. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  1103. ** See tickets #2741 and #2681.
  1104. **
  1105. ** To avoid stomping the errno value on a failed read the lastErrno value
  1106. ** is set before returning.
  1107. */
  1108. static int seekAndRead(rttFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  1109. int got;
  1110. int prior = 0;
  1111. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  1112. i64 newOffset;
  1113. #endif
  1114. TIMER_START;
  1115. assert( cnt==(cnt&0x1ffff) );
  1116. assert( id->h>2 );
  1117. cnt &= 0x1ffff;
  1118. do{
  1119. #if defined(USE_PREAD)
  1120. #error "rtt pread not support"
  1121. got = osPread(id->h, pBuf, cnt, offset);
  1122. SimulateIOError( got = -1 );
  1123. #elif defined(USE_PREAD64)
  1124. #error "rtt pread64 not support"
  1125. got = osPread64(id->h, pBuf, cnt, offset);
  1126. SimulateIOError( got = -1 );
  1127. #else
  1128. newOffset = lseek(id->h, offset, SEEK_SET);
  1129. SimulateIOError( newOffset-- );
  1130. if( newOffset!=offset ){
  1131. if( newOffset == -1 ){
  1132. ((rttFile*)id)->lastErrno = errno;
  1133. }else{
  1134. ((rttFile*)id)->lastErrno = 0;
  1135. }
  1136. return -1;
  1137. }
  1138. got = osRead(id->h, pBuf, cnt);
  1139. #endif
  1140. if( got==cnt ) break;
  1141. if( got<0 ){
  1142. if( errno==EINTR ){ got = 1; continue; }
  1143. prior = 0;
  1144. ((rttFile*)id)->lastErrno = errno;
  1145. break;
  1146. }else if( got>0 ){
  1147. cnt -= got;
  1148. offset += got;
  1149. prior += got;
  1150. pBuf = (void*)(got + (char*)pBuf);
  1151. }
  1152. }while( got>0 );
  1153. TIMER_END;
  1154. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  1155. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  1156. return got+prior;
  1157. }
  1158. /*
  1159. ** Read data from a file into a buffer. Return SQLITE_OK if all
  1160. ** bytes were read successfully and SQLITE_IOERR if anything goes
  1161. ** wrong.
  1162. */
  1163. static int rttRead(
  1164. sqlite3_file *id,
  1165. void *pBuf,
  1166. int amt,
  1167. sqlite3_int64 offset
  1168. ){
  1169. rttFile *pFile = (rttFile *)id;
  1170. int got;
  1171. assert( id );
  1172. assert( offset>=0 );
  1173. assert( amt>0 );
  1174. got = seekAndRead(pFile, offset, pBuf, amt);
  1175. if( got==amt ){
  1176. return SQLITE_OK;
  1177. }else if( got<0 ){
  1178. /* lastErrno set by seekAndRead */
  1179. return SQLITE_IOERR_READ;
  1180. }else{
  1181. pFile->lastErrno = 0; /* not a system error */
  1182. /* Unread parts of the buffer must be zero-filled */
  1183. memset(&((char*)pBuf)[got], 0, amt-got);
  1184. return SQLITE_IOERR_SHORT_READ;
  1185. }
  1186. }
  1187. /*
  1188. ** Attempt to seek the file-descriptor passed as the first argument to
  1189. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  1190. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  1191. ** return the actual number of bytes written (which may be less than
  1192. ** nBuf).
  1193. */
  1194. static int seekAndWriteFd(
  1195. int fd, /* File descriptor to write to */
  1196. i64 iOff, /* File offset to begin writing at */
  1197. const void *pBuf, /* Copy data from this buffer to the file */
  1198. int nBuf, /* Size of buffer pBuf in bytes */
  1199. int *piErrno /* OUT: Error number if error occurs */
  1200. ){
  1201. int rc = 0; /* Value returned by system call */
  1202. assert( nBuf==(nBuf&0x1ffff) );
  1203. assert( fd>2 );
  1204. nBuf &= 0x1ffff;
  1205. TIMER_START;
  1206. #if defined(USE_PREAD)
  1207. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  1208. #elif defined(USE_PREAD64)
  1209. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  1210. #else
  1211. do{
  1212. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  1213. SimulateIOError( iSeek-- );
  1214. if( iSeek!=iOff ){
  1215. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  1216. return -1;
  1217. }
  1218. rc = osWrite(fd, pBuf, nBuf);
  1219. }while( rc<0 && errno==EINTR );
  1220. #endif
  1221. TIMER_END;
  1222. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  1223. if( rc<0 && piErrno ) *piErrno = errno;
  1224. return rc;
  1225. }
  1226. /*
  1227. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  1228. ** Return the number of bytes actually read. Update the offset.
  1229. **
  1230. ** To avoid stomping the errno value on a failed write the lastErrno value
  1231. ** is set before returning.
  1232. */
  1233. static int seekAndWrite(rttFile *id, i64 offset, const void *pBuf, int cnt){
  1234. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  1235. }
  1236. /*
  1237. ** Write data from a buffer into a file. Return SQLITE_OK on success
  1238. ** or some other error code on failure.
  1239. */
  1240. static int rttWrite(
  1241. sqlite3_file *id,
  1242. const void *pBuf,
  1243. int amt,
  1244. sqlite3_int64 offset
  1245. ){
  1246. rttFile *pFile = (rttFile*)id;
  1247. int wrote = 0;
  1248. assert( id );
  1249. assert( amt>0 );
  1250. #ifdef SQLITE_DEBUG
  1251. /* If we are doing a normal write to a database file (as opposed to
  1252. ** doing a hot-journal rollback or a write to some file other than a
  1253. ** normal database file) then record the fact that the database
  1254. ** has changed. If the transaction counter is modified, record that
  1255. ** fact too.
  1256. */
  1257. if( pFile->inNormalWrite ){
  1258. pFile->dbUpdate = 1; /* The database has been modified */
  1259. if( offset<=24 && offset+amt>=27 ){
  1260. int rc;
  1261. char oldCntr[4];
  1262. SimulateIOErrorBenign(1);
  1263. rc = seekAndRead(pFile, 24, oldCntr, 4);
  1264. SimulateIOErrorBenign(0);
  1265. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  1266. pFile->transCntrChng = 1; /* The transaction counter has changed */
  1267. }
  1268. }
  1269. }
  1270. #endif
  1271. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  1272. amt -= wrote;
  1273. offset += wrote;
  1274. pBuf = &((char*)pBuf)[wrote];
  1275. }
  1276. SimulateIOError(( wrote=(-1), amt=1 ));
  1277. SimulateDiskfullError(( wrote=0, amt=1 ));
  1278. if( amt>0 ){
  1279. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  1280. /* lastErrno set by seekAndWrite */
  1281. return SQLITE_IOERR_WRITE;
  1282. }else{
  1283. pFile->lastErrno = 0; /* not a system error */
  1284. return SQLITE_FULL;
  1285. }
  1286. }
  1287. return SQLITE_OK;
  1288. }
  1289. #ifdef SQLITE_TEST
  1290. /*
  1291. ** Count the number of fullsyncs and normal syncs. This is used to test
  1292. ** that syncs and fullsyncs are occurring at the right times.
  1293. */
  1294. int sqlite3_sync_count = 0;
  1295. int sqlite3_fullsync_count = 0;
  1296. #endif
  1297. /*
  1298. ** We do not trust systems to provide a working fdatasync(). Some do.
  1299. ** Others do no. To be safe, we will stick with the (slightly slower)
  1300. ** fsync(). If you know that your system does support fdatasync() correctly,
  1301. ** then simply compile with -Dfdatasync=fdatasync
  1302. */
  1303. #if !defined(fdatasync)
  1304. #include "dfs.h"
  1305. #include "dfs_file.h"
  1306. int fdatasync(fd)
  1307. {
  1308. struct dfs_fd *dfs_fd;
  1309. dfs_fd = fd_get(fd);
  1310. return dfs_file_flush(dfs_fd);
  1311. }
  1312. #endif
  1313. /*
  1314. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  1315. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  1316. ** only available on Mac OS X. But that could change.
  1317. */
  1318. #ifdef F_FULLFSYNC
  1319. # define HAVE_FULLFSYNC 0
  1320. #endif
  1321. /*
  1322. ** The fsync() system call does not work as advertised on many
  1323. ** unix systems. The following procedure is an attempt to make
  1324. ** it work better.
  1325. **
  1326. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  1327. ** for testing when we want to run through the test suite quickly.
  1328. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  1329. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  1330. ** or power failure will likely corrupt the database file.
  1331. **
  1332. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  1333. ** The idea behind dataOnly is that it should only write the file content
  1334. ** to disk, not the inode. We only set dataOnly if the file size is
  1335. ** unchanged since the file size is part of the inode. However,
  1336. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  1337. ** file size has changed. The only real difference between fdatasync()
  1338. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  1339. ** inode if the mtime or owner or other inode attributes have changed.
  1340. ** We only care about the file size, not the other file attributes, so
  1341. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  1342. ** So, we always use fdatasync() if it is available, regardless of
  1343. ** the value of the dataOnly flag.
  1344. */
  1345. static int full_fsync(int fd, int fullSync, int dataOnly){
  1346. int rc;
  1347. /* The following "ifdef/elif/else/" block has the same structure as
  1348. ** the one below. It is replicated here solely to avoid cluttering
  1349. ** up the real code with the UNUSED_PARAMETER() macros.
  1350. */
  1351. #ifdef SQLITE_NO_SYNC
  1352. UNUSED_PARAMETER(fd);
  1353. UNUSED_PARAMETER(fullSync);
  1354. UNUSED_PARAMETER(dataOnly);
  1355. #elif HAVE_FULLFSYNC
  1356. UNUSED_PARAMETER(dataOnly);
  1357. #else
  1358. UNUSED_PARAMETER(fullSync);
  1359. UNUSED_PARAMETER(dataOnly);
  1360. #endif
  1361. /* Record the number of times that we do a normal fsync() and
  1362. ** FULLSYNC. This is used during testing to verify that this procedure
  1363. ** gets called with the correct arguments.
  1364. */
  1365. #ifdef SQLITE_TEST
  1366. if( fullSync ) sqlite3_fullsync_count++;
  1367. sqlite3_sync_count++;
  1368. #endif
  1369. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  1370. ** no-op
  1371. */
  1372. #ifdef SQLITE_NO_SYNC
  1373. rc = SQLITE_OK;
  1374. #elif HAVE_FULLFSYNC
  1375. #error "rtt not support FULLFSYNC"
  1376. #else
  1377. rc = fdatasync(fd);
  1378. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  1379. return rc;
  1380. }
  1381. /*
  1382. ** Make sure all writes to a particular file are committed to disk.
  1383. **
  1384. ** If dataOnly==0 then both the file itself and its metadata (file
  1385. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  1386. ** file data is synced.
  1387. **
  1388. ** Under Rtt, also make sure that the directory entry for the file
  1389. ** has been created by fsync-ing the directory that contains the file.
  1390. ** If we do not do this and we encounter a power failure, the directory
  1391. ** entry for the journal might not exist after we reboot. The next
  1392. ** SQLite to access the file will not know that the journal exists (because
  1393. ** the directory entry for the journal was never created) and the transaction
  1394. ** will not roll back - possibly leading to database corruption.
  1395. */
  1396. static int rttSync(sqlite3_file *id, int flags){
  1397. int rc;
  1398. rttFile *pFile = (rttFile*)id;
  1399. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  1400. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  1401. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  1402. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  1403. || (flags&0x0F)==SQLITE_SYNC_FULL
  1404. );
  1405. /* Rtt cannot, but some systems may return SQLITE_FULL from here. This
  1406. ** line is to test that doing so does not cause any problems.
  1407. */
  1408. SimulateDiskfullError( return SQLITE_FULL );
  1409. assert( pFile );
  1410. OSTRACE(("SYNC %-3d\n", pFile->h));
  1411. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  1412. SimulateIOError( rc=1 );
  1413. if( rc ){
  1414. pFile->lastErrno = errno;
  1415. return rttLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  1416. }
  1417. /* Also fsync the directory containing the file if the DIRSYNC flag
  1418. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  1419. ** are unable to fsync a directory, so ignore errors on the fsync.
  1420. */
  1421. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  1422. int dirfd;
  1423. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  1424. HAVE_FULLFSYNC, isFullsync));
  1425. rc = osOpenDirectory(pFile->zPath, &dirfd);
  1426. if( rc==SQLITE_OK && dirfd>=0 ){
  1427. full_fsync(dirfd, 0, 0);
  1428. robust_close(pFile, dirfd, __LINE__);
  1429. }else if( rc==SQLITE_CANTOPEN ){
  1430. rc = SQLITE_OK;
  1431. }
  1432. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  1433. }
  1434. return rc;
  1435. }
  1436. /*
  1437. ** Truncate an open file to a specified size
  1438. */
  1439. static int rttTruncate(sqlite3_file *id, i64 nByte){
  1440. rttFile *pFile = (rttFile *)id;
  1441. int rc;
  1442. assert( pFile );
  1443. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  1444. /* If the user has configured a chunk-size for this file, truncate the
  1445. ** file so that it consists of an integer number of chunks (i.e. the
  1446. ** actual file size after the operation may be larger than the requested
  1447. ** size).
  1448. */
  1449. if( pFile->szChunk>0 ){
  1450. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  1451. }
  1452. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  1453. if( rc ){
  1454. pFile->lastErrno = errno;
  1455. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  1456. }else{
  1457. #ifdef SQLITE_DEBUG
  1458. /* If we are doing a normal write to a database file (as opposed to
  1459. ** doing a hot-journal rollback or a write to some file other than a
  1460. ** normal database file) and we truncate the file to zero length,
  1461. ** that effectively updates the change counter. This might happen
  1462. ** when restoring a database using the backup API from a zero-length
  1463. ** source.
  1464. */
  1465. if( pFile->inNormalWrite && nByte==0 ){
  1466. pFile->transCntrChng = 1;
  1467. }
  1468. #endif
  1469. return SQLITE_OK;
  1470. }
  1471. }
  1472. /*
  1473. ** Determine the current size of a file in bytes
  1474. */
  1475. static int rttFileSize(sqlite3_file *id, i64 *pSize){
  1476. int rc;
  1477. struct stat buf;
  1478. assert( id );
  1479. rc = osFstat(((rttFile*)id)->h, &buf);
  1480. SimulateIOError( rc=1 );
  1481. if( rc!=0 ){
  1482. ((rttFile*)id)->lastErrno = errno;
  1483. return SQLITE_IOERR_FSTAT;
  1484. }
  1485. *pSize = buf.st_size;
  1486. /* When opening a zero-size database, the findInodeInfo() procedure
  1487. ** writes a single byte into that file in order to work around a bug
  1488. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  1489. ** layers, we need to report this file size as zero even though it is
  1490. ** really 1. Ticket #3260.
  1491. */
  1492. if( *pSize==1 ) *pSize = 0;
  1493. return SQLITE_OK;
  1494. }
  1495. /*
  1496. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  1497. ** file-control operation. Enlarge the database to nBytes in size
  1498. ** (rounded up to the next chunk-size). If the database is already
  1499. ** nBytes or larger, this routine is a no-op.
  1500. */
  1501. static int fcntlSizeHint(rttFile *pFile, i64 nByte){
  1502. if( pFile->szChunk>0 ){
  1503. i64 nSize; /* Required file size */
  1504. struct stat buf; /* Used to hold return values of fstat() */
  1505. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  1506. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  1507. if( nSize>(i64)buf.st_size ){
  1508. /* If the OS does not have posix_fallocate(), fake it. First use
  1509. ** ftruncate() to set the file size, then write a single byte to
  1510. ** the last byte in each block within the extended region. This
  1511. ** is the same technique used by glibc to implement posix_fallocate()
  1512. ** on systems that do not have a real fallocate() system call.
  1513. */
  1514. int nBlk = buf.st_blksize; /* File-system block size */
  1515. i64 iWrite; /* Next offset to write to */
  1516. if( robust_ftruncate(pFile->h, nSize) ){
  1517. pFile->lastErrno = errno;
  1518. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  1519. }
  1520. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  1521. while( iWrite<nSize ){
  1522. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  1523. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  1524. iWrite += nBlk;
  1525. }
  1526. }
  1527. }
  1528. return SQLITE_OK;
  1529. }
  1530. /*
  1531. ** If *pArg is inititially negative then this is a query. Set *pArg to
  1532. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  1533. **
  1534. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  1535. */
  1536. static void rttModeBit(rttFile *pFile, unsigned char mask, int *pArg){
  1537. if( *pArg<0 ){
  1538. *pArg = (pFile->ctrlFlags & mask)!=0;
  1539. }else if( (*pArg)==0 ){
  1540. pFile->ctrlFlags &= ~mask;
  1541. }else{
  1542. pFile->ctrlFlags |= mask;
  1543. }
  1544. }
  1545. /* Forward declaration */
  1546. static int rttGetTempname(int nBuf, char *zBuf);
  1547. /*
  1548. ** Information and control of an open file handle.
  1549. */
  1550. static int rttFileControl(sqlite3_file *id, int op, void *pArg){
  1551. rttFile *pFile = (rttFile*)id;
  1552. switch( op ){
  1553. case SQLITE_FCNTL_LOCKSTATE: {
  1554. *(int*)pArg = pFile->eFileLock;
  1555. return SQLITE_OK;
  1556. }
  1557. case SQLITE_LAST_ERRNO: {
  1558. *(int*)pArg = pFile->lastErrno;
  1559. return SQLITE_OK;
  1560. }
  1561. case SQLITE_FCNTL_CHUNK_SIZE: {
  1562. pFile->szChunk = *(int *)pArg;
  1563. return SQLITE_OK;
  1564. }
  1565. case SQLITE_FCNTL_SIZE_HINT: {
  1566. int rc;
  1567. SimulateIOErrorBenign(1);
  1568. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  1569. SimulateIOErrorBenign(0);
  1570. return rc;
  1571. }
  1572. case SQLITE_FCNTL_PERSIST_WAL: {
  1573. rttModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  1574. return SQLITE_OK;
  1575. }
  1576. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  1577. rttModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  1578. return SQLITE_OK;
  1579. }
  1580. case SQLITE_FCNTL_VFSNAME: {
  1581. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  1582. return SQLITE_OK;
  1583. }
  1584. case SQLITE_FCNTL_TEMPFILENAME: {
  1585. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  1586. if( zTFile ){
  1587. rttGetTempname(pFile->pVfs->mxPathname, zTFile);
  1588. *(char**)pArg = zTFile;
  1589. }
  1590. return SQLITE_OK;
  1591. }
  1592. #ifdef SQLITE_DEBUG
  1593. /* The pager calls this method to signal that it has done
  1594. ** a rollback and that the database is therefore unchanged and
  1595. ** it hence it is OK for the transaction change counter to be
  1596. ** unchanged.
  1597. */
  1598. case SQLITE_FCNTL_DB_UNCHANGED: {
  1599. ((rttFile*)id)->dbUpdate = 0;
  1600. return SQLITE_OK;
  1601. }
  1602. #endif
  1603. }
  1604. return SQLITE_NOTFOUND;
  1605. }
  1606. /*
  1607. ** Return the sector size in bytes of the underlying block device for
  1608. ** the specified file. This is almost always 512 bytes, but may be
  1609. ** larger for some devices.
  1610. **
  1611. ** SQLite code assumes this function cannot fail. It also assumes that
  1612. ** if two files are created in the same file-system directory (i.e.
  1613. ** a database and its journal file) that the sector size will be the
  1614. ** same for both.
  1615. */
  1616. static int rttSectorSize(sqlite3_file *NotUsed){
  1617. UNUSED_PARAMETER(NotUsed);
  1618. return SQLITE_DEFAULT_SECTOR_SIZE;
  1619. }
  1620. /*
  1621. ** Return the device characteristics for the file.
  1622. **
  1623. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  1624. ** However, that choice is contraversial since technically the underlying
  1625. ** file system does not always provide powersafe overwrites. (In other
  1626. ** words, after a power-loss event, parts of the file that were never
  1627. ** written might end up being altered.) However, non-PSOW behavior is very,
  1628. ** very rare. And asserting PSOW makes a large reduction in the amount
  1629. ** of required I/O for journaling, since a lot of padding is eliminated.
  1630. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  1631. ** available to turn it off and URI query parameter available to turn it off.
  1632. */
  1633. static int rttDeviceCharacteristics(sqlite3_file *id){
  1634. rttFile *p = (rttFile*)id;
  1635. int rc = 0;
  1636. if( p->ctrlFlags & UNIXFILE_PSOW ){
  1637. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  1638. }
  1639. return rc;
  1640. }
  1641. #ifndef SQLITE_OMIT_WAL
  1642. # error "WAL mode requires not support from the rt-thread, compile\
  1643. with SQLITE_OMIT_WAL."
  1644. #else
  1645. # define rttShmMap 0
  1646. # define rttShmLock 0
  1647. # define rttShmBarrier 0
  1648. # define rttShmUnmap 0
  1649. #endif /* #ifndef SQLITE_OMIT_WAL */
  1650. #if SQLITE_MAX_MMAP_SIZE>0
  1651. #error "rtt not spportt mmap"
  1652. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  1653. /*
  1654. ** If possible, return a pointer to a mapping of file fd starting at offset
  1655. ** iOff. The mapping must be valid for at least nAmt bytes.
  1656. **
  1657. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  1658. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  1659. ** Finally, if an error does occur, return an SQLite error code. The final
  1660. ** value of *pp is undefined in this case.
  1661. **
  1662. ** If this function does return a pointer, the caller must eventually
  1663. ** release the reference by calling unixUnfetch().
  1664. */
  1665. static int rttFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  1666. *pp = 0;
  1667. return SQLITE_OK;
  1668. }
  1669. /*
  1670. ** If the third argument is non-NULL, then this function releases a
  1671. ** reference obtained by an earlier call to unixFetch(). The second
  1672. ** argument passed to this function must be the same as the corresponding
  1673. ** argument that was passed to the unixFetch() invocation.
  1674. **
  1675. ** Or, if the third argument is NULL, then this function is being called
  1676. ** to inform the VFS layer that, according to POSIX, any existing mapping
  1677. ** may now be invalid and should be unmapped.
  1678. */
  1679. static int rttUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  1680. rttFile *pFd = (rttFile *)fd; /* The underlying database file */
  1681. UNUSED_PARAMETER(iOff);
  1682. return SQLITE_OK;
  1683. }
  1684. /*
  1685. ** Here ends the implementation of all sqlite3_file methods.
  1686. **
  1687. ********************** End sqlite3_file Methods *******************************
  1688. ******************************************************************************/
  1689. /*
  1690. ** This division contains definitions of sqlite3_io_methods objects that
  1691. ** implement various file locking strategies. It also contains definitions
  1692. ** of "finder" functions. A finder-function is used to locate the appropriate
  1693. ** sqlite3_io_methods object for a particular database file. The pAppData
  1694. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  1695. ** the correct finder-function for that VFS.
  1696. **
  1697. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  1698. ** object. The only interesting finder-function is autolockIoFinder, which
  1699. ** looks at the filesystem type and tries to guess the best locking
  1700. ** strategy from that.
  1701. **
  1702. ** For finder-funtion F, two objects are created:
  1703. **
  1704. ** (1) The real finder-function named "FImpt()".
  1705. **
  1706. ** (2) A constant pointer to this function named just "F".
  1707. **
  1708. **
  1709. ** A pointer to the F pointer is used as the pAppData value for VFS
  1710. ** objects. We have to do this instead of letting pAppData point
  1711. ** directly at the finder-function since C90 rules prevent a void*
  1712. ** from be cast into a function pointer.
  1713. **
  1714. **
  1715. ** Each instance of this macro generates two objects:
  1716. **
  1717. ** * A constant sqlite3_io_methods object call METHOD that has locking
  1718. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  1719. **
  1720. ** * An I/O method finder function called FINDER that returns a pointer
  1721. ** to the METHOD object in the previous bullet.
  1722. */
  1723. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  1724. static const sqlite3_io_methods METHOD = { \
  1725. VERSION, /* iVersion */ \
  1726. CLOSE, /* xClose */ \
  1727. rttRead, /* xRead */ \
  1728. rttWrite, /* xWrite */ \
  1729. rttTruncate, /* xTruncate */ \
  1730. rttSync, /* xSync */ \
  1731. rttFileSize, /* xFileSize */ \
  1732. LOCK, /* xLock */ \
  1733. UNLOCK, /* xUnlock */ \
  1734. CKLOCK, /* xCheckReservedLock */ \
  1735. rttFileControl, /* xFileControl */ \
  1736. rttSectorSize, /* xSectorSize */ \
  1737. rttDeviceCharacteristics, /* xDeviceCapabilities */ \
  1738. rttShmMap, /* xShmMap */ \
  1739. rttShmLock, /* xShmLock */ \
  1740. rttShmBarrier, /* xShmBarrier */ \
  1741. rttShmUnmap, /* xShmUnmap */ \
  1742. rttFetch, /* xFetch */ \
  1743. rttUnfetch, /* xUnfetch */ \
  1744. }; \
  1745. static const sqlite3_io_methods *FINDER##Impl(const char *z, rttFile *p){ \
  1746. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  1747. return &METHOD; \
  1748. } \
  1749. static const sqlite3_io_methods *(*const FINDER)(const char*,rttFile *p) \
  1750. = FINDER##Impl;
  1751. /*
  1752. ** Here are all of the sqlite3_io_methods objects for each of the
  1753. ** locking strategies. Functions that return pointers to these methods
  1754. ** are also created.
  1755. */
  1756. IOMETHODS(
  1757. nolockIoFinder, /* Finder function name */
  1758. nolockIoMethods, /* sqlite3_io_methods object name */
  1759. 1, /* shared memory is disabled */
  1760. nolockClose, /* xClose method */
  1761. nolockLock, /* xLock method */
  1762. nolockUnlock, /* xUnlock method */
  1763. nolockCheckReservedLock /* xCheckReservedLock method */
  1764. )
  1765. IOMETHODS(
  1766. dotlockIoFinder, /* Finder function name */
  1767. dotlockIoMethods, /* sqlite3_io_methods object name */
  1768. 1, /* shared memory is disabled */
  1769. dotlockClose, /* xClose method */
  1770. dotlockLock, /* xLock method */
  1771. dotlockUnlock, /* xUnlock method */
  1772. dotlockCheckReservedLock /* xCheckReservedLock method */
  1773. )
  1774. #if SQLITE_ENABLE_LOCKING_STYLE
  1775. IOMETHODS(
  1776. flockIoFinder, /* Finder function name */
  1777. flockIoMethods, /* sqlite3_io_methods object name */
  1778. 1, /* shared memory is disabled */
  1779. flockClose, /* xClose method */
  1780. flockLock, /* xLock method */
  1781. flockUnlock, /* xUnlock method */
  1782. flockCheckReservedLock /* xCheckReservedLock method */
  1783. )
  1784. #endif
  1785. /*
  1786. ** An abstract type for a pointer to a IO method finder function:
  1787. */
  1788. typedef const sqlite3_io_methods *(*finder_type)(const char*,rttFile*);
  1789. /****************************************************************************
  1790. **************************** sqlite3_vfs methods ****************************
  1791. **
  1792. ** This division contains the implementation of methods on the
  1793. ** sqlite3_vfs object.
  1794. */
  1795. /*
  1796. ** Initialize the contents of the rttFile structure pointed to by pId.
  1797. */
  1798. static int fillInRttFile(
  1799. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  1800. int h, /* Open file descriptor of file being opened */
  1801. sqlite3_file *pId, /* Write to the rttFile structure here */
  1802. const char *zFilename, /* Name of the file being opened */
  1803. int ctrlFlags /* Zero or more UNIXFILE_* values */
  1804. ){
  1805. const sqlite3_io_methods *pLockingStyle;
  1806. rttFile *pNew = (rttFile *)pId;
  1807. int rc = SQLITE_OK;
  1808. assert( pNew->pInode==NULL );
  1809. /* Usually the path zFilename should not be a relative pathname. The
  1810. ** exception is when opening the proxy "conch" file in builds that
  1811. ** include the special Apple locking styles.
  1812. */
  1813. assert( zFilename==0 || zFilename[0]=='/' );
  1814. /* No locking occurs in temporary files */
  1815. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  1816. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  1817. pNew->h = h;
  1818. pNew->pVfs = pVfs;
  1819. pNew->zPath = zFilename;
  1820. pNew->ctrlFlags = (u8)ctrlFlags;
  1821. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  1822. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  1823. pNew->ctrlFlags |= UNIXFILE_PSOW;
  1824. }
  1825. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  1826. pNew->ctrlFlags |= UNIXFILE_EXCL;
  1827. }
  1828. if( ctrlFlags & UNIXFILE_NOLOCK ){
  1829. pLockingStyle = &nolockIoMethods;
  1830. }else{
  1831. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  1832. #if SQLITE_ENABLE_LOCKING_STYLE
  1833. /* Cache zFilename in the locking context (AFP and dotlock override) for
  1834. ** proxyLock activation is possible (remote proxy is based on db name)
  1835. ** zFilename remains valid until file is closed, to support */
  1836. pNew->lockingContext = (void*)zFilename;
  1837. #endif
  1838. }
  1839. if( pLockingStyle == &dotlockIoMethods ){
  1840. /* Dotfile locking uses the file path so it needs to be included in
  1841. ** the dotlockLockingContext
  1842. */
  1843. char *zLockFile;
  1844. int nFilename;
  1845. assert( zFilename!=0 );
  1846. nFilename = (int)strlen(zFilename) + 6;
  1847. zLockFile = (char *)sqlite3_malloc(nFilename);
  1848. if( zLockFile==0 ){
  1849. rc = SQLITE_NOMEM;
  1850. }else{
  1851. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  1852. }
  1853. pNew->lockingContext = zLockFile;
  1854. }
  1855. pNew->lastErrno = 0;
  1856. if( rc!=SQLITE_OK ){
  1857. if( h>=0 ) robust_close(pNew, h, __LINE__);
  1858. }else{
  1859. pNew->pMethod = pLockingStyle;
  1860. OpenCounter(+1);
  1861. verifyDbFile(pNew);
  1862. }
  1863. return rc;
  1864. }
  1865. /*
  1866. ** Return the name of a directory in which to put temporary files.
  1867. ** If no suitable temporary file directory can be found, return NULL.
  1868. */
  1869. static const char *rttTempFileDir(void){
  1870. static const char *azDirs[] = {
  1871. 0,
  1872. "/sql",
  1873. "/sql/tmp"
  1874. "/tmp",
  1875. 0 /* List terminator */
  1876. };
  1877. unsigned int i;
  1878. struct stat buf;
  1879. const char *zDir = 0;
  1880. azDirs[0] = sqlite3_temp_directory;
  1881. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  1882. if( zDir==0 ) continue;
  1883. if( osStat(zDir, &buf) ) continue;
  1884. if( !S_ISDIR(buf.st_mode) ) continue;
  1885. break;
  1886. }
  1887. return zDir;
  1888. }
  1889. /*
  1890. ** Create a temporary file name in zBuf. zBuf must be allocated
  1891. ** by the calling process and must be big enough to hold at least
  1892. ** pVfs->mxPathname bytes.
  1893. */
  1894. static int rttGetTempname(int nBuf, char *zBuf){
  1895. static const unsigned char zChars[] =
  1896. "abcdefghijklmnopqrstuvwxyz"
  1897. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1898. "0123456789";
  1899. unsigned int i, j;
  1900. const char *zDir;
  1901. /* It's odd to simulate an io-error here, but really this is just
  1902. ** using the io-error infrastructure to test that SQLite handles this
  1903. ** function failing.
  1904. */
  1905. SimulateIOError( return SQLITE_IOERR );
  1906. zDir = rttTempFileDir();
  1907. if( zDir==0 ) zDir = ".";
  1908. /* Check that the output buffer is large enough for the temporary file
  1909. ** name. If it is not, return SQLITE_ERROR.
  1910. */
  1911. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  1912. return SQLITE_ERROR;
  1913. }
  1914. do{
  1915. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  1916. j = (int)strlen(zBuf);
  1917. sqlite3_randomness(15, &zBuf[j]);
  1918. for(i=0; i<15; i++, j++){
  1919. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  1920. }
  1921. zBuf[j] = 0;
  1922. zBuf[j+1] = 0;
  1923. }while( osAccess(zBuf,0)==0 );
  1924. return SQLITE_OK;
  1925. }
  1926. /*
  1927. ** Open the file zPath.
  1928. **
  1929. ** Previously, the SQLite OS layer used three functions in place of this
  1930. ** one:
  1931. **
  1932. ** sqlite3OsOpenReadWrite();
  1933. ** sqlite3OsOpenReadOnly();
  1934. ** sqlite3OsOpenExclusive();
  1935. **
  1936. ** These calls correspond to the following combinations of flags:
  1937. **
  1938. ** ReadWrite() -> (READWRITE | CREATE)
  1939. ** ReadOnly() -> (READONLY)
  1940. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  1941. **
  1942. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  1943. ** true, the file was configured to be automatically deleted when the
  1944. ** file handle closed. To achieve the same effect using this new
  1945. ** interface, add the DELETEONCLOSE flag to those specified above for
  1946. ** OpenExclusive().
  1947. */
  1948. static int rttOpen(
  1949. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  1950. const char *zPath, /* Pathname of file to be opened */
  1951. sqlite3_file *pFile, /* The file descriptor to be filled in */
  1952. int flags, /* Input flags to control the opening */
  1953. int *pOutFlags /* Output flags returned to SQLite core */
  1954. ){
  1955. rttFile *p = (rttFile *)pFile;
  1956. int fd = -1; /* File descriptor returned by open() */
  1957. int openFlags = 0; /* Flags to pass to open() */
  1958. int eType = flags&0xFFFFFF00; /* Type of file to open */
  1959. int noLock; /* True to omit locking primitives */
  1960. int rc = SQLITE_OK; /* Function Return Code */
  1961. int ctrlFlags = 0; /* UNIXFILE_* flags */
  1962. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  1963. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  1964. int isCreate = (flags & SQLITE_OPEN_CREATE);
  1965. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  1966. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  1967. #if SQLITE_ENABLE_LOCKING_STYLE
  1968. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  1969. #endif
  1970. /* If creating a master or main-file journal, this function will open
  1971. ** a file-descriptor on the directory too. The first time unixSync()
  1972. ** is called the directory file descriptor will be fsync()ed and close()d.
  1973. */
  1974. int syncDir = (isCreate && (
  1975. eType==SQLITE_OPEN_MASTER_JOURNAL
  1976. || eType==SQLITE_OPEN_MAIN_JOURNAL
  1977. || eType==SQLITE_OPEN_WAL
  1978. ));
  1979. /* If argument zPath is a NULL pointer, this function is required to open
  1980. ** a temporary file. Use this buffer to store the file name in.
  1981. */
  1982. char zTmpname[MAX_PATHNAME+2];
  1983. const char *zName = zPath;
  1984. /* Check the following statements are true:
  1985. **
  1986. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  1987. ** (b) if CREATE is set, then READWRITE must also be set, and
  1988. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  1989. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  1990. */
  1991. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  1992. assert(isCreate==0 || isReadWrite);
  1993. assert(isExclusive==0 || isCreate);
  1994. assert(isDelete==0 || isCreate);
  1995. /* The main DB, main journal, WAL file and master journal are never
  1996. ** automatically deleted. Nor are they ever temporary files. */
  1997. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  1998. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  1999. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  2000. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  2001. /* Assert that the upper layer has set one of the "file-type" flags. */
  2002. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  2003. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  2004. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  2005. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  2006. );
  2007. memset(p, 0, sizeof(rttFile));
  2008. if( !zName ){
  2009. /* If zName is NULL, the upper layer is requesting a temp file. */
  2010. assert(isDelete && !syncDir);
  2011. rc = rttGetTempname(MAX_PATHNAME+2, zTmpname);
  2012. if( rc!=SQLITE_OK ){
  2013. return rc;
  2014. }
  2015. zName = zTmpname;
  2016. /* Generated temporary filenames are always double-zero terminated
  2017. ** for use by sqlite3_uri_parameter(). */
  2018. assert( zName[strlen(zName)+1]==0 );
  2019. }
  2020. /* Determine the value of the flags parameter passed to POSIX function
  2021. ** open(). These must be calculated even if open() is not called, as
  2022. ** they may be stored as part of the file handle and used by the
  2023. ** 'conch file' locking functions later on. */
  2024. if( isReadonly ) openFlags |= O_RDONLY;
  2025. if( isReadWrite ) openFlags |= O_RDWR;
  2026. if( isCreate ) openFlags |= O_CREAT;
  2027. if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/);
  2028. openFlags |= (0/*O_LARGEFILE*/|O_BINARY);
  2029. if( fd<0 ){
  2030. mode_t openMode = 0; /* Permissions to create file with */
  2031. fd = robust_open(zName, openFlags, openMode);
  2032. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  2033. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  2034. /* Failed to open the file for read/write access. Try read-only. */
  2035. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  2036. openFlags &= ~(O_RDWR|O_CREAT);
  2037. flags |= SQLITE_OPEN_READONLY;
  2038. openFlags |= O_RDONLY;
  2039. isReadonly = 1;
  2040. fd = robust_open(zName, openFlags, openMode);
  2041. }
  2042. if( fd<0 ){
  2043. rc = rttLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  2044. goto open_finished;
  2045. }
  2046. }
  2047. assert( fd>=0 );
  2048. if( pOutFlags ){
  2049. *pOutFlags = flags;
  2050. }
  2051. if( isDelete ){
  2052. osUnlink(zName);
  2053. }
  2054. #if SQLITE_ENABLE_LOCKING_STYLE
  2055. else{
  2056. p->openFlags = openFlags;
  2057. }
  2058. #endif
  2059. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  2060. /* Set up appropriate ctrlFlags */
  2061. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  2062. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  2063. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  2064. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  2065. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  2066. rc = fillInRttFile(pVfs, fd, pFile, zPath, ctrlFlags);
  2067. open_finished:
  2068. return rc;
  2069. }
  2070. /*
  2071. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  2072. ** the directory after deleting the file.
  2073. */
  2074. static int rttDelete(
  2075. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  2076. const char *zPath, /* Name of file to be deleted */
  2077. int dirSync /* If true, fsync() directory after deleting file */
  2078. ){
  2079. int rc = SQLITE_OK;
  2080. UNUSED_PARAMETER(NotUsed);
  2081. SimulateIOError(return SQLITE_IOERR_DELETE);
  2082. if( osUnlink(zPath)==(-1) ){
  2083. if( errno==ENOENT ){
  2084. rc = SQLITE_IOERR_DELETE_NOENT;
  2085. }else{
  2086. rc = rttLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  2087. }
  2088. return rc;
  2089. }
  2090. #ifndef SQLITE_DISABLE_DIRSYNC
  2091. if( (dirSync & 1)!=0 ){
  2092. int fd;
  2093. rc = osOpenDirectory(zPath, &fd);
  2094. if( rc==SQLITE_OK ){
  2095. robust_close(0, fd, __LINE__);
  2096. }else if( rc==SQLITE_CANTOPEN ){
  2097. rc = SQLITE_OK;
  2098. }
  2099. }
  2100. #endif
  2101. return rc;
  2102. }
  2103. /*
  2104. ** Test the existence of or access permissions of file zPath. The
  2105. ** test performed depends on the value of flags:
  2106. **
  2107. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  2108. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  2109. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  2110. **
  2111. ** Otherwise return 0.
  2112. */
  2113. static int rttAccess(
  2114. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  2115. const char *zPath, /* Path of the file to examine */
  2116. int flags, /* What do we want to learn about the zPath file? */
  2117. int *pResOut /* Write result boolean here */
  2118. ){
  2119. int amode = 0;
  2120. UNUSED_PARAMETER(NotUsed);
  2121. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  2122. switch( flags ){
  2123. case SQLITE_ACCESS_EXISTS:
  2124. amode = F_OK;
  2125. break;
  2126. case SQLITE_ACCESS_READWRITE:
  2127. amode = W_OK|R_OK;
  2128. break;
  2129. case SQLITE_ACCESS_READ:
  2130. amode = R_OK;
  2131. break;
  2132. default:
  2133. assert(!"Invalid flags argument");
  2134. }
  2135. *pResOut = (osAccess(zPath, amode)==0);
  2136. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  2137. struct stat buf;
  2138. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  2139. *pResOut = 0;
  2140. }
  2141. }
  2142. return SQLITE_OK;
  2143. }
  2144. /*
  2145. ** Turn a relative pathname into a full pathname. The relative path
  2146. ** is stored as a nul-terminated string in the buffer pointed to by
  2147. ** zPath.
  2148. **
  2149. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  2150. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  2151. ** this buffer before returning.
  2152. */
  2153. static int rttFullPathname(
  2154. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  2155. const char *zPath, /* Possibly relative input path */
  2156. int nOut, /* Size of output buffer in bytes */
  2157. char *zOut /* Output buffer */
  2158. ){
  2159. /* It's odd to simulate an io-error here, but really this is just
  2160. ** using the io-error infrastructure to test that SQLite handles this
  2161. ** function failing. This function could fail if, for example, the
  2162. ** current working directory has been unlinked.
  2163. */
  2164. SimulateIOError( return SQLITE_ERROR );
  2165. assert( pVfs->mxPathname==MAX_PATHNAME );
  2166. UNUSED_PARAMETER(pVfs);
  2167. zOut[nOut-1] = '\0';
  2168. if( zPath[0]=='/' ){
  2169. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  2170. }else{
  2171. int nCwd;
  2172. if( osGetcwd(zOut, nOut-1)==0 ){
  2173. return rttLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  2174. }
  2175. nCwd = (int)strlen(zOut);
  2176. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  2177. }
  2178. return SQLITE_OK;
  2179. }
  2180. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2181. # error "rtt not support load extension, compile with SQLITE_OMIT_WAL."
  2182. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  2183. #define rttDlOpen 0
  2184. #define rttDlError 0
  2185. #define rttDlSym 0
  2186. #define rttDlClose 0
  2187. #endif
  2188. /*
  2189. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  2190. */
  2191. static int rttRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  2192. UNUSED_PARAMETER(NotUsed);
  2193. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  2194. /* We have to initialize zBuf to prevent valgrind from reporting
  2195. ** errors. The reports issued by valgrind are incorrect - we would
  2196. ** prefer that the randomness be increased by making use of the
  2197. ** uninitialized space in zBuf - but valgrind errors tend to worry
  2198. ** some users. Rather than argue, it seems easier just to initialize
  2199. ** the whole array and silence valgrind, even if that means less randomness
  2200. ** in the random seed.
  2201. **
  2202. ** When testing, initializing zBuf[] to zero is all we do. That means
  2203. ** that we always use the same random number sequence. This makes the
  2204. ** tests repeatable.
  2205. */
  2206. memset(zBuf, 0, nBuf);
  2207. {
  2208. int i;
  2209. char tick8, tick16;
  2210. tick8 = (char)rt_tick_get();
  2211. tick16 = (char)(rt_tick_get() >> 8);
  2212. for (i=0; i<nBuf; i++)
  2213. {
  2214. zBuf[i] = (char)(i ^ tick8 ^ tick16);
  2215. tick8 = zBuf[i];
  2216. tick16 = ~(tick8 ^ tick16);
  2217. }
  2218. }
  2219. return nBuf;
  2220. }
  2221. /*
  2222. ** Sleep for a little while. Return the amount of time slept.
  2223. ** The argument is the number of microseconds we want to sleep.
  2224. ** The return value is the number of microseconds of sleep actually
  2225. ** requested from the underlying operating system, a number which
  2226. ** might be greater than or equal to the argument, but not less
  2227. ** than the argument.
  2228. */
  2229. static int rttSleep(sqlite3_vfs *NotUsed, int microseconds){
  2230. int seconds = (microseconds+999999)/1000000;
  2231. osSleep(seconds * 1000);
  2232. UNUSED_PARAMETER(NotUsed);
  2233. return seconds*1000000;
  2234. }
  2235. /*
  2236. ** The following variable, if set to a non-zero value, is interpreted as
  2237. ** the number of seconds since 1970 and is used to set the result of
  2238. ** sqlite3OsCurrentTime() during testing.
  2239. */
  2240. #ifdef SQLITE_TEST
  2241. int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  2242. #endif
  2243. #ifndef NO_GETTOD
  2244. #define NO_GETTOD 1
  2245. #endif
  2246. /*
  2247. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  2248. ** the current time and date as a Julian Day number times 86_400_000. In
  2249. ** other words, write into *piNow the number of milliseconds since the Julian
  2250. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  2251. ** proleptic Gregorian calendar.
  2252. **
  2253. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  2254. ** cannot be found.
  2255. */
  2256. static int rttCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  2257. static const sqlite3_int64 rttEpoch = 24405875*(sqlite3_int64)8640000;
  2258. int rc = SQLITE_OK;
  2259. #if defined(NO_GETTOD)
  2260. time_t t;
  2261. time(&t);
  2262. *piNow = ((sqlite3_int64)t)*1000 + rttEpoch;
  2263. #else
  2264. struct timeval sNow;
  2265. if( gettimeofday(&sNow, 0)==0 ){
  2266. *piNow = rttEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  2267. }else{
  2268. rc = SQLITE_ERROR;
  2269. }
  2270. #endif
  2271. #ifdef SQLITE_TEST
  2272. if( sqlite3_current_time ){
  2273. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + rttEpoch;
  2274. }
  2275. #endif
  2276. UNUSED_PARAMETER(NotUsed);
  2277. return rc;
  2278. }
  2279. /*
  2280. ** Find the current time (in Universal Coordinated Time). Write the
  2281. ** current time and date as a Julian Day number into *prNow and
  2282. ** return 0. Return 1 if the time and date cannot be found.
  2283. */
  2284. static int rttCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  2285. sqlite3_int64 i = 0;
  2286. int rc;
  2287. UNUSED_PARAMETER(NotUsed);
  2288. rc = rttCurrentTimeInt64(0, &i);
  2289. *prNow = i/86400000.0;
  2290. return rc;
  2291. }
  2292. /*
  2293. ** We added the xGetLastError() method with the intention of providing
  2294. ** better low-level error messages when operating-system problems come up
  2295. ** during SQLite operation. But so far, none of that has been implemented
  2296. ** in the core. So this routine is never called. For now, it is merely
  2297. ** a place-holder.
  2298. */
  2299. static int rttGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  2300. UNUSED_PARAMETER(NotUsed);
  2301. UNUSED_PARAMETER(NotUsed2);
  2302. UNUSED_PARAMETER(NotUsed3);
  2303. return 0;
  2304. }
  2305. /*
  2306. ************************ End of sqlite3_vfs methods ***************************
  2307. ******************************************************************************/
  2308. /*
  2309. ** Initialize the operating system interface.
  2310. **
  2311. ** This routine registers all VFS implementations for unix-like operating
  2312. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  2313. ** should be the only routines in this file that are visible from other
  2314. ** files.
  2315. **
  2316. ** This routine is called once during SQLite initialization and by a
  2317. ** single thread. The memory allocation and mutex subsystems have not
  2318. ** necessarily been initialized when this routine is called, and so they
  2319. ** should not be used.
  2320. */
  2321. /*
  2322. ** The following macro defines an initializer for an sqlite3_vfs object.
  2323. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  2324. ** to the "finder" function. (pAppData is a pointer to a pointer because
  2325. ** silly C90 rules prohibit a void* from being cast to a function pointer
  2326. ** and so we have to go through the intermediate pointer to avoid problems
  2327. ** when compiling with -pedantic-errors on GCC.)
  2328. **
  2329. ** The FINDER parameter to this macro is the name of the pointer to the
  2330. ** finder-function. The finder-function returns a pointer to the
  2331. ** sqlite_io_methods object that implements the desired locking
  2332. ** behaviors. See the division above that contains the IOMETHODS
  2333. ** macro for addition information on finder-functions.
  2334. **
  2335. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  2336. ** object. But the "autolockIoFinder" available on MacOSX does a little
  2337. ** more than that; it looks at the filesystem type that hosts the
  2338. ** database file and tries to choose an locking method appropriate for
  2339. ** that filesystem time.
  2340. */
  2341. #define UNIXVFS(VFSNAME, FINDER) { \
  2342. 3, /* iVersion */ \
  2343. sizeof(rttFile), /* szOsFile */ \
  2344. MAX_PATHNAME, /* mxPathname */ \
  2345. 0, /* pNext */ \
  2346. VFSNAME, /* zName */ \
  2347. (void*)&FINDER, /* pAppData */ \
  2348. rttOpen, /* xOpen */ \
  2349. rttDelete, /* xDelete */ \
  2350. rttAccess, /* xAccess */ \
  2351. rttFullPathname, /* xFullPathname */ \
  2352. rttDlOpen, /* xDlOpen */ \
  2353. rttDlError, /* xDlError */ \
  2354. rttDlSym, /* xDlSym */ \
  2355. rttDlClose, /* xDlClose */ \
  2356. rttRandomness, /* xRandomness */ \
  2357. rttSleep, /* xSleep */ \
  2358. rttCurrentTime, /* xCurrentTime */ \
  2359. rttGetLastError, /* xGetLastError */ \
  2360. rttCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  2361. rttSetSystemCall, /* xSetSystemCall */ \
  2362. rttGetSystemCall, /* xGetSystemCall */ \
  2363. rttNextSystemCall, /* xNextSystemCall */ \
  2364. }
  2365. int sqlite3_os_init(void){
  2366. /*
  2367. ** All default VFSes for unix are contained in the following array.
  2368. **
  2369. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  2370. ** by the SQLite core when the VFS is registered. So the following
  2371. ** array cannot be const.
  2372. */
  2373. static sqlite3_vfs aVfs[] = {
  2374. UNIXVFS("unix-none", nolockIoFinder ),
  2375. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  2376. #if SQLITE_ENABLE_LOCKING_STYLE
  2377. UNIXVFS("unix-flock", flockIoFinder ),
  2378. #endif
  2379. };
  2380. unsigned int i; /* Loop counter */
  2381. /* Double-check that the aSyscall[] array has been constructed
  2382. ** correctly. See ticket [bb3a86e890c8e96ab] */
  2383. assert( ArraySize(aSyscall)==24 );
  2384. /* Register all VFSes defined in the aVfs[] array */
  2385. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  2386. sqlite3_vfs_register(&aVfs[i], i==0);
  2387. }
  2388. return SQLITE_OK;
  2389. }
  2390. /*
  2391. ** Shutdown the operating system interface.
  2392. **
  2393. ** Some operating systems might need to do some cleanup in this routine,
  2394. ** to release dynamically allocated objects. But not on unix.
  2395. ** This routine is a no-op for unix.
  2396. */
  2397. int sqlite3_os_end(void){
  2398. return SQLITE_OK;
  2399. }
  2400. #endif /* SQLITE_OS_RTT */