os_win.c 163 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221
  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_WIN /* This file is used for Windows only */
  17. #ifdef __CYGWIN__
  18. # include <sys/cygwin.h>
  19. # include <errno.h> /* amalgamator: keep */
  20. #endif
  21. /*
  22. ** Include code that is common to all os_*.c files
  23. */
  24. #include "os_common.h"
  25. /*
  26. ** Compiling and using WAL mode requires several APIs that are only
  27. ** available in Windows platforms based on the NT kernel.
  28. */
  29. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  30. # error "WAL mode requires support from the Windows NT kernel, compile\
  31. with SQLITE_OMIT_WAL."
  32. #endif
  33. /*
  34. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  35. ** based on the sub-platform)?
  36. */
  37. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  38. # define SQLITE_WIN32_HAS_ANSI
  39. #endif
  40. /*
  41. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  42. ** based on the sub-platform)?
  43. */
  44. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  45. !defined(SQLITE_WIN32_NO_WIDE)
  46. # define SQLITE_WIN32_HAS_WIDE
  47. #endif
  48. /*
  49. ** Make sure at least one set of Win32 APIs is available.
  50. */
  51. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  52. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  53. must be defined."
  54. #endif
  55. /*
  56. ** Maximum pathname length (in chars) for Win32. This should normally be
  57. ** MAX_PATH.
  58. */
  59. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  60. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  61. #endif
  62. /*
  63. ** Maximum pathname length (in chars) for WinNT. This should normally be
  64. ** 32767.
  65. */
  66. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  67. # define SQLITE_WINNT_MAX_PATH_CHARS (32767)
  68. #endif
  69. /*
  70. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  71. ** characters, so we allocate 3 bytes per character assuming worst-case of
  72. ** 4-bytes-per-character for UTF8.
  73. */
  74. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  75. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  76. #endif
  77. /*
  78. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  79. ** 32767 * sizeof(WCHAR).
  80. */
  81. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  82. # define SQLITE_WINNT_MAX_PATH_BYTES \
  83. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  84. #endif
  85. /*
  86. ** Maximum error message length (in chars) for WinRT.
  87. */
  88. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  89. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  90. #endif
  91. /*
  92. ** Returns non-zero if the character should be treated as a directory
  93. ** separator.
  94. */
  95. #ifndef winIsDirSep
  96. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  97. #endif
  98. /*
  99. ** This macro is used when a local variable is set to a value that is
  100. ** [sometimes] not used by the code (e.g. via conditional compilation).
  101. */
  102. #ifndef UNUSED_VARIABLE_VALUE
  103. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  104. #endif
  105. /*
  106. ** Returns the string that should be used as the directory separator.
  107. */
  108. #ifndef winGetDirDep
  109. # ifdef __CYGWIN__
  110. # define winGetDirDep() "/"
  111. # else
  112. # define winGetDirDep() "\\"
  113. # endif
  114. #endif
  115. /*
  116. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  117. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  118. ** are not present in the header file)?
  119. */
  120. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  121. /*
  122. ** Two of the file mapping APIs are different under WinRT. Figure out which
  123. ** set we need.
  124. */
  125. #if SQLITE_OS_WINRT
  126. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  127. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  128. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  129. #else
  130. #if defined(SQLITE_WIN32_HAS_ANSI)
  131. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  132. DWORD, DWORD, DWORD, LPCSTR);
  133. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  134. #if defined(SQLITE_WIN32_HAS_WIDE)
  135. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  136. DWORD, DWORD, DWORD, LPCWSTR);
  137. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  138. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  139. #endif /* SQLITE_OS_WINRT */
  140. /*
  141. ** This file mapping API is common to both Win32 and WinRT.
  142. */
  143. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  144. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  145. /*
  146. ** Some Microsoft compilers lack this definition.
  147. */
  148. #ifndef INVALID_FILE_ATTRIBUTES
  149. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  150. #endif
  151. #ifndef FILE_FLAG_MASK
  152. # define FILE_FLAG_MASK (0xFF3C0000)
  153. #endif
  154. #ifndef FILE_ATTRIBUTE_MASK
  155. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  156. #endif
  157. #ifndef SQLITE_OMIT_WAL
  158. /* Forward references to structures used for WAL */
  159. typedef struct winShm winShm; /* A connection to shared-memory */
  160. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  161. #endif
  162. /*
  163. ** WinCE lacks native support for file locking so we have to fake it
  164. ** with some code of our own.
  165. */
  166. #if SQLITE_OS_WINCE
  167. typedef struct winceLock {
  168. int nReaders; /* Number of reader locks obtained */
  169. BOOL bPending; /* Indicates a pending lock has been obtained */
  170. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  171. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  172. } winceLock;
  173. #endif
  174. /*
  175. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  176. ** portability layer.
  177. */
  178. typedef struct winFile winFile;
  179. struct winFile {
  180. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  181. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  182. HANDLE h; /* Handle for accessing the file */
  183. u8 locktype; /* Type of lock currently held on this file */
  184. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  185. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  186. DWORD lastErrno; /* The Windows errno from the last I/O error */
  187. #ifndef SQLITE_OMIT_WAL
  188. winShm *pShm; /* Instance of shared memory on this file */
  189. #endif
  190. const char *zPath; /* Full pathname of this file */
  191. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  192. #if SQLITE_OS_WINCE
  193. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  194. HANDLE hMutex; /* Mutex used to control access to shared lock */
  195. HANDLE hShared; /* Shared memory segment used for locking */
  196. winceLock local; /* Locks obtained by this instance of winFile */
  197. winceLock *shared; /* Global shared lock memory for the file */
  198. #endif
  199. #if SQLITE_MAX_MMAP_SIZE>0
  200. int nFetchOut; /* Number of outstanding xFetch references */
  201. HANDLE hMap; /* Handle for accessing memory mapping */
  202. void *pMapRegion; /* Area memory mapped */
  203. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  204. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  205. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  206. #endif
  207. };
  208. /*
  209. ** Allowed values for winFile.ctrlFlags
  210. */
  211. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  212. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  213. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  214. /*
  215. * The size of the buffer used by sqlite3_win32_write_debug().
  216. */
  217. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  218. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  219. #endif
  220. /*
  221. * The value used with sqlite3_win32_set_directory() to specify that
  222. * the data directory should be changed.
  223. */
  224. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  225. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  226. #endif
  227. /*
  228. * The value used with sqlite3_win32_set_directory() to specify that
  229. * the temporary directory should be changed.
  230. */
  231. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  232. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  233. #endif
  234. /*
  235. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  236. * various Win32 API heap functions instead of our own.
  237. */
  238. #ifdef SQLITE_WIN32_MALLOC
  239. /*
  240. * If this is non-zero, an isolated heap will be created by the native Win32
  241. * allocator subsystem; otherwise, the default process heap will be used. This
  242. * setting has no effect when compiling for WinRT. By default, this is enabled
  243. * and an isolated heap will be created to store all allocated data.
  244. *
  245. ******************************************************************************
  246. * WARNING: It is important to note that when this setting is non-zero and the
  247. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  248. * function), all data that was allocated using the isolated heap will
  249. * be freed immediately and any attempt to access any of that freed
  250. * data will almost certainly result in an immediate access violation.
  251. ******************************************************************************
  252. */
  253. #ifndef SQLITE_WIN32_HEAP_CREATE
  254. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  255. #endif
  256. /*
  257. * The initial size of the Win32-specific heap. This value may be zero.
  258. */
  259. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  260. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  261. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  262. #endif
  263. /*
  264. * The maximum size of the Win32-specific heap. This value may be zero.
  265. */
  266. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  267. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  268. #endif
  269. /*
  270. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  271. * zero for the default behavior.
  272. */
  273. #ifndef SQLITE_WIN32_HEAP_FLAGS
  274. # define SQLITE_WIN32_HEAP_FLAGS (0)
  275. #endif
  276. /*
  277. ** The winMemData structure stores information required by the Win32-specific
  278. ** sqlite3_mem_methods implementation.
  279. */
  280. typedef struct winMemData winMemData;
  281. struct winMemData {
  282. #ifndef NDEBUG
  283. u32 magic; /* Magic number to detect structure corruption. */
  284. #endif
  285. HANDLE hHeap; /* The handle to our heap. */
  286. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  287. };
  288. #ifndef NDEBUG
  289. #define WINMEM_MAGIC 0x42b2830b
  290. #endif
  291. static struct winMemData win_mem_data = {
  292. #ifndef NDEBUG
  293. WINMEM_MAGIC,
  294. #endif
  295. NULL, FALSE
  296. };
  297. #ifndef NDEBUG
  298. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  299. #else
  300. #define winMemAssertMagic()
  301. #endif
  302. #define winMemGetHeap() win_mem_data.hHeap
  303. static void *winMemMalloc(int nBytes);
  304. static void winMemFree(void *pPrior);
  305. static void *winMemRealloc(void *pPrior, int nBytes);
  306. static int winMemSize(void *p);
  307. static int winMemRoundup(int n);
  308. static int winMemInit(void *pAppData);
  309. static void winMemShutdown(void *pAppData);
  310. const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  311. #endif /* SQLITE_WIN32_MALLOC */
  312. /*
  313. ** The following variable is (normally) set once and never changes
  314. ** thereafter. It records whether the operating system is Win9x
  315. ** or WinNT.
  316. **
  317. ** 0: Operating system unknown.
  318. ** 1: Operating system is Win9x.
  319. ** 2: Operating system is WinNT.
  320. **
  321. ** In order to facilitate testing on a WinNT system, the test fixture
  322. ** can manually set this value to 1 to emulate Win98 behavior.
  323. */
  324. #ifdef SQLITE_TEST
  325. int sqlite3_os_type = 0;
  326. #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  327. defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
  328. static int sqlite3_os_type = 0;
  329. #endif
  330. #ifndef SYSCALL
  331. # define SYSCALL sqlite3_syscall_ptr
  332. #endif
  333. /*
  334. ** This function is not available on Windows CE or WinRT.
  335. */
  336. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  337. # define osAreFileApisANSI() 1
  338. #endif
  339. /*
  340. ** Many system calls are accessed through pointer-to-functions so that
  341. ** they may be overridden at runtime to facilitate fault injection during
  342. ** testing and sandboxing. The following array holds the names and pointers
  343. ** to all overrideable system calls.
  344. */
  345. static struct win_syscall {
  346. const char *zName; /* Name of the system call */
  347. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  348. sqlite3_syscall_ptr pDefault; /* Default value */
  349. } aSyscall[] = {
  350. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  351. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  352. #else
  353. { "AreFileApisANSI", (SYSCALL)0, 0 },
  354. #endif
  355. #ifndef osAreFileApisANSI
  356. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  357. #endif
  358. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  359. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  360. #else
  361. { "CharLowerW", (SYSCALL)0, 0 },
  362. #endif
  363. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  364. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  365. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  366. #else
  367. { "CharUpperW", (SYSCALL)0, 0 },
  368. #endif
  369. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  370. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  371. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  372. #if defined(SQLITE_WIN32_HAS_ANSI)
  373. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  374. #else
  375. { "CreateFileA", (SYSCALL)0, 0 },
  376. #endif
  377. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  378. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  379. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  380. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  381. #else
  382. { "CreateFileW", (SYSCALL)0, 0 },
  383. #endif
  384. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  385. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  386. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  387. !defined(SQLITE_OMIT_WAL))
  388. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  389. #else
  390. { "CreateFileMappingA", (SYSCALL)0, 0 },
  391. #endif
  392. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  393. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  394. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  395. !defined(SQLITE_OMIT_WAL))
  396. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  397. #else
  398. { "CreateFileMappingW", (SYSCALL)0, 0 },
  399. #endif
  400. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  401. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  402. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  403. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  404. #else
  405. { "CreateMutexW", (SYSCALL)0, 0 },
  406. #endif
  407. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  408. LPCWSTR))aSyscall[8].pCurrent)
  409. #if defined(SQLITE_WIN32_HAS_ANSI)
  410. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  411. #else
  412. { "DeleteFileA", (SYSCALL)0, 0 },
  413. #endif
  414. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  415. #if defined(SQLITE_WIN32_HAS_WIDE)
  416. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  417. #else
  418. { "DeleteFileW", (SYSCALL)0, 0 },
  419. #endif
  420. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  421. #if SQLITE_OS_WINCE
  422. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  423. #else
  424. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  425. #endif
  426. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  427. LPFILETIME))aSyscall[11].pCurrent)
  428. #if SQLITE_OS_WINCE
  429. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  430. #else
  431. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  432. #endif
  433. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  434. LPSYSTEMTIME))aSyscall[12].pCurrent)
  435. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  436. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  437. #if defined(SQLITE_WIN32_HAS_ANSI)
  438. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  439. #else
  440. { "FormatMessageA", (SYSCALL)0, 0 },
  441. #endif
  442. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  443. DWORD,va_list*))aSyscall[14].pCurrent)
  444. #if defined(SQLITE_WIN32_HAS_WIDE)
  445. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  446. #else
  447. { "FormatMessageW", (SYSCALL)0, 0 },
  448. #endif
  449. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  450. DWORD,va_list*))aSyscall[15].pCurrent)
  451. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  452. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  453. #else
  454. { "FreeLibrary", (SYSCALL)0, 0 },
  455. #endif
  456. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  457. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  458. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  459. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  460. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  461. #else
  462. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  463. #endif
  464. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  465. LPDWORD))aSyscall[18].pCurrent)
  466. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  467. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  468. #else
  469. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  470. #endif
  471. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  472. LPDWORD))aSyscall[19].pCurrent)
  473. #if defined(SQLITE_WIN32_HAS_ANSI)
  474. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  475. #else
  476. { "GetFileAttributesA", (SYSCALL)0, 0 },
  477. #endif
  478. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  479. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  480. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  481. #else
  482. { "GetFileAttributesW", (SYSCALL)0, 0 },
  483. #endif
  484. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  485. #if defined(SQLITE_WIN32_HAS_WIDE)
  486. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  487. #else
  488. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  489. #endif
  490. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  491. LPVOID))aSyscall[22].pCurrent)
  492. #if !SQLITE_OS_WINRT
  493. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  494. #else
  495. { "GetFileSize", (SYSCALL)0, 0 },
  496. #endif
  497. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  498. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  499. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  500. #else
  501. { "GetFullPathNameA", (SYSCALL)0, 0 },
  502. #endif
  503. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  504. LPSTR*))aSyscall[24].pCurrent)
  505. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  506. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  507. #else
  508. { "GetFullPathNameW", (SYSCALL)0, 0 },
  509. #endif
  510. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  511. LPWSTR*))aSyscall[25].pCurrent)
  512. { "GetLastError", (SYSCALL)GetLastError, 0 },
  513. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  514. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  515. #if SQLITE_OS_WINCE
  516. /* The GetProcAddressA() routine is only available on Windows CE. */
  517. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  518. #else
  519. /* All other Windows platforms expect GetProcAddress() to take
  520. ** an ANSI string regardless of the _UNICODE setting */
  521. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  522. #endif
  523. #else
  524. { "GetProcAddressA", (SYSCALL)0, 0 },
  525. #endif
  526. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  527. LPCSTR))aSyscall[27].pCurrent)
  528. #if !SQLITE_OS_WINRT
  529. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  530. #else
  531. { "GetSystemInfo", (SYSCALL)0, 0 },
  532. #endif
  533. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  534. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  535. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  536. #if !SQLITE_OS_WINCE
  537. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  538. #else
  539. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  540. #endif
  541. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  542. LPFILETIME))aSyscall[30].pCurrent)
  543. #if defined(SQLITE_WIN32_HAS_ANSI)
  544. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  545. #else
  546. { "GetTempPathA", (SYSCALL)0, 0 },
  547. #endif
  548. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  549. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  550. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  551. #else
  552. { "GetTempPathW", (SYSCALL)0, 0 },
  553. #endif
  554. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  555. #if !SQLITE_OS_WINRT
  556. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  557. #else
  558. { "GetTickCount", (SYSCALL)0, 0 },
  559. #endif
  560. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  561. #if defined(SQLITE_WIN32_HAS_ANSI)
  562. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  563. #else
  564. { "GetVersionExA", (SYSCALL)0, 0 },
  565. #endif
  566. #define osGetVersionExA ((BOOL(WINAPI*)( \
  567. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  568. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  569. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  570. #else
  571. { "GetVersionExW", (SYSCALL)0, 0 },
  572. #endif
  573. #define osGetVersionExW ((BOOL(WINAPI*)( \
  574. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  575. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  576. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  577. SIZE_T))aSyscall[36].pCurrent)
  578. #if !SQLITE_OS_WINRT
  579. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  580. #else
  581. { "HeapCreate", (SYSCALL)0, 0 },
  582. #endif
  583. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  584. SIZE_T))aSyscall[37].pCurrent)
  585. #if !SQLITE_OS_WINRT
  586. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  587. #else
  588. { "HeapDestroy", (SYSCALL)0, 0 },
  589. #endif
  590. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  591. { "HeapFree", (SYSCALL)HeapFree, 0 },
  592. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  593. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  594. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  595. SIZE_T))aSyscall[40].pCurrent)
  596. { "HeapSize", (SYSCALL)HeapSize, 0 },
  597. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  598. LPCVOID))aSyscall[41].pCurrent)
  599. #if !SQLITE_OS_WINRT
  600. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  601. #else
  602. { "HeapValidate", (SYSCALL)0, 0 },
  603. #endif
  604. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  605. LPCVOID))aSyscall[42].pCurrent)
  606. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  607. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  608. #else
  609. { "LoadLibraryA", (SYSCALL)0, 0 },
  610. #endif
  611. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent)
  612. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  613. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  614. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  615. #else
  616. { "LoadLibraryW", (SYSCALL)0, 0 },
  617. #endif
  618. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent)
  619. #if !SQLITE_OS_WINRT
  620. { "LocalFree", (SYSCALL)LocalFree, 0 },
  621. #else
  622. { "LocalFree", (SYSCALL)0, 0 },
  623. #endif
  624. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent)
  625. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  626. { "LockFile", (SYSCALL)LockFile, 0 },
  627. #else
  628. { "LockFile", (SYSCALL)0, 0 },
  629. #endif
  630. #ifndef osLockFile
  631. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  632. DWORD))aSyscall[46].pCurrent)
  633. #endif
  634. #if !SQLITE_OS_WINCE
  635. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  636. #else
  637. { "LockFileEx", (SYSCALL)0, 0 },
  638. #endif
  639. #ifndef osLockFileEx
  640. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  641. LPOVERLAPPED))aSyscall[47].pCurrent)
  642. #endif
  643. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  644. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  645. #else
  646. { "MapViewOfFile", (SYSCALL)0, 0 },
  647. #endif
  648. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  649. SIZE_T))aSyscall[48].pCurrent)
  650. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  651. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  652. int))aSyscall[49].pCurrent)
  653. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  654. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  655. LARGE_INTEGER*))aSyscall[50].pCurrent)
  656. { "ReadFile", (SYSCALL)ReadFile, 0 },
  657. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  658. LPOVERLAPPED))aSyscall[51].pCurrent)
  659. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  660. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent)
  661. #if !SQLITE_OS_WINRT
  662. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  663. #else
  664. { "SetFilePointer", (SYSCALL)0, 0 },
  665. #endif
  666. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  667. DWORD))aSyscall[53].pCurrent)
  668. #if !SQLITE_OS_WINRT
  669. { "Sleep", (SYSCALL)Sleep, 0 },
  670. #else
  671. { "Sleep", (SYSCALL)0, 0 },
  672. #endif
  673. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent)
  674. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  675. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  676. LPFILETIME))aSyscall[55].pCurrent)
  677. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  678. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  679. #else
  680. { "UnlockFile", (SYSCALL)0, 0 },
  681. #endif
  682. #ifndef osUnlockFile
  683. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  684. DWORD))aSyscall[56].pCurrent)
  685. #endif
  686. #if !SQLITE_OS_WINCE
  687. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  688. #else
  689. { "UnlockFileEx", (SYSCALL)0, 0 },
  690. #endif
  691. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  692. LPOVERLAPPED))aSyscall[57].pCurrent)
  693. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  694. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  695. #else
  696. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  697. #endif
  698. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent)
  699. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  700. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  701. LPCSTR,LPBOOL))aSyscall[59].pCurrent)
  702. { "WriteFile", (SYSCALL)WriteFile, 0 },
  703. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  704. LPOVERLAPPED))aSyscall[60].pCurrent)
  705. #if SQLITE_OS_WINRT
  706. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  707. #else
  708. { "CreateEventExW", (SYSCALL)0, 0 },
  709. #endif
  710. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  711. DWORD,DWORD))aSyscall[61].pCurrent)
  712. #if !SQLITE_OS_WINRT
  713. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  714. #else
  715. { "WaitForSingleObject", (SYSCALL)0, 0 },
  716. #endif
  717. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  718. DWORD))aSyscall[62].pCurrent)
  719. #if SQLITE_OS_WINRT
  720. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  721. #else
  722. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  723. #endif
  724. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  725. BOOL))aSyscall[63].pCurrent)
  726. #if SQLITE_OS_WINRT
  727. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  728. #else
  729. { "SetFilePointerEx", (SYSCALL)0, 0 },
  730. #endif
  731. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  732. PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent)
  733. #if SQLITE_OS_WINRT
  734. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  735. #else
  736. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  737. #endif
  738. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  739. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent)
  740. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  741. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  742. #else
  743. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  744. #endif
  745. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  746. SIZE_T))aSyscall[66].pCurrent)
  747. #if SQLITE_OS_WINRT
  748. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  749. #else
  750. { "CreateFile2", (SYSCALL)0, 0 },
  751. #endif
  752. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  753. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent)
  754. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  755. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  756. #else
  757. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  758. #endif
  759. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  760. DWORD))aSyscall[68].pCurrent)
  761. #if SQLITE_OS_WINRT
  762. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  763. #else
  764. { "GetTickCount64", (SYSCALL)0, 0 },
  765. #endif
  766. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent)
  767. #if SQLITE_OS_WINRT
  768. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  769. #else
  770. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  771. #endif
  772. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  773. LPSYSTEM_INFO))aSyscall[70].pCurrent)
  774. #if defined(SQLITE_WIN32_HAS_ANSI)
  775. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  776. #else
  777. { "OutputDebugStringA", (SYSCALL)0, 0 },
  778. #endif
  779. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent)
  780. #if defined(SQLITE_WIN32_HAS_WIDE)
  781. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  782. #else
  783. { "OutputDebugStringW", (SYSCALL)0, 0 },
  784. #endif
  785. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent)
  786. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  787. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent)
  788. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  789. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  790. #else
  791. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  792. #endif
  793. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  794. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent)
  795. }; /* End of the overrideable system calls */
  796. /*
  797. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  798. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  799. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  800. ** system call named zName.
  801. */
  802. static int winSetSystemCall(
  803. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  804. const char *zName, /* Name of system call to override */
  805. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  806. ){
  807. unsigned int i;
  808. int rc = SQLITE_NOTFOUND;
  809. UNUSED_PARAMETER(pNotUsed);
  810. if( zName==0 ){
  811. /* If no zName is given, restore all system calls to their default
  812. ** settings and return NULL
  813. */
  814. rc = SQLITE_OK;
  815. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  816. if( aSyscall[i].pDefault ){
  817. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  818. }
  819. }
  820. }else{
  821. /* If zName is specified, operate on only the one system call
  822. ** specified.
  823. */
  824. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  825. if( strcmp(zName, aSyscall[i].zName)==0 ){
  826. if( aSyscall[i].pDefault==0 ){
  827. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  828. }
  829. rc = SQLITE_OK;
  830. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  831. aSyscall[i].pCurrent = pNewFunc;
  832. break;
  833. }
  834. }
  835. }
  836. return rc;
  837. }
  838. /*
  839. ** Return the value of a system call. Return NULL if zName is not a
  840. ** recognized system call name. NULL is also returned if the system call
  841. ** is currently undefined.
  842. */
  843. static sqlite3_syscall_ptr winGetSystemCall(
  844. sqlite3_vfs *pNotUsed,
  845. const char *zName
  846. ){
  847. unsigned int i;
  848. UNUSED_PARAMETER(pNotUsed);
  849. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  850. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  851. }
  852. return 0;
  853. }
  854. /*
  855. ** Return the name of the first system call after zName. If zName==NULL
  856. ** then return the name of the first system call. Return NULL if zName
  857. ** is the last system call or if zName is not the name of a valid
  858. ** system call.
  859. */
  860. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  861. int i = -1;
  862. UNUSED_PARAMETER(p);
  863. if( zName ){
  864. for(i=0; i<ArraySize(aSyscall)-1; i++){
  865. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  866. }
  867. }
  868. for(i++; i<ArraySize(aSyscall); i++){
  869. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  870. }
  871. return 0;
  872. }
  873. /*
  874. ** This function outputs the specified (ANSI) string to the Win32 debugger
  875. ** (if available).
  876. */
  877. void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  878. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  879. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  880. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  881. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  882. #if defined(SQLITE_WIN32_HAS_ANSI)
  883. if( nMin>0 ){
  884. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  885. memcpy(zDbgBuf, zBuf, nMin);
  886. osOutputDebugStringA(zDbgBuf);
  887. }else{
  888. osOutputDebugStringA(zBuf);
  889. }
  890. #elif defined(SQLITE_WIN32_HAS_WIDE)
  891. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  892. if ( osMultiByteToWideChar(
  893. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  894. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  895. return;
  896. }
  897. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  898. #else
  899. if( nMin>0 ){
  900. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  901. memcpy(zDbgBuf, zBuf, nMin);
  902. fprintf(stderr, "%s", zDbgBuf);
  903. }else{
  904. fprintf(stderr, "%s", zBuf);
  905. }
  906. #endif
  907. }
  908. /*
  909. ** The following routine suspends the current thread for at least ms
  910. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  911. */
  912. #if SQLITE_OS_WINRT
  913. static HANDLE sleepObj = NULL;
  914. #endif
  915. void sqlite3_win32_sleep(DWORD milliseconds){
  916. #if SQLITE_OS_WINRT
  917. if ( sleepObj==NULL ){
  918. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  919. SYNCHRONIZE);
  920. }
  921. assert( sleepObj!=NULL );
  922. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  923. #else
  924. osSleep(milliseconds);
  925. #endif
  926. }
  927. /*
  928. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  929. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  930. **
  931. ** Here is an interesting observation: Win95, Win98, and WinME lack
  932. ** the LockFileEx() API. But we can still statically link against that
  933. ** API as long as we don't call it when running Win95/98/ME. A call to
  934. ** this routine is used to determine if the host is Win95/98/ME or
  935. ** WinNT/2K/XP so that we will know whether or not we can safely call
  936. ** the LockFileEx() API.
  937. */
  938. #ifndef NTDDI_WIN8
  939. # define NTDDI_WIN8 0x06020000
  940. #endif
  941. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  942. # define osIsNT() (1)
  943. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  944. # define osIsNT() (0)
  945. #else
  946. static int osIsNT(void){
  947. if( sqlite3_os_type==0 ){
  948. #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
  949. OSVERSIONINFOW sInfo;
  950. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  951. osGetVersionExW(&sInfo);
  952. #else
  953. OSVERSIONINFOA sInfo;
  954. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  955. osGetVersionExA(&sInfo);
  956. #endif
  957. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  958. }
  959. return sqlite3_os_type==2;
  960. }
  961. #endif
  962. #ifdef SQLITE_WIN32_MALLOC
  963. /*
  964. ** Allocate nBytes of memory.
  965. */
  966. static void *winMemMalloc(int nBytes){
  967. HANDLE hHeap;
  968. void *p;
  969. winMemAssertMagic();
  970. hHeap = winMemGetHeap();
  971. assert( hHeap!=0 );
  972. assert( hHeap!=INVALID_HANDLE_VALUE );
  973. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  974. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  975. #endif
  976. assert( nBytes>=0 );
  977. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  978. if( !p ){
  979. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  980. nBytes, osGetLastError(), (void*)hHeap);
  981. }
  982. return p;
  983. }
  984. /*
  985. ** Free memory.
  986. */
  987. static void winMemFree(void *pPrior){
  988. HANDLE hHeap;
  989. winMemAssertMagic();
  990. hHeap = winMemGetHeap();
  991. assert( hHeap!=0 );
  992. assert( hHeap!=INVALID_HANDLE_VALUE );
  993. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  994. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  995. #endif
  996. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  997. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  998. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  999. pPrior, osGetLastError(), (void*)hHeap);
  1000. }
  1001. }
  1002. /*
  1003. ** Change the size of an existing memory allocation
  1004. */
  1005. static void *winMemRealloc(void *pPrior, int nBytes){
  1006. HANDLE hHeap;
  1007. void *p;
  1008. winMemAssertMagic();
  1009. hHeap = winMemGetHeap();
  1010. assert( hHeap!=0 );
  1011. assert( hHeap!=INVALID_HANDLE_VALUE );
  1012. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  1013. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  1014. #endif
  1015. assert( nBytes>=0 );
  1016. if( !pPrior ){
  1017. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  1018. }else{
  1019. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  1020. }
  1021. if( !p ){
  1022. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  1023. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  1024. (void*)hHeap);
  1025. }
  1026. return p;
  1027. }
  1028. /*
  1029. ** Return the size of an outstanding allocation, in bytes.
  1030. */
  1031. static int winMemSize(void *p){
  1032. HANDLE hHeap;
  1033. SIZE_T n;
  1034. winMemAssertMagic();
  1035. hHeap = winMemGetHeap();
  1036. assert( hHeap!=0 );
  1037. assert( hHeap!=INVALID_HANDLE_VALUE );
  1038. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  1039. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  1040. #endif
  1041. if( !p ) return 0;
  1042. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  1043. if( n==(SIZE_T)-1 ){
  1044. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  1045. p, osGetLastError(), (void*)hHeap);
  1046. return 0;
  1047. }
  1048. return (int)n;
  1049. }
  1050. /*
  1051. ** Round up a request size to the next valid allocation size.
  1052. */
  1053. static int winMemRoundup(int n){
  1054. return n;
  1055. }
  1056. /*
  1057. ** Initialize this module.
  1058. */
  1059. static int winMemInit(void *pAppData){
  1060. winMemData *pWinMemData = (winMemData *)pAppData;
  1061. if( !pWinMemData ) return SQLITE_ERROR;
  1062. assert( pWinMemData->magic==WINMEM_MAGIC );
  1063. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  1064. if( !pWinMemData->hHeap ){
  1065. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  1066. SQLITE_WIN32_HEAP_INIT_SIZE,
  1067. SQLITE_WIN32_HEAP_MAX_SIZE);
  1068. if( !pWinMemData->hHeap ){
  1069. sqlite3_log(SQLITE_NOMEM,
  1070. "failed to HeapCreate (%lu), flags=%u, initSize=%u, maxSize=%u",
  1071. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  1072. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  1073. return SQLITE_NOMEM;
  1074. }
  1075. pWinMemData->bOwned = TRUE;
  1076. assert( pWinMemData->bOwned );
  1077. }
  1078. #else
  1079. pWinMemData->hHeap = osGetProcessHeap();
  1080. if( !pWinMemData->hHeap ){
  1081. sqlite3_log(SQLITE_NOMEM,
  1082. "failed to GetProcessHeap (%lu)", osGetLastError());
  1083. return SQLITE_NOMEM;
  1084. }
  1085. pWinMemData->bOwned = FALSE;
  1086. assert( !pWinMemData->bOwned );
  1087. #endif
  1088. assert( pWinMemData->hHeap!=0 );
  1089. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  1090. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  1091. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  1092. #endif
  1093. return SQLITE_OK;
  1094. }
  1095. /*
  1096. ** Deinitialize this module.
  1097. */
  1098. static void winMemShutdown(void *pAppData){
  1099. winMemData *pWinMemData = (winMemData *)pAppData;
  1100. if( !pWinMemData ) return;
  1101. if( pWinMemData->hHeap ){
  1102. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  1103. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  1104. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  1105. #endif
  1106. if( pWinMemData->bOwned ){
  1107. if( !osHeapDestroy(pWinMemData->hHeap) ){
  1108. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  1109. osGetLastError(), (void*)pWinMemData->hHeap);
  1110. }
  1111. pWinMemData->bOwned = FALSE;
  1112. }
  1113. pWinMemData->hHeap = NULL;
  1114. }
  1115. }
  1116. /*
  1117. ** Populate the low-level memory allocation function pointers in
  1118. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  1119. ** arguments specify the block of memory to manage.
  1120. **
  1121. ** This routine is only called by sqlite3_config(), and therefore
  1122. ** is not required to be threadsafe (it is not).
  1123. */
  1124. const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  1125. static const sqlite3_mem_methods winMemMethods = {
  1126. winMemMalloc,
  1127. winMemFree,
  1128. winMemRealloc,
  1129. winMemSize,
  1130. winMemRoundup,
  1131. winMemInit,
  1132. winMemShutdown,
  1133. &win_mem_data
  1134. };
  1135. return &winMemMethods;
  1136. }
  1137. void sqlite3MemSetDefault(void){
  1138. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  1139. }
  1140. #endif /* SQLITE_WIN32_MALLOC */
  1141. /*
  1142. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  1143. **
  1144. ** Space to hold the returned string is obtained from malloc.
  1145. */
  1146. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  1147. int nChar;
  1148. LPWSTR zWideFilename;
  1149. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  1150. if( nChar==0 ){
  1151. return 0;
  1152. }
  1153. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  1154. if( zWideFilename==0 ){
  1155. return 0;
  1156. }
  1157. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  1158. nChar);
  1159. if( nChar==0 ){
  1160. sqlite3_free(zWideFilename);
  1161. zWideFilename = 0;
  1162. }
  1163. return zWideFilename;
  1164. }
  1165. /*
  1166. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  1167. ** obtained from sqlite3_malloc().
  1168. */
  1169. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  1170. int nByte;
  1171. char *zFilename;
  1172. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  1173. if( nByte == 0 ){
  1174. return 0;
  1175. }
  1176. zFilename = sqlite3MallocZero( nByte );
  1177. if( zFilename==0 ){
  1178. return 0;
  1179. }
  1180. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  1181. 0, 0);
  1182. if( nByte == 0 ){
  1183. sqlite3_free(zFilename);
  1184. zFilename = 0;
  1185. }
  1186. return zFilename;
  1187. }
  1188. /*
  1189. ** Convert an ANSI string to Microsoft Unicode, based on the
  1190. ** current codepage settings for file apis.
  1191. **
  1192. ** Space to hold the returned string is obtained
  1193. ** from sqlite3_malloc.
  1194. */
  1195. static LPWSTR winMbcsToUnicode(const char *zFilename){
  1196. int nByte;
  1197. LPWSTR zMbcsFilename;
  1198. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  1199. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  1200. 0)*sizeof(WCHAR);
  1201. if( nByte==0 ){
  1202. return 0;
  1203. }
  1204. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  1205. if( zMbcsFilename==0 ){
  1206. return 0;
  1207. }
  1208. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  1209. nByte);
  1210. if( nByte==0 ){
  1211. sqlite3_free(zMbcsFilename);
  1212. zMbcsFilename = 0;
  1213. }
  1214. return zMbcsFilename;
  1215. }
  1216. /*
  1217. ** Convert Microsoft Unicode to multi-byte character string, based on the
  1218. ** user's ANSI codepage.
  1219. **
  1220. ** Space to hold the returned string is obtained from
  1221. ** sqlite3_malloc().
  1222. */
  1223. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  1224. int nByte;
  1225. char *zFilename;
  1226. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  1227. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  1228. if( nByte == 0 ){
  1229. return 0;
  1230. }
  1231. zFilename = sqlite3MallocZero( nByte );
  1232. if( zFilename==0 ){
  1233. return 0;
  1234. }
  1235. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  1236. nByte, 0, 0);
  1237. if( nByte == 0 ){
  1238. sqlite3_free(zFilename);
  1239. zFilename = 0;
  1240. }
  1241. return zFilename;
  1242. }
  1243. /*
  1244. ** Convert multibyte character string to UTF-8. Space to hold the
  1245. ** returned string is obtained from sqlite3_malloc().
  1246. */
  1247. char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  1248. char *zFilenameUtf8;
  1249. LPWSTR zTmpWide;
  1250. zTmpWide = winMbcsToUnicode(zFilename);
  1251. if( zTmpWide==0 ){
  1252. return 0;
  1253. }
  1254. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  1255. sqlite3_free(zTmpWide);
  1256. return zFilenameUtf8;
  1257. }
  1258. /*
  1259. ** Convert UTF-8 to multibyte character string. Space to hold the
  1260. ** returned string is obtained from sqlite3_malloc().
  1261. */
  1262. char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  1263. char *zFilenameMbcs;
  1264. LPWSTR zTmpWide;
  1265. zTmpWide = winUtf8ToUnicode(zFilename);
  1266. if( zTmpWide==0 ){
  1267. return 0;
  1268. }
  1269. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  1270. sqlite3_free(zTmpWide);
  1271. return zFilenameMbcs;
  1272. }
  1273. /*
  1274. ** This function sets the data directory or the temporary directory based on
  1275. ** the provided arguments. The type argument must be 1 in order to set the
  1276. ** data directory or 2 in order to set the temporary directory. The zValue
  1277. ** argument is the name of the directory to use. The return value will be
  1278. ** SQLITE_OK if successful.
  1279. */
  1280. int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  1281. char **ppDirectory = 0;
  1282. #ifndef SQLITE_OMIT_AUTOINIT
  1283. int rc = sqlite3_initialize();
  1284. if( rc ) return rc;
  1285. #endif
  1286. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  1287. ppDirectory = &sqlite3_data_directory;
  1288. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  1289. ppDirectory = &sqlite3_temp_directory;
  1290. }
  1291. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  1292. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  1293. );
  1294. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  1295. if( ppDirectory ){
  1296. char *zValueUtf8 = 0;
  1297. if( zValue && zValue[0] ){
  1298. zValueUtf8 = winUnicodeToUtf8(zValue);
  1299. if ( zValueUtf8==0 ){
  1300. return SQLITE_NOMEM;
  1301. }
  1302. }
  1303. sqlite3_free(*ppDirectory);
  1304. *ppDirectory = zValueUtf8;
  1305. return SQLITE_OK;
  1306. }
  1307. return SQLITE_ERROR;
  1308. }
  1309. /*
  1310. ** The return value of winGetLastErrorMsg
  1311. ** is zero if the error message fits in the buffer, or non-zero
  1312. ** otherwise (if the message was truncated).
  1313. */
  1314. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  1315. /* FormatMessage returns 0 on failure. Otherwise it
  1316. ** returns the number of TCHARs written to the output
  1317. ** buffer, excluding the terminating null char.
  1318. */
  1319. DWORD dwLen = 0;
  1320. char *zOut = 0;
  1321. if( osIsNT() ){
  1322. #if SQLITE_OS_WINRT
  1323. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  1324. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  1325. FORMAT_MESSAGE_IGNORE_INSERTS,
  1326. NULL,
  1327. lastErrno,
  1328. 0,
  1329. zTempWide,
  1330. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  1331. 0);
  1332. #else
  1333. LPWSTR zTempWide = NULL;
  1334. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1335. FORMAT_MESSAGE_FROM_SYSTEM |
  1336. FORMAT_MESSAGE_IGNORE_INSERTS,
  1337. NULL,
  1338. lastErrno,
  1339. 0,
  1340. (LPWSTR) &zTempWide,
  1341. 0,
  1342. 0);
  1343. #endif
  1344. if( dwLen > 0 ){
  1345. /* allocate a buffer and convert to UTF8 */
  1346. sqlite3BeginBenignMalloc();
  1347. zOut = winUnicodeToUtf8(zTempWide);
  1348. sqlite3EndBenignMalloc();
  1349. #if !SQLITE_OS_WINRT
  1350. /* free the system buffer allocated by FormatMessage */
  1351. osLocalFree(zTempWide);
  1352. #endif
  1353. }
  1354. }
  1355. #ifdef SQLITE_WIN32_HAS_ANSI
  1356. else{
  1357. char *zTemp = NULL;
  1358. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1359. FORMAT_MESSAGE_FROM_SYSTEM |
  1360. FORMAT_MESSAGE_IGNORE_INSERTS,
  1361. NULL,
  1362. lastErrno,
  1363. 0,
  1364. (LPSTR) &zTemp,
  1365. 0,
  1366. 0);
  1367. if( dwLen > 0 ){
  1368. /* allocate a buffer and convert to UTF8 */
  1369. sqlite3BeginBenignMalloc();
  1370. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  1371. sqlite3EndBenignMalloc();
  1372. /* free the system buffer allocated by FormatMessage */
  1373. osLocalFree(zTemp);
  1374. }
  1375. }
  1376. #endif
  1377. if( 0 == dwLen ){
  1378. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  1379. }else{
  1380. /* copy a maximum of nBuf chars to output buffer */
  1381. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  1382. /* free the UTF8 buffer */
  1383. sqlite3_free(zOut);
  1384. }
  1385. return 0;
  1386. }
  1387. /*
  1388. **
  1389. ** This function - winLogErrorAtLine() - is only ever called via the macro
  1390. ** winLogError().
  1391. **
  1392. ** This routine is invoked after an error occurs in an OS function.
  1393. ** It logs a message using sqlite3_log() containing the current value of
  1394. ** error code and, if possible, the human-readable equivalent from
  1395. ** FormatMessage.
  1396. **
  1397. ** The first argument passed to the macro should be the error code that
  1398. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  1399. ** The two subsequent arguments should be the name of the OS function that
  1400. ** failed and the associated file-system path, if any.
  1401. */
  1402. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  1403. static int winLogErrorAtLine(
  1404. int errcode, /* SQLite error code */
  1405. DWORD lastErrno, /* Win32 last error */
  1406. const char *zFunc, /* Name of OS function that failed */
  1407. const char *zPath, /* File path associated with error */
  1408. int iLine /* Source line number where error occurred */
  1409. ){
  1410. char zMsg[500]; /* Human readable error text */
  1411. int i; /* Loop counter */
  1412. zMsg[0] = 0;
  1413. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  1414. assert( errcode!=SQLITE_OK );
  1415. if( zPath==0 ) zPath = "";
  1416. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  1417. zMsg[i] = 0;
  1418. sqlite3_log(errcode,
  1419. "os_win.c:%d: (%lu) %s(%s) - %s",
  1420. iLine, lastErrno, zFunc, zPath, zMsg
  1421. );
  1422. return errcode;
  1423. }
  1424. /*
  1425. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  1426. ** will be retried following a locking error - probably caused by
  1427. ** antivirus software. Also the initial delay before the first retry.
  1428. ** The delay increases linearly with each retry.
  1429. */
  1430. #ifndef SQLITE_WIN32_IOERR_RETRY
  1431. # define SQLITE_WIN32_IOERR_RETRY 10
  1432. #endif
  1433. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  1434. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  1435. #endif
  1436. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  1437. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  1438. /*
  1439. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  1440. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  1441. ** to give up with an error.
  1442. */
  1443. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  1444. DWORD e = osGetLastError();
  1445. if( *pnRetry>=winIoerrRetry ){
  1446. if( pError ){
  1447. *pError = e;
  1448. }
  1449. return 0;
  1450. }
  1451. if( e==ERROR_ACCESS_DENIED ||
  1452. e==ERROR_LOCK_VIOLATION ||
  1453. e==ERROR_SHARING_VIOLATION ){
  1454. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  1455. ++*pnRetry;
  1456. return 1;
  1457. }
  1458. if( pError ){
  1459. *pError = e;
  1460. }
  1461. return 0;
  1462. }
  1463. /*
  1464. ** Log a I/O error retry episode.
  1465. */
  1466. static void winLogIoerr(int nRetry){
  1467. if( nRetry ){
  1468. sqlite3_log(SQLITE_IOERR,
  1469. "delayed %dms for lock/sharing conflict",
  1470. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  1471. );
  1472. }
  1473. }
  1474. #if SQLITE_OS_WINCE
  1475. /*************************************************************************
  1476. ** This section contains code for WinCE only.
  1477. */
  1478. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  1479. /*
  1480. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  1481. ** create a substitute.
  1482. */
  1483. #include <time.h>
  1484. struct tm *__cdecl localtime(const time_t *t)
  1485. {
  1486. static struct tm y;
  1487. FILETIME uTm, lTm;
  1488. SYSTEMTIME pTm;
  1489. sqlite3_int64 t64;
  1490. t64 = *t;
  1491. t64 = (t64 + 11644473600)*10000000;
  1492. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  1493. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  1494. osFileTimeToLocalFileTime(&uTm,&lTm);
  1495. osFileTimeToSystemTime(&lTm,&pTm);
  1496. y.tm_year = pTm.wYear - 1900;
  1497. y.tm_mon = pTm.wMonth - 1;
  1498. y.tm_wday = pTm.wDayOfWeek;
  1499. y.tm_mday = pTm.wDay;
  1500. y.tm_hour = pTm.wHour;
  1501. y.tm_min = pTm.wMinute;
  1502. y.tm_sec = pTm.wSecond;
  1503. return &y;
  1504. }
  1505. #endif
  1506. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  1507. /*
  1508. ** Acquire a lock on the handle h
  1509. */
  1510. static void winceMutexAcquire(HANDLE h){
  1511. DWORD dwErr;
  1512. do {
  1513. dwErr = osWaitForSingleObject(h, INFINITE);
  1514. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  1515. }
  1516. /*
  1517. ** Release a lock acquired by winceMutexAcquire()
  1518. */
  1519. #define winceMutexRelease(h) ReleaseMutex(h)
  1520. /*
  1521. ** Create the mutex and shared memory used for locking in the file
  1522. ** descriptor pFile
  1523. */
  1524. static int winceCreateLock(const char *zFilename, winFile *pFile){
  1525. LPWSTR zTok;
  1526. LPWSTR zName;
  1527. DWORD lastErrno;
  1528. BOOL bLogged = FALSE;
  1529. BOOL bInit = TRUE;
  1530. zName = winUtf8ToUnicode(zFilename);
  1531. if( zName==0 ){
  1532. /* out of memory */
  1533. return SQLITE_IOERR_NOMEM;
  1534. }
  1535. /* Initialize the local lockdata */
  1536. memset(&pFile->local, 0, sizeof(pFile->local));
  1537. /* Replace the backslashes from the filename and lowercase it
  1538. ** to derive a mutex name. */
  1539. zTok = osCharLowerW(zName);
  1540. for (;*zTok;zTok++){
  1541. if (*zTok == '\\') *zTok = '_';
  1542. }
  1543. /* Create/open the named mutex */
  1544. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  1545. if (!pFile->hMutex){
  1546. pFile->lastErrno = osGetLastError();
  1547. sqlite3_free(zName);
  1548. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  1549. "winceCreateLock1", zFilename);
  1550. }
  1551. /* Acquire the mutex before continuing */
  1552. winceMutexAcquire(pFile->hMutex);
  1553. /* Since the names of named mutexes, semaphores, file mappings etc are
  1554. ** case-sensitive, take advantage of that by uppercasing the mutex name
  1555. ** and using that as the shared filemapping name.
  1556. */
  1557. osCharUpperW(zName);
  1558. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  1559. PAGE_READWRITE, 0, sizeof(winceLock),
  1560. zName);
  1561. /* Set a flag that indicates we're the first to create the memory so it
  1562. ** must be zero-initialized */
  1563. lastErrno = osGetLastError();
  1564. if (lastErrno == ERROR_ALREADY_EXISTS){
  1565. bInit = FALSE;
  1566. }
  1567. sqlite3_free(zName);
  1568. /* If we succeeded in making the shared memory handle, map it. */
  1569. if( pFile->hShared ){
  1570. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  1571. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  1572. /* If mapping failed, close the shared memory handle and erase it */
  1573. if( !pFile->shared ){
  1574. pFile->lastErrno = osGetLastError();
  1575. winLogError(SQLITE_IOERR, pFile->lastErrno,
  1576. "winceCreateLock2", zFilename);
  1577. bLogged = TRUE;
  1578. osCloseHandle(pFile->hShared);
  1579. pFile->hShared = NULL;
  1580. }
  1581. }
  1582. /* If shared memory could not be created, then close the mutex and fail */
  1583. if( pFile->hShared==NULL ){
  1584. if( !bLogged ){
  1585. pFile->lastErrno = lastErrno;
  1586. winLogError(SQLITE_IOERR, pFile->lastErrno,
  1587. "winceCreateLock3", zFilename);
  1588. bLogged = TRUE;
  1589. }
  1590. winceMutexRelease(pFile->hMutex);
  1591. osCloseHandle(pFile->hMutex);
  1592. pFile->hMutex = NULL;
  1593. return SQLITE_IOERR;
  1594. }
  1595. /* Initialize the shared memory if we're supposed to */
  1596. if( bInit ){
  1597. memset(pFile->shared, 0, sizeof(winceLock));
  1598. }
  1599. winceMutexRelease(pFile->hMutex);
  1600. return SQLITE_OK;
  1601. }
  1602. /*
  1603. ** Destroy the part of winFile that deals with wince locks
  1604. */
  1605. static void winceDestroyLock(winFile *pFile){
  1606. if (pFile->hMutex){
  1607. /* Acquire the mutex */
  1608. winceMutexAcquire(pFile->hMutex);
  1609. /* The following blocks should probably assert in debug mode, but they
  1610. are to cleanup in case any locks remained open */
  1611. if (pFile->local.nReaders){
  1612. pFile->shared->nReaders --;
  1613. }
  1614. if (pFile->local.bReserved){
  1615. pFile->shared->bReserved = FALSE;
  1616. }
  1617. if (pFile->local.bPending){
  1618. pFile->shared->bPending = FALSE;
  1619. }
  1620. if (pFile->local.bExclusive){
  1621. pFile->shared->bExclusive = FALSE;
  1622. }
  1623. /* De-reference and close our copy of the shared memory handle */
  1624. osUnmapViewOfFile(pFile->shared);
  1625. osCloseHandle(pFile->hShared);
  1626. /* Done with the mutex */
  1627. winceMutexRelease(pFile->hMutex);
  1628. osCloseHandle(pFile->hMutex);
  1629. pFile->hMutex = NULL;
  1630. }
  1631. }
  1632. /*
  1633. ** An implementation of the LockFile() API of Windows for CE
  1634. */
  1635. static BOOL winceLockFile(
  1636. LPHANDLE phFile,
  1637. DWORD dwFileOffsetLow,
  1638. DWORD dwFileOffsetHigh,
  1639. DWORD nNumberOfBytesToLockLow,
  1640. DWORD nNumberOfBytesToLockHigh
  1641. ){
  1642. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  1643. BOOL bReturn = FALSE;
  1644. UNUSED_PARAMETER(dwFileOffsetHigh);
  1645. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  1646. if (!pFile->hMutex) return TRUE;
  1647. winceMutexAcquire(pFile->hMutex);
  1648. /* Wanting an exclusive lock? */
  1649. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  1650. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  1651. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  1652. pFile->shared->bExclusive = TRUE;
  1653. pFile->local.bExclusive = TRUE;
  1654. bReturn = TRUE;
  1655. }
  1656. }
  1657. /* Want a read-only lock? */
  1658. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  1659. nNumberOfBytesToLockLow == 1){
  1660. if (pFile->shared->bExclusive == 0){
  1661. pFile->local.nReaders ++;
  1662. if (pFile->local.nReaders == 1){
  1663. pFile->shared->nReaders ++;
  1664. }
  1665. bReturn = TRUE;
  1666. }
  1667. }
  1668. /* Want a pending lock? */
  1669. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  1670. && nNumberOfBytesToLockLow == 1){
  1671. /* If no pending lock has been acquired, then acquire it */
  1672. if (pFile->shared->bPending == 0) {
  1673. pFile->shared->bPending = TRUE;
  1674. pFile->local.bPending = TRUE;
  1675. bReturn = TRUE;
  1676. }
  1677. }
  1678. /* Want a reserved lock? */
  1679. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  1680. && nNumberOfBytesToLockLow == 1){
  1681. if (pFile->shared->bReserved == 0) {
  1682. pFile->shared->bReserved = TRUE;
  1683. pFile->local.bReserved = TRUE;
  1684. bReturn = TRUE;
  1685. }
  1686. }
  1687. winceMutexRelease(pFile->hMutex);
  1688. return bReturn;
  1689. }
  1690. /*
  1691. ** An implementation of the UnlockFile API of Windows for CE
  1692. */
  1693. static BOOL winceUnlockFile(
  1694. LPHANDLE phFile,
  1695. DWORD dwFileOffsetLow,
  1696. DWORD dwFileOffsetHigh,
  1697. DWORD nNumberOfBytesToUnlockLow,
  1698. DWORD nNumberOfBytesToUnlockHigh
  1699. ){
  1700. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  1701. BOOL bReturn = FALSE;
  1702. UNUSED_PARAMETER(dwFileOffsetHigh);
  1703. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  1704. if (!pFile->hMutex) return TRUE;
  1705. winceMutexAcquire(pFile->hMutex);
  1706. /* Releasing a reader lock or an exclusive lock */
  1707. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  1708. /* Did we have an exclusive lock? */
  1709. if (pFile->local.bExclusive){
  1710. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  1711. pFile->local.bExclusive = FALSE;
  1712. pFile->shared->bExclusive = FALSE;
  1713. bReturn = TRUE;
  1714. }
  1715. /* Did we just have a reader lock? */
  1716. else if (pFile->local.nReaders){
  1717. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  1718. || nNumberOfBytesToUnlockLow == 1);
  1719. pFile->local.nReaders --;
  1720. if (pFile->local.nReaders == 0)
  1721. {
  1722. pFile->shared->nReaders --;
  1723. }
  1724. bReturn = TRUE;
  1725. }
  1726. }
  1727. /* Releasing a pending lock */
  1728. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  1729. && nNumberOfBytesToUnlockLow == 1){
  1730. if (pFile->local.bPending){
  1731. pFile->local.bPending = FALSE;
  1732. pFile->shared->bPending = FALSE;
  1733. bReturn = TRUE;
  1734. }
  1735. }
  1736. /* Releasing a reserved lock */
  1737. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  1738. && nNumberOfBytesToUnlockLow == 1){
  1739. if (pFile->local.bReserved) {
  1740. pFile->local.bReserved = FALSE;
  1741. pFile->shared->bReserved = FALSE;
  1742. bReturn = TRUE;
  1743. }
  1744. }
  1745. winceMutexRelease(pFile->hMutex);
  1746. return bReturn;
  1747. }
  1748. /*
  1749. ** End of the special code for wince
  1750. *****************************************************************************/
  1751. #endif /* SQLITE_OS_WINCE */
  1752. /*
  1753. ** Lock a file region.
  1754. */
  1755. static BOOL winLockFile(
  1756. LPHANDLE phFile,
  1757. DWORD flags,
  1758. DWORD offsetLow,
  1759. DWORD offsetHigh,
  1760. DWORD numBytesLow,
  1761. DWORD numBytesHigh
  1762. ){
  1763. #if SQLITE_OS_WINCE
  1764. /*
  1765. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  1766. ** API LockFile.
  1767. */
  1768. return winceLockFile(phFile, offsetLow, offsetHigh,
  1769. numBytesLow, numBytesHigh);
  1770. #else
  1771. if( osIsNT() ){
  1772. OVERLAPPED ovlp;
  1773. memset(&ovlp, 0, sizeof(OVERLAPPED));
  1774. ovlp.Offset = offsetLow;
  1775. ovlp.OffsetHigh = offsetHigh;
  1776. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  1777. }else{
  1778. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  1779. numBytesHigh);
  1780. }
  1781. #endif
  1782. }
  1783. /*
  1784. ** Unlock a file region.
  1785. */
  1786. static BOOL winUnlockFile(
  1787. LPHANDLE phFile,
  1788. DWORD offsetLow,
  1789. DWORD offsetHigh,
  1790. DWORD numBytesLow,
  1791. DWORD numBytesHigh
  1792. ){
  1793. #if SQLITE_OS_WINCE
  1794. /*
  1795. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  1796. ** API UnlockFile.
  1797. */
  1798. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  1799. numBytesLow, numBytesHigh);
  1800. #else
  1801. if( osIsNT() ){
  1802. OVERLAPPED ovlp;
  1803. memset(&ovlp, 0, sizeof(OVERLAPPED));
  1804. ovlp.Offset = offsetLow;
  1805. ovlp.OffsetHigh = offsetHigh;
  1806. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  1807. }else{
  1808. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  1809. numBytesHigh);
  1810. }
  1811. #endif
  1812. }
  1813. /*****************************************************************************
  1814. ** The next group of routines implement the I/O methods specified
  1815. ** by the sqlite3_io_methods object.
  1816. ******************************************************************************/
  1817. /*
  1818. ** Some Microsoft compilers lack this definition.
  1819. */
  1820. #ifndef INVALID_SET_FILE_POINTER
  1821. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  1822. #endif
  1823. /*
  1824. ** Move the current position of the file handle passed as the first
  1825. ** argument to offset iOffset within the file. If successful, return 0.
  1826. ** Otherwise, set pFile->lastErrno and return non-zero.
  1827. */
  1828. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  1829. #if !SQLITE_OS_WINRT
  1830. LONG upperBits; /* Most sig. 32 bits of new offset */
  1831. LONG lowerBits; /* Least sig. 32 bits of new offset */
  1832. DWORD dwRet; /* Value returned by SetFilePointer() */
  1833. DWORD lastErrno; /* Value returned by GetLastError() */
  1834. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  1835. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  1836. lowerBits = (LONG)(iOffset & 0xffffffff);
  1837. /* API oddity: If successful, SetFilePointer() returns a dword
  1838. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  1839. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  1840. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  1841. ** whether an error has actually occurred, it is also necessary to call
  1842. ** GetLastError().
  1843. */
  1844. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  1845. if( (dwRet==INVALID_SET_FILE_POINTER
  1846. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  1847. pFile->lastErrno = lastErrno;
  1848. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  1849. "winSeekFile", pFile->zPath);
  1850. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  1851. return 1;
  1852. }
  1853. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  1854. return 0;
  1855. #else
  1856. /*
  1857. ** Same as above, except that this implementation works for WinRT.
  1858. */
  1859. LARGE_INTEGER x; /* The new offset */
  1860. BOOL bRet; /* Value returned by SetFilePointerEx() */
  1861. x.QuadPart = iOffset;
  1862. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  1863. if(!bRet){
  1864. pFile->lastErrno = osGetLastError();
  1865. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  1866. "winSeekFile", pFile->zPath);
  1867. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  1868. return 1;
  1869. }
  1870. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  1871. return 0;
  1872. #endif
  1873. }
  1874. #if SQLITE_MAX_MMAP_SIZE>0
  1875. /* Forward references to VFS helper methods used for memory mapped files */
  1876. static int winMapfile(winFile*, sqlite3_int64);
  1877. static int winUnmapfile(winFile*);
  1878. #endif
  1879. /*
  1880. ** Close a file.
  1881. **
  1882. ** It is reported that an attempt to close a handle might sometimes
  1883. ** fail. This is a very unreasonable result, but Windows is notorious
  1884. ** for being unreasonable so I do not doubt that it might happen. If
  1885. ** the close fails, we pause for 100 milliseconds and try again. As
  1886. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  1887. ** giving up and returning an error.
  1888. */
  1889. #define MX_CLOSE_ATTEMPT 3
  1890. static int winClose(sqlite3_file *id){
  1891. int rc, cnt = 0;
  1892. winFile *pFile = (winFile*)id;
  1893. assert( id!=0 );
  1894. #ifndef SQLITE_OMIT_WAL
  1895. assert( pFile->pShm==0 );
  1896. #endif
  1897. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  1898. OSTRACE(("CLOSE file=%p\n", pFile->h));
  1899. #if SQLITE_MAX_MMAP_SIZE>0
  1900. winUnmapfile(pFile);
  1901. #endif
  1902. do{
  1903. rc = osCloseHandle(pFile->h);
  1904. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  1905. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  1906. #if SQLITE_OS_WINCE
  1907. #define WINCE_DELETION_ATTEMPTS 3
  1908. winceDestroyLock(pFile);
  1909. if( pFile->zDeleteOnClose ){
  1910. int cnt = 0;
  1911. while(
  1912. osDeleteFileW(pFile->zDeleteOnClose)==0
  1913. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  1914. && cnt++ < WINCE_DELETION_ATTEMPTS
  1915. ){
  1916. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  1917. }
  1918. sqlite3_free(pFile->zDeleteOnClose);
  1919. }
  1920. #endif
  1921. if( rc ){
  1922. pFile->h = NULL;
  1923. }
  1924. OpenCounter(-1);
  1925. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  1926. return rc ? SQLITE_OK
  1927. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  1928. "winClose", pFile->zPath);
  1929. }
  1930. /*
  1931. ** Read data from a file into a buffer. Return SQLITE_OK if all
  1932. ** bytes were read successfully and SQLITE_IOERR if anything goes
  1933. ** wrong.
  1934. */
  1935. static int winRead(
  1936. sqlite3_file *id, /* File to read from */
  1937. void *pBuf, /* Write content into this buffer */
  1938. int amt, /* Number of bytes to read */
  1939. sqlite3_int64 offset /* Begin reading at this offset */
  1940. ){
  1941. #if !SQLITE_OS_WINCE
  1942. OVERLAPPED overlapped; /* The offset for ReadFile. */
  1943. #endif
  1944. winFile *pFile = (winFile*)id; /* file handle */
  1945. DWORD nRead; /* Number of bytes actually read from file */
  1946. int nRetry = 0; /* Number of retrys */
  1947. assert( id!=0 );
  1948. assert( amt>0 );
  1949. assert( offset>=0 );
  1950. SimulateIOError(return SQLITE_IOERR_READ);
  1951. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  1952. pFile->h, pBuf, amt, offset, pFile->locktype));
  1953. #if SQLITE_MAX_MMAP_SIZE>0
  1954. /* Deal with as much of this read request as possible by transfering
  1955. ** data from the memory mapping using memcpy(). */
  1956. if( offset<pFile->mmapSize ){
  1957. if( offset+amt <= pFile->mmapSize ){
  1958. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  1959. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  1960. return SQLITE_OK;
  1961. }else{
  1962. int nCopy = (int)(pFile->mmapSize - offset);
  1963. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  1964. pBuf = &((u8 *)pBuf)[nCopy];
  1965. amt -= nCopy;
  1966. offset += nCopy;
  1967. }
  1968. }
  1969. #endif
  1970. #if SQLITE_OS_WINCE
  1971. if( winSeekFile(pFile, offset) ){
  1972. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  1973. return SQLITE_FULL;
  1974. }
  1975. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  1976. #else
  1977. memset(&overlapped, 0, sizeof(OVERLAPPED));
  1978. overlapped.Offset = (LONG)(offset & 0xffffffff);
  1979. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  1980. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  1981. osGetLastError()!=ERROR_HANDLE_EOF ){
  1982. #endif
  1983. DWORD lastErrno;
  1984. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  1985. pFile->lastErrno = lastErrno;
  1986. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  1987. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  1988. "winRead", pFile->zPath);
  1989. }
  1990. winLogIoerr(nRetry);
  1991. if( nRead<(DWORD)amt ){
  1992. /* Unread parts of the buffer must be zero-filled */
  1993. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  1994. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  1995. return SQLITE_IOERR_SHORT_READ;
  1996. }
  1997. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  1998. return SQLITE_OK;
  1999. }
  2000. /*
  2001. ** Write data from a buffer into a file. Return SQLITE_OK on success
  2002. ** or some other error code on failure.
  2003. */
  2004. static int winWrite(
  2005. sqlite3_file *id, /* File to write into */
  2006. const void *pBuf, /* The bytes to be written */
  2007. int amt, /* Number of bytes to write */
  2008. sqlite3_int64 offset /* Offset into the file to begin writing at */
  2009. ){
  2010. int rc = 0; /* True if error has occurred, else false */
  2011. winFile *pFile = (winFile*)id; /* File handle */
  2012. int nRetry = 0; /* Number of retries */
  2013. assert( amt>0 );
  2014. assert( pFile );
  2015. SimulateIOError(return SQLITE_IOERR_WRITE);
  2016. SimulateDiskfullError(return SQLITE_FULL);
  2017. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  2018. pFile->h, pBuf, amt, offset, pFile->locktype));
  2019. #if SQLITE_MAX_MMAP_SIZE>0
  2020. /* Deal with as much of this write request as possible by transfering
  2021. ** data from the memory mapping using memcpy(). */
  2022. if( offset<pFile->mmapSize ){
  2023. if( offset+amt <= pFile->mmapSize ){
  2024. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  2025. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  2026. return SQLITE_OK;
  2027. }else{
  2028. int nCopy = (int)(pFile->mmapSize - offset);
  2029. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  2030. pBuf = &((u8 *)pBuf)[nCopy];
  2031. amt -= nCopy;
  2032. offset += nCopy;
  2033. }
  2034. }
  2035. #endif
  2036. #if SQLITE_OS_WINCE
  2037. rc = winSeekFile(pFile, offset);
  2038. if( rc==0 ){
  2039. #else
  2040. {
  2041. #endif
  2042. #if !SQLITE_OS_WINCE
  2043. OVERLAPPED overlapped; /* The offset for WriteFile. */
  2044. #endif
  2045. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  2046. int nRem = amt; /* Number of bytes yet to be written */
  2047. DWORD nWrite; /* Bytes written by each WriteFile() call */
  2048. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  2049. #if !SQLITE_OS_WINCE
  2050. memset(&overlapped, 0, sizeof(OVERLAPPED));
  2051. overlapped.Offset = (LONG)(offset & 0xffffffff);
  2052. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  2053. #endif
  2054. while( nRem>0 ){
  2055. #if SQLITE_OS_WINCE
  2056. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  2057. #else
  2058. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  2059. #endif
  2060. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  2061. break;
  2062. }
  2063. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  2064. if( nWrite==0 || nWrite>(DWORD)nRem ){
  2065. lastErrno = osGetLastError();
  2066. break;
  2067. }
  2068. #if !SQLITE_OS_WINCE
  2069. offset += nWrite;
  2070. overlapped.Offset = (LONG)(offset & 0xffffffff);
  2071. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  2072. #endif
  2073. aRem += nWrite;
  2074. nRem -= nWrite;
  2075. }
  2076. if( nRem>0 ){
  2077. pFile->lastErrno = lastErrno;
  2078. rc = 1;
  2079. }
  2080. }
  2081. if( rc ){
  2082. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  2083. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  2084. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  2085. return winLogError(SQLITE_FULL, pFile->lastErrno,
  2086. "winWrite1", pFile->zPath);
  2087. }
  2088. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  2089. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  2090. "winWrite2", pFile->zPath);
  2091. }else{
  2092. winLogIoerr(nRetry);
  2093. }
  2094. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  2095. return SQLITE_OK;
  2096. }
  2097. /*
  2098. ** Truncate an open file to a specified size
  2099. */
  2100. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  2101. winFile *pFile = (winFile*)id; /* File handle object */
  2102. int rc = SQLITE_OK; /* Return code for this function */
  2103. DWORD lastErrno;
  2104. assert( pFile );
  2105. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  2106. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  2107. pFile->h, nByte, pFile->locktype));
  2108. /* If the user has configured a chunk-size for this file, truncate the
  2109. ** file so that it consists of an integer number of chunks (i.e. the
  2110. ** actual file size after the operation may be larger than the requested
  2111. ** size).
  2112. */
  2113. if( pFile->szChunk>0 ){
  2114. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  2115. }
  2116. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  2117. if( winSeekFile(pFile, nByte) ){
  2118. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  2119. "winTruncate1", pFile->zPath);
  2120. }else if( 0==osSetEndOfFile(pFile->h) &&
  2121. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  2122. pFile->lastErrno = lastErrno;
  2123. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  2124. "winTruncate2", pFile->zPath);
  2125. }
  2126. #if SQLITE_MAX_MMAP_SIZE>0
  2127. /* If the file was truncated to a size smaller than the currently
  2128. ** mapped region, reduce the effective mapping size as well. SQLite will
  2129. ** use read() and write() to access data beyond this point from now on.
  2130. */
  2131. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  2132. pFile->mmapSize = nByte;
  2133. }
  2134. #endif
  2135. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  2136. return rc;
  2137. }
  2138. #ifdef SQLITE_TEST
  2139. /*
  2140. ** Count the number of fullsyncs and normal syncs. This is used to test
  2141. ** that syncs and fullsyncs are occuring at the right times.
  2142. */
  2143. int sqlite3_sync_count = 0;
  2144. int sqlite3_fullsync_count = 0;
  2145. #endif
  2146. /*
  2147. ** Make sure all writes to a particular file are committed to disk.
  2148. */
  2149. static int winSync(sqlite3_file *id, int flags){
  2150. #ifndef SQLITE_NO_SYNC
  2151. /*
  2152. ** Used only when SQLITE_NO_SYNC is not defined.
  2153. */
  2154. BOOL rc;
  2155. #endif
  2156. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  2157. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  2158. /*
  2159. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  2160. ** OSTRACE() macros.
  2161. */
  2162. winFile *pFile = (winFile*)id;
  2163. #else
  2164. UNUSED_PARAMETER(id);
  2165. #endif
  2166. assert( pFile );
  2167. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  2168. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  2169. || (flags&0x0F)==SQLITE_SYNC_FULL
  2170. );
  2171. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  2172. ** line is to test that doing so does not cause any problems.
  2173. */
  2174. SimulateDiskfullError( return SQLITE_FULL );
  2175. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  2176. pFile->h, flags, pFile->locktype));
  2177. #ifndef SQLITE_TEST
  2178. UNUSED_PARAMETER(flags);
  2179. #else
  2180. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  2181. sqlite3_fullsync_count++;
  2182. }
  2183. sqlite3_sync_count++;
  2184. #endif
  2185. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  2186. ** no-op
  2187. */
  2188. #ifdef SQLITE_NO_SYNC
  2189. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  2190. return SQLITE_OK;
  2191. #else
  2192. rc = osFlushFileBuffers(pFile->h);
  2193. SimulateIOError( rc=FALSE );
  2194. if( rc ){
  2195. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  2196. return SQLITE_OK;
  2197. }else{
  2198. pFile->lastErrno = osGetLastError();
  2199. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  2200. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  2201. "winSync", pFile->zPath);
  2202. }
  2203. #endif
  2204. }
  2205. /*
  2206. ** Determine the current size of a file in bytes
  2207. */
  2208. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  2209. winFile *pFile = (winFile*)id;
  2210. int rc = SQLITE_OK;
  2211. assert( id!=0 );
  2212. assert( pSize!=0 );
  2213. SimulateIOError(return SQLITE_IOERR_FSTAT);
  2214. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  2215. #if SQLITE_OS_WINRT
  2216. {
  2217. FILE_STANDARD_INFO info;
  2218. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  2219. &info, sizeof(info)) ){
  2220. *pSize = info.EndOfFile.QuadPart;
  2221. }else{
  2222. pFile->lastErrno = osGetLastError();
  2223. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  2224. "winFileSize", pFile->zPath);
  2225. }
  2226. }
  2227. #else
  2228. {
  2229. DWORD upperBits;
  2230. DWORD lowerBits;
  2231. DWORD lastErrno;
  2232. lowerBits = osGetFileSize(pFile->h, &upperBits);
  2233. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  2234. if( (lowerBits == INVALID_FILE_SIZE)
  2235. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  2236. pFile->lastErrno = lastErrno;
  2237. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  2238. "winFileSize", pFile->zPath);
  2239. }
  2240. }
  2241. #endif
  2242. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  2243. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  2244. return rc;
  2245. }
  2246. /*
  2247. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  2248. */
  2249. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  2250. # define LOCKFILE_FAIL_IMMEDIATELY 1
  2251. #endif
  2252. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  2253. # define LOCKFILE_EXCLUSIVE_LOCK 2
  2254. #endif
  2255. /*
  2256. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  2257. ** When the LockFile function was used, it was always expected to fail
  2258. ** immediately if the lock could not be obtained. Also, it always expected to
  2259. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  2260. ** and reflect those expectations; therefore, they should not be changed.
  2261. */
  2262. #ifndef SQLITE_LOCKFILE_FLAGS
  2263. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  2264. LOCKFILE_EXCLUSIVE_LOCK)
  2265. #endif
  2266. /*
  2267. ** Currently, SQLite never calls the LockFileEx function without wanting the
  2268. ** call to fail immediately if the lock cannot be obtained.
  2269. */
  2270. #ifndef SQLITE_LOCKFILEEX_FLAGS
  2271. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  2272. #endif
  2273. /*
  2274. ** Acquire a reader lock.
  2275. ** Different API routines are called depending on whether or not this
  2276. ** is Win9x or WinNT.
  2277. */
  2278. static int winGetReadLock(winFile *pFile){
  2279. int res;
  2280. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  2281. if( osIsNT() ){
  2282. #if SQLITE_OS_WINCE
  2283. /*
  2284. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  2285. ** API LockFileEx.
  2286. */
  2287. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  2288. #else
  2289. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  2290. SHARED_SIZE, 0);
  2291. #endif
  2292. }
  2293. #ifdef SQLITE_WIN32_HAS_ANSI
  2294. else{
  2295. int lk;
  2296. sqlite3_randomness(sizeof(lk), &lk);
  2297. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  2298. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  2299. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  2300. }
  2301. #endif
  2302. if( res == 0 ){
  2303. pFile->lastErrno = osGetLastError();
  2304. /* No need to log a failure to lock */
  2305. }
  2306. OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  2307. return res;
  2308. }
  2309. /*
  2310. ** Undo a readlock
  2311. */
  2312. static int winUnlockReadLock(winFile *pFile){
  2313. int res;
  2314. DWORD lastErrno;
  2315. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  2316. if( osIsNT() ){
  2317. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  2318. }
  2319. #ifdef SQLITE_WIN32_HAS_ANSI
  2320. else{
  2321. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  2322. }
  2323. #endif
  2324. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  2325. pFile->lastErrno = lastErrno;
  2326. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  2327. "winUnlockReadLock", pFile->zPath);
  2328. }
  2329. OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  2330. return res;
  2331. }
  2332. /*
  2333. ** Lock the file with the lock specified by parameter locktype - one
  2334. ** of the following:
  2335. **
  2336. ** (1) SHARED_LOCK
  2337. ** (2) RESERVED_LOCK
  2338. ** (3) PENDING_LOCK
  2339. ** (4) EXCLUSIVE_LOCK
  2340. **
  2341. ** Sometimes when requesting one lock state, additional lock states
  2342. ** are inserted in between. The locking might fail on one of the later
  2343. ** transitions leaving the lock state different from what it started but
  2344. ** still short of its goal. The following chart shows the allowed
  2345. ** transitions and the inserted intermediate states:
  2346. **
  2347. ** UNLOCKED -> SHARED
  2348. ** SHARED -> RESERVED
  2349. ** SHARED -> (PENDING) -> EXCLUSIVE
  2350. ** RESERVED -> (PENDING) -> EXCLUSIVE
  2351. ** PENDING -> EXCLUSIVE
  2352. **
  2353. ** This routine will only increase a lock. The winUnlock() routine
  2354. ** erases all locks at once and returns us immediately to locking level 0.
  2355. ** It is not possible to lower the locking level one step at a time. You
  2356. ** must go straight to locking level 0.
  2357. */
  2358. static int winLock(sqlite3_file *id, int locktype){
  2359. int rc = SQLITE_OK; /* Return code from subroutines */
  2360. int res = 1; /* Result of a Windows lock call */
  2361. int newLocktype; /* Set pFile->locktype to this value before exiting */
  2362. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  2363. winFile *pFile = (winFile*)id;
  2364. DWORD lastErrno = NO_ERROR;
  2365. assert( id!=0 );
  2366. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  2367. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  2368. /* If there is already a lock of this type or more restrictive on the
  2369. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  2370. ** sqlite3OsEnterMutex() hasn't been called yet.
  2371. */
  2372. if( pFile->locktype>=locktype ){
  2373. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  2374. return SQLITE_OK;
  2375. }
  2376. /* Make sure the locking sequence is correct
  2377. */
  2378. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  2379. assert( locktype!=PENDING_LOCK );
  2380. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  2381. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  2382. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  2383. ** the PENDING_LOCK byte is temporary.
  2384. */
  2385. newLocktype = pFile->locktype;
  2386. if( (pFile->locktype==NO_LOCK)
  2387. || ( (locktype==EXCLUSIVE_LOCK)
  2388. && (pFile->locktype==RESERVED_LOCK))
  2389. ){
  2390. int cnt = 3;
  2391. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  2392. PENDING_BYTE, 0, 1, 0))==0 ){
  2393. /* Try 3 times to get the pending lock. This is needed to work
  2394. ** around problems caused by indexing and/or anti-virus software on
  2395. ** Windows systems.
  2396. ** If you are using this code as a model for alternative VFSes, do not
  2397. ** copy this retry logic. It is a hack intended for Windows only.
  2398. */
  2399. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
  2400. pFile->h, cnt, sqlite3ErrName(res)));
  2401. if( cnt ) sqlite3_win32_sleep(1);
  2402. }
  2403. gotPendingLock = res;
  2404. if( !res ){
  2405. lastErrno = osGetLastError();
  2406. }
  2407. }
  2408. /* Acquire a shared lock
  2409. */
  2410. if( locktype==SHARED_LOCK && res ){
  2411. assert( pFile->locktype==NO_LOCK );
  2412. res = winGetReadLock(pFile);
  2413. if( res ){
  2414. newLocktype = SHARED_LOCK;
  2415. }else{
  2416. lastErrno = osGetLastError();
  2417. }
  2418. }
  2419. /* Acquire a RESERVED lock
  2420. */
  2421. if( locktype==RESERVED_LOCK && res ){
  2422. assert( pFile->locktype==SHARED_LOCK );
  2423. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  2424. if( res ){
  2425. newLocktype = RESERVED_LOCK;
  2426. }else{
  2427. lastErrno = osGetLastError();
  2428. }
  2429. }
  2430. /* Acquire a PENDING lock
  2431. */
  2432. if( locktype==EXCLUSIVE_LOCK && res ){
  2433. newLocktype = PENDING_LOCK;
  2434. gotPendingLock = 0;
  2435. }
  2436. /* Acquire an EXCLUSIVE lock
  2437. */
  2438. if( locktype==EXCLUSIVE_LOCK && res ){
  2439. assert( pFile->locktype>=SHARED_LOCK );
  2440. res = winUnlockReadLock(pFile);
  2441. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  2442. SHARED_SIZE, 0);
  2443. if( res ){
  2444. newLocktype = EXCLUSIVE_LOCK;
  2445. }else{
  2446. lastErrno = osGetLastError();
  2447. winGetReadLock(pFile);
  2448. }
  2449. }
  2450. /* If we are holding a PENDING lock that ought to be released, then
  2451. ** release it now.
  2452. */
  2453. if( gotPendingLock && locktype==SHARED_LOCK ){
  2454. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  2455. }
  2456. /* Update the state of the lock has held in the file descriptor then
  2457. ** return the appropriate result code.
  2458. */
  2459. if( res ){
  2460. rc = SQLITE_OK;
  2461. }else{
  2462. pFile->lastErrno = lastErrno;
  2463. rc = SQLITE_BUSY;
  2464. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  2465. pFile->h, locktype, newLocktype));
  2466. }
  2467. pFile->locktype = (u8)newLocktype;
  2468. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  2469. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  2470. return rc;
  2471. }
  2472. /*
  2473. ** This routine checks if there is a RESERVED lock held on the specified
  2474. ** file by this or any other process. If such a lock is held, return
  2475. ** non-zero, otherwise zero.
  2476. */
  2477. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  2478. int rc;
  2479. winFile *pFile = (winFile*)id;
  2480. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  2481. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  2482. assert( id!=0 );
  2483. if( pFile->locktype>=RESERVED_LOCK ){
  2484. rc = 1;
  2485. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
  2486. }else{
  2487. rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  2488. if( rc ){
  2489. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  2490. }
  2491. rc = !rc;
  2492. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
  2493. }
  2494. *pResOut = rc;
  2495. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  2496. pFile->h, pResOut, *pResOut));
  2497. return SQLITE_OK;
  2498. }
  2499. /*
  2500. ** Lower the locking level on file descriptor id to locktype. locktype
  2501. ** must be either NO_LOCK or SHARED_LOCK.
  2502. **
  2503. ** If the locking level of the file descriptor is already at or below
  2504. ** the requested locking level, this routine is a no-op.
  2505. **
  2506. ** It is not possible for this routine to fail if the second argument
  2507. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  2508. ** might return SQLITE_IOERR;
  2509. */
  2510. static int winUnlock(sqlite3_file *id, int locktype){
  2511. int type;
  2512. winFile *pFile = (winFile*)id;
  2513. int rc = SQLITE_OK;
  2514. assert( pFile!=0 );
  2515. assert( locktype<=SHARED_LOCK );
  2516. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  2517. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  2518. type = pFile->locktype;
  2519. if( type>=EXCLUSIVE_LOCK ){
  2520. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  2521. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  2522. /* This should never happen. We should always be able to
  2523. ** reacquire the read lock */
  2524. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  2525. "winUnlock", pFile->zPath);
  2526. }
  2527. }
  2528. if( type>=RESERVED_LOCK ){
  2529. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  2530. }
  2531. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  2532. winUnlockReadLock(pFile);
  2533. }
  2534. if( type>=PENDING_LOCK ){
  2535. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  2536. }
  2537. pFile->locktype = (u8)locktype;
  2538. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  2539. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  2540. return rc;
  2541. }
  2542. /*
  2543. ** If *pArg is inititially negative then this is a query. Set *pArg to
  2544. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  2545. **
  2546. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  2547. */
  2548. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  2549. if( *pArg<0 ){
  2550. *pArg = (pFile->ctrlFlags & mask)!=0;
  2551. }else if( (*pArg)==0 ){
  2552. pFile->ctrlFlags &= ~mask;
  2553. }else{
  2554. pFile->ctrlFlags |= mask;
  2555. }
  2556. }
  2557. /* Forward references to VFS helper methods used for temporary files */
  2558. static int winGetTempname(sqlite3_vfs *, char **);
  2559. static int winIsDir(const void *);
  2560. static BOOL winIsDriveLetterAndColon(const char *);
  2561. /*
  2562. ** Control and query of the open file handle.
  2563. */
  2564. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  2565. winFile *pFile = (winFile*)id;
  2566. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  2567. switch( op ){
  2568. case SQLITE_FCNTL_LOCKSTATE: {
  2569. *(int*)pArg = pFile->locktype;
  2570. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2571. return SQLITE_OK;
  2572. }
  2573. case SQLITE_LAST_ERRNO: {
  2574. *(int*)pArg = (int)pFile->lastErrno;
  2575. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2576. return SQLITE_OK;
  2577. }
  2578. case SQLITE_FCNTL_CHUNK_SIZE: {
  2579. pFile->szChunk = *(int *)pArg;
  2580. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2581. return SQLITE_OK;
  2582. }
  2583. case SQLITE_FCNTL_SIZE_HINT: {
  2584. if( pFile->szChunk>0 ){
  2585. sqlite3_int64 oldSz;
  2586. int rc = winFileSize(id, &oldSz);
  2587. if( rc==SQLITE_OK ){
  2588. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  2589. if( newSz>oldSz ){
  2590. SimulateIOErrorBenign(1);
  2591. rc = winTruncate(id, newSz);
  2592. SimulateIOErrorBenign(0);
  2593. }
  2594. }
  2595. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  2596. return rc;
  2597. }
  2598. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2599. return SQLITE_OK;
  2600. }
  2601. case SQLITE_FCNTL_PERSIST_WAL: {
  2602. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  2603. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2604. return SQLITE_OK;
  2605. }
  2606. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  2607. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  2608. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2609. return SQLITE_OK;
  2610. }
  2611. case SQLITE_FCNTL_VFSNAME: {
  2612. *(char**)pArg = sqlite3_mprintf("win32");
  2613. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2614. return SQLITE_OK;
  2615. }
  2616. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  2617. int *a = (int*)pArg;
  2618. if( a[0]>0 ){
  2619. winIoerrRetry = a[0];
  2620. }else{
  2621. a[0] = winIoerrRetry;
  2622. }
  2623. if( a[1]>0 ){
  2624. winIoerrRetryDelay = a[1];
  2625. }else{
  2626. a[1] = winIoerrRetryDelay;
  2627. }
  2628. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  2629. return SQLITE_OK;
  2630. }
  2631. case SQLITE_FCNTL_TEMPFILENAME: {
  2632. char *zTFile = 0;
  2633. int rc = winGetTempname(pFile->pVfs, &zTFile);
  2634. if( rc==SQLITE_OK ){
  2635. *(char**)pArg = zTFile;
  2636. }
  2637. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  2638. return rc;
  2639. }
  2640. #if SQLITE_MAX_MMAP_SIZE>0
  2641. case SQLITE_FCNTL_MMAP_SIZE: {
  2642. i64 newLimit = *(i64*)pArg;
  2643. int rc = SQLITE_OK;
  2644. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  2645. newLimit = sqlite3GlobalConfig.mxMmap;
  2646. }
  2647. *(i64*)pArg = pFile->mmapSizeMax;
  2648. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  2649. pFile->mmapSizeMax = newLimit;
  2650. if( pFile->mmapSize>0 ){
  2651. winUnmapfile(pFile);
  2652. rc = winMapfile(pFile, -1);
  2653. }
  2654. }
  2655. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  2656. return rc;
  2657. }
  2658. #endif
  2659. }
  2660. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  2661. return SQLITE_NOTFOUND;
  2662. }
  2663. /*
  2664. ** Return the sector size in bytes of the underlying block device for
  2665. ** the specified file. This is almost always 512 bytes, but may be
  2666. ** larger for some devices.
  2667. **
  2668. ** SQLite code assumes this function cannot fail. It also assumes that
  2669. ** if two files are created in the same file-system directory (i.e.
  2670. ** a database and its journal file) that the sector size will be the
  2671. ** same for both.
  2672. */
  2673. static int winSectorSize(sqlite3_file *id){
  2674. (void)id;
  2675. return SQLITE_DEFAULT_SECTOR_SIZE;
  2676. }
  2677. /*
  2678. ** Return a vector of device characteristics.
  2679. */
  2680. static int winDeviceCharacteristics(sqlite3_file *id){
  2681. winFile *p = (winFile*)id;
  2682. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  2683. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  2684. }
  2685. /*
  2686. ** Windows will only let you create file view mappings
  2687. ** on allocation size granularity boundaries.
  2688. ** During sqlite3_os_init() we do a GetSystemInfo()
  2689. ** to get the granularity size.
  2690. */
  2691. SYSTEM_INFO winSysInfo;
  2692. #ifndef SQLITE_OMIT_WAL
  2693. /*
  2694. ** Helper functions to obtain and relinquish the global mutex. The
  2695. ** global mutex is used to protect the winLockInfo objects used by
  2696. ** this file, all of which may be shared by multiple threads.
  2697. **
  2698. ** Function winShmMutexHeld() is used to assert() that the global mutex
  2699. ** is held when required. This function is only used as part of assert()
  2700. ** statements. e.g.
  2701. **
  2702. ** winShmEnterMutex()
  2703. ** assert( winShmMutexHeld() );
  2704. ** winShmLeaveMutex()
  2705. */
  2706. static void winShmEnterMutex(void){
  2707. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  2708. }
  2709. static void winShmLeaveMutex(void){
  2710. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  2711. }
  2712. #ifdef SQLITE_DEBUG
  2713. static int winShmMutexHeld(void) {
  2714. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  2715. }
  2716. #endif
  2717. /*
  2718. ** Object used to represent a single file opened and mmapped to provide
  2719. ** shared memory. When multiple threads all reference the same
  2720. ** log-summary, each thread has its own winFile object, but they all
  2721. ** point to a single instance of this object. In other words, each
  2722. ** log-summary is opened only once per process.
  2723. **
  2724. ** winShmMutexHeld() must be true when creating or destroying
  2725. ** this object or while reading or writing the following fields:
  2726. **
  2727. ** nRef
  2728. ** pNext
  2729. **
  2730. ** The following fields are read-only after the object is created:
  2731. **
  2732. ** fid
  2733. ** zFilename
  2734. **
  2735. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  2736. ** winShmMutexHeld() is true when reading or writing any other field
  2737. ** in this structure.
  2738. **
  2739. */
  2740. struct winShmNode {
  2741. sqlite3_mutex *mutex; /* Mutex to access this object */
  2742. char *zFilename; /* Name of the file */
  2743. winFile hFile; /* File handle from winOpen */
  2744. int szRegion; /* Size of shared-memory regions */
  2745. int nRegion; /* Size of array apRegion */
  2746. struct ShmRegion {
  2747. HANDLE hMap; /* File handle from CreateFileMapping */
  2748. void *pMap;
  2749. } *aRegion;
  2750. DWORD lastErrno; /* The Windows errno from the last I/O error */
  2751. int nRef; /* Number of winShm objects pointing to this */
  2752. winShm *pFirst; /* All winShm objects pointing to this */
  2753. winShmNode *pNext; /* Next in list of all winShmNode objects */
  2754. #ifdef SQLITE_DEBUG
  2755. u8 nextShmId; /* Next available winShm.id value */
  2756. #endif
  2757. };
  2758. /*
  2759. ** A global array of all winShmNode objects.
  2760. **
  2761. ** The winShmMutexHeld() must be true while reading or writing this list.
  2762. */
  2763. static winShmNode *winShmNodeList = 0;
  2764. /*
  2765. ** Structure used internally by this VFS to record the state of an
  2766. ** open shared memory connection.
  2767. **
  2768. ** The following fields are initialized when this object is created and
  2769. ** are read-only thereafter:
  2770. **
  2771. ** winShm.pShmNode
  2772. ** winShm.id
  2773. **
  2774. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  2775. ** while accessing any read/write fields.
  2776. */
  2777. struct winShm {
  2778. winShmNode *pShmNode; /* The underlying winShmNode object */
  2779. winShm *pNext; /* Next winShm with the same winShmNode */
  2780. u8 hasMutex; /* True if holding the winShmNode mutex */
  2781. u16 sharedMask; /* Mask of shared locks held */
  2782. u16 exclMask; /* Mask of exclusive locks held */
  2783. #ifdef SQLITE_DEBUG
  2784. u8 id; /* Id of this connection with its winShmNode */
  2785. #endif
  2786. };
  2787. /*
  2788. ** Constants used for locking
  2789. */
  2790. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  2791. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  2792. /*
  2793. ** Apply advisory locks for all n bytes beginning at ofst.
  2794. */
  2795. #define _SHM_UNLCK 1
  2796. #define _SHM_RDLCK 2
  2797. #define _SHM_WRLCK 3
  2798. static int winShmSystemLock(
  2799. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  2800. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  2801. int ofst, /* Offset to first byte to be locked/unlocked */
  2802. int nByte /* Number of bytes to lock or unlock */
  2803. ){
  2804. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  2805. /* Access to the winShmNode object is serialized by the caller */
  2806. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  2807. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  2808. pFile->hFile.h, lockType, ofst, nByte));
  2809. /* Release/Acquire the system-level lock */
  2810. if( lockType==_SHM_UNLCK ){
  2811. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  2812. }else{
  2813. /* Initialize the locking parameters */
  2814. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  2815. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  2816. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  2817. }
  2818. if( rc!= 0 ){
  2819. rc = SQLITE_OK;
  2820. }else{
  2821. pFile->lastErrno = osGetLastError();
  2822. rc = SQLITE_BUSY;
  2823. }
  2824. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  2825. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  2826. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  2827. return rc;
  2828. }
  2829. /* Forward references to VFS methods */
  2830. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  2831. static int winDelete(sqlite3_vfs *,const char*,int);
  2832. /*
  2833. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  2834. **
  2835. ** This is not a VFS shared-memory method; it is a utility function called
  2836. ** by VFS shared-memory methods.
  2837. */
  2838. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  2839. winShmNode **pp;
  2840. winShmNode *p;
  2841. assert( winShmMutexHeld() );
  2842. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  2843. osGetCurrentProcessId(), deleteFlag));
  2844. pp = &winShmNodeList;
  2845. while( (p = *pp)!=0 ){
  2846. if( p->nRef==0 ){
  2847. int i;
  2848. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  2849. for(i=0; i<p->nRegion; i++){
  2850. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  2851. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  2852. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  2853. UNUSED_VARIABLE_VALUE(bRc);
  2854. bRc = osCloseHandle(p->aRegion[i].hMap);
  2855. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  2856. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  2857. UNUSED_VARIABLE_VALUE(bRc);
  2858. }
  2859. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  2860. SimulateIOErrorBenign(1);
  2861. winClose((sqlite3_file *)&p->hFile);
  2862. SimulateIOErrorBenign(0);
  2863. }
  2864. if( deleteFlag ){
  2865. SimulateIOErrorBenign(1);
  2866. sqlite3BeginBenignMalloc();
  2867. winDelete(pVfs, p->zFilename, 0);
  2868. sqlite3EndBenignMalloc();
  2869. SimulateIOErrorBenign(0);
  2870. }
  2871. *pp = p->pNext;
  2872. sqlite3_free(p->aRegion);
  2873. sqlite3_free(p);
  2874. }else{
  2875. pp = &p->pNext;
  2876. }
  2877. }
  2878. }
  2879. /*
  2880. ** Open the shared-memory area associated with database file pDbFd.
  2881. **
  2882. ** When opening a new shared-memory file, if no other instances of that
  2883. ** file are currently open, in this process or in other processes, then
  2884. ** the file must be truncated to zero length or have its header cleared.
  2885. */
  2886. static int winOpenSharedMemory(winFile *pDbFd){
  2887. struct winShm *p; /* The connection to be opened */
  2888. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  2889. int rc; /* Result code */
  2890. struct winShmNode *pNew; /* Newly allocated winShmNode */
  2891. int nName; /* Size of zName in bytes */
  2892. assert( pDbFd->pShm==0 ); /* Not previously opened */
  2893. /* Allocate space for the new sqlite3_shm object. Also speculatively
  2894. ** allocate space for a new winShmNode and filename.
  2895. */
  2896. p = sqlite3MallocZero( sizeof(*p) );
  2897. if( p==0 ) return SQLITE_IOERR_NOMEM;
  2898. nName = sqlite3Strlen30(pDbFd->zPath);
  2899. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  2900. if( pNew==0 ){
  2901. sqlite3_free(p);
  2902. return SQLITE_IOERR_NOMEM;
  2903. }
  2904. pNew->zFilename = (char*)&pNew[1];
  2905. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  2906. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  2907. /* Look to see if there is an existing winShmNode that can be used.
  2908. ** If no matching winShmNode currently exists, create a new one.
  2909. */
  2910. winShmEnterMutex();
  2911. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  2912. /* TBD need to come up with better match here. Perhaps
  2913. ** use FILE_ID_BOTH_DIR_INFO Structure.
  2914. */
  2915. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  2916. }
  2917. if( pShmNode ){
  2918. sqlite3_free(pNew);
  2919. }else{
  2920. pShmNode = pNew;
  2921. pNew = 0;
  2922. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  2923. pShmNode->pNext = winShmNodeList;
  2924. winShmNodeList = pShmNode;
  2925. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  2926. if( pShmNode->mutex==0 ){
  2927. rc = SQLITE_IOERR_NOMEM;
  2928. goto shm_open_err;
  2929. }
  2930. rc = winOpen(pDbFd->pVfs,
  2931. pShmNode->zFilename, /* Name of the file (UTF-8) */
  2932. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  2933. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  2934. 0);
  2935. if( SQLITE_OK!=rc ){
  2936. goto shm_open_err;
  2937. }
  2938. /* Check to see if another process is holding the dead-man switch.
  2939. ** If not, truncate the file to zero length.
  2940. */
  2941. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  2942. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  2943. if( rc!=SQLITE_OK ){
  2944. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  2945. "winOpenShm", pDbFd->zPath);
  2946. }
  2947. }
  2948. if( rc==SQLITE_OK ){
  2949. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  2950. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  2951. }
  2952. if( rc ) goto shm_open_err;
  2953. }
  2954. /* Make the new connection a child of the winShmNode */
  2955. p->pShmNode = pShmNode;
  2956. #ifdef SQLITE_DEBUG
  2957. p->id = pShmNode->nextShmId++;
  2958. #endif
  2959. pShmNode->nRef++;
  2960. pDbFd->pShm = p;
  2961. winShmLeaveMutex();
  2962. /* The reference count on pShmNode has already been incremented under
  2963. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  2964. ** new (struct winShm) object to the pShmNode has been set. All that is
  2965. ** left to do is to link the new object into the linked list starting
  2966. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  2967. ** mutex.
  2968. */
  2969. sqlite3_mutex_enter(pShmNode->mutex);
  2970. p->pNext = pShmNode->pFirst;
  2971. pShmNode->pFirst = p;
  2972. sqlite3_mutex_leave(pShmNode->mutex);
  2973. return SQLITE_OK;
  2974. /* Jump here on any error */
  2975. shm_open_err:
  2976. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  2977. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  2978. sqlite3_free(p);
  2979. sqlite3_free(pNew);
  2980. winShmLeaveMutex();
  2981. return rc;
  2982. }
  2983. /*
  2984. ** Close a connection to shared-memory. Delete the underlying
  2985. ** storage if deleteFlag is true.
  2986. */
  2987. static int winShmUnmap(
  2988. sqlite3_file *fd, /* Database holding shared memory */
  2989. int deleteFlag /* Delete after closing if true */
  2990. ){
  2991. winFile *pDbFd; /* Database holding shared-memory */
  2992. winShm *p; /* The connection to be closed */
  2993. winShmNode *pShmNode; /* The underlying shared-memory file */
  2994. winShm **pp; /* For looping over sibling connections */
  2995. pDbFd = (winFile*)fd;
  2996. p = pDbFd->pShm;
  2997. if( p==0 ) return SQLITE_OK;
  2998. pShmNode = p->pShmNode;
  2999. /* Remove connection p from the set of connections associated
  3000. ** with pShmNode */
  3001. sqlite3_mutex_enter(pShmNode->mutex);
  3002. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  3003. *pp = p->pNext;
  3004. /* Free the connection p */
  3005. sqlite3_free(p);
  3006. pDbFd->pShm = 0;
  3007. sqlite3_mutex_leave(pShmNode->mutex);
  3008. /* If pShmNode->nRef has reached 0, then close the underlying
  3009. ** shared-memory file, too */
  3010. winShmEnterMutex();
  3011. assert( pShmNode->nRef>0 );
  3012. pShmNode->nRef--;
  3013. if( pShmNode->nRef==0 ){
  3014. winShmPurge(pDbFd->pVfs, deleteFlag);
  3015. }
  3016. winShmLeaveMutex();
  3017. return SQLITE_OK;
  3018. }
  3019. /*
  3020. ** Change the lock state for a shared-memory segment.
  3021. */
  3022. static int winShmLock(
  3023. sqlite3_file *fd, /* Database file holding the shared memory */
  3024. int ofst, /* First lock to acquire or release */
  3025. int n, /* Number of locks to acquire or release */
  3026. int flags /* What to do with the lock */
  3027. ){
  3028. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  3029. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  3030. winShm *pX; /* For looping over all siblings */
  3031. winShmNode *pShmNode = p->pShmNode;
  3032. int rc = SQLITE_OK; /* Result code */
  3033. u16 mask; /* Mask of locks to take or release */
  3034. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  3035. assert( n>=1 );
  3036. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  3037. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  3038. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  3039. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  3040. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  3041. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  3042. assert( n>1 || mask==(1<<ofst) );
  3043. sqlite3_mutex_enter(pShmNode->mutex);
  3044. if( flags & SQLITE_SHM_UNLOCK ){
  3045. u16 allMask = 0; /* Mask of locks held by siblings */
  3046. /* See if any siblings hold this same lock */
  3047. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  3048. if( pX==p ) continue;
  3049. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  3050. allMask |= pX->sharedMask;
  3051. }
  3052. /* Unlock the system-level locks */
  3053. if( (mask & allMask)==0 ){
  3054. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  3055. }else{
  3056. rc = SQLITE_OK;
  3057. }
  3058. /* Undo the local locks */
  3059. if( rc==SQLITE_OK ){
  3060. p->exclMask &= ~mask;
  3061. p->sharedMask &= ~mask;
  3062. }
  3063. }else if( flags & SQLITE_SHM_SHARED ){
  3064. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  3065. /* Find out which shared locks are already held by sibling connections.
  3066. ** If any sibling already holds an exclusive lock, go ahead and return
  3067. ** SQLITE_BUSY.
  3068. */
  3069. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  3070. if( (pX->exclMask & mask)!=0 ){
  3071. rc = SQLITE_BUSY;
  3072. break;
  3073. }
  3074. allShared |= pX->sharedMask;
  3075. }
  3076. /* Get shared locks at the system level, if necessary */
  3077. if( rc==SQLITE_OK ){
  3078. if( (allShared & mask)==0 ){
  3079. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  3080. }else{
  3081. rc = SQLITE_OK;
  3082. }
  3083. }
  3084. /* Get the local shared locks */
  3085. if( rc==SQLITE_OK ){
  3086. p->sharedMask |= mask;
  3087. }
  3088. }else{
  3089. /* Make sure no sibling connections hold locks that will block this
  3090. ** lock. If any do, return SQLITE_BUSY right away.
  3091. */
  3092. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  3093. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  3094. rc = SQLITE_BUSY;
  3095. break;
  3096. }
  3097. }
  3098. /* Get the exclusive locks at the system level. Then if successful
  3099. ** also mark the local connection as being locked.
  3100. */
  3101. if( rc==SQLITE_OK ){
  3102. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  3103. if( rc==SQLITE_OK ){
  3104. assert( (p->sharedMask & mask)==0 );
  3105. p->exclMask |= mask;
  3106. }
  3107. }
  3108. }
  3109. sqlite3_mutex_leave(pShmNode->mutex);
  3110. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  3111. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  3112. sqlite3ErrName(rc)));
  3113. return rc;
  3114. }
  3115. /*
  3116. ** Implement a memory barrier or memory fence on shared memory.
  3117. **
  3118. ** All loads and stores begun before the barrier must complete before
  3119. ** any load or store begun after the barrier.
  3120. */
  3121. static void winShmBarrier(
  3122. sqlite3_file *fd /* Database holding the shared memory */
  3123. ){
  3124. UNUSED_PARAMETER(fd);
  3125. /* MemoryBarrier(); // does not work -- do not know why not */
  3126. winShmEnterMutex();
  3127. winShmLeaveMutex();
  3128. }
  3129. /*
  3130. ** This function is called to obtain a pointer to region iRegion of the
  3131. ** shared-memory associated with the database file fd. Shared-memory regions
  3132. ** are numbered starting from zero. Each shared-memory region is szRegion
  3133. ** bytes in size.
  3134. **
  3135. ** If an error occurs, an error code is returned and *pp is set to NULL.
  3136. **
  3137. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  3138. ** region has not been allocated (by any client, including one running in a
  3139. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  3140. ** isWrite is non-zero and the requested shared-memory region has not yet
  3141. ** been allocated, it is allocated by this function.
  3142. **
  3143. ** If the shared-memory region has already been allocated or is allocated by
  3144. ** this call as described above, then it is mapped into this processes
  3145. ** address space (if it is not already), *pp is set to point to the mapped
  3146. ** memory and SQLITE_OK returned.
  3147. */
  3148. static int winShmMap(
  3149. sqlite3_file *fd, /* Handle open on database file */
  3150. int iRegion, /* Region to retrieve */
  3151. int szRegion, /* Size of regions */
  3152. int isWrite, /* True to extend file if necessary */
  3153. void volatile **pp /* OUT: Mapped memory */
  3154. ){
  3155. winFile *pDbFd = (winFile*)fd;
  3156. winShm *p = pDbFd->pShm;
  3157. winShmNode *pShmNode;
  3158. int rc = SQLITE_OK;
  3159. if( !p ){
  3160. rc = winOpenSharedMemory(pDbFd);
  3161. if( rc!=SQLITE_OK ) return rc;
  3162. p = pDbFd->pShm;
  3163. }
  3164. pShmNode = p->pShmNode;
  3165. sqlite3_mutex_enter(pShmNode->mutex);
  3166. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  3167. if( pShmNode->nRegion<=iRegion ){
  3168. struct ShmRegion *apNew; /* New aRegion[] array */
  3169. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  3170. sqlite3_int64 sz; /* Current size of wal-index file */
  3171. pShmNode->szRegion = szRegion;
  3172. /* The requested region is not mapped into this processes address space.
  3173. ** Check to see if it has been allocated (i.e. if the wal-index file is
  3174. ** large enough to contain the requested region).
  3175. */
  3176. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  3177. if( rc!=SQLITE_OK ){
  3178. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  3179. "winShmMap1", pDbFd->zPath);
  3180. goto shmpage_out;
  3181. }
  3182. if( sz<nByte ){
  3183. /* The requested memory region does not exist. If isWrite is set to
  3184. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  3185. **
  3186. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  3187. ** the requested memory region.
  3188. */
  3189. if( !isWrite ) goto shmpage_out;
  3190. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  3191. if( rc!=SQLITE_OK ){
  3192. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  3193. "winShmMap2", pDbFd->zPath);
  3194. goto shmpage_out;
  3195. }
  3196. }
  3197. /* Map the requested memory region into this processes address space. */
  3198. apNew = (struct ShmRegion *)sqlite3_realloc(
  3199. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  3200. );
  3201. if( !apNew ){
  3202. rc = SQLITE_IOERR_NOMEM;
  3203. goto shmpage_out;
  3204. }
  3205. pShmNode->aRegion = apNew;
  3206. while( pShmNode->nRegion<=iRegion ){
  3207. HANDLE hMap = NULL; /* file-mapping handle */
  3208. void *pMap = 0; /* Mapped memory region */
  3209. #if SQLITE_OS_WINRT
  3210. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  3211. NULL, PAGE_READWRITE, nByte, NULL
  3212. );
  3213. #elif defined(SQLITE_WIN32_HAS_WIDE)
  3214. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  3215. NULL, PAGE_READWRITE, 0, nByte, NULL
  3216. );
  3217. #elif defined(SQLITE_WIN32_HAS_ANSI)
  3218. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  3219. NULL, PAGE_READWRITE, 0, nByte, NULL
  3220. );
  3221. #endif
  3222. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  3223. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  3224. hMap ? "ok" : "failed"));
  3225. if( hMap ){
  3226. int iOffset = pShmNode->nRegion*szRegion;
  3227. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  3228. #if SQLITE_OS_WINRT
  3229. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  3230. iOffset - iOffsetShift, szRegion + iOffsetShift
  3231. );
  3232. #else
  3233. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  3234. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  3235. );
  3236. #endif
  3237. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  3238. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  3239. szRegion, pMap ? "ok" : "failed"));
  3240. }
  3241. if( !pMap ){
  3242. pShmNode->lastErrno = osGetLastError();
  3243. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  3244. "winShmMap3", pDbFd->zPath);
  3245. if( hMap ) osCloseHandle(hMap);
  3246. goto shmpage_out;
  3247. }
  3248. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  3249. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  3250. pShmNode->nRegion++;
  3251. }
  3252. }
  3253. shmpage_out:
  3254. if( pShmNode->nRegion>iRegion ){
  3255. int iOffset = iRegion*szRegion;
  3256. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  3257. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  3258. *pp = (void *)&p[iOffsetShift];
  3259. }else{
  3260. *pp = 0;
  3261. }
  3262. sqlite3_mutex_leave(pShmNode->mutex);
  3263. return rc;
  3264. }
  3265. #else
  3266. # define winShmMap 0
  3267. # define winShmLock 0
  3268. # define winShmBarrier 0
  3269. # define winShmUnmap 0
  3270. #endif /* #ifndef SQLITE_OMIT_WAL */
  3271. /*
  3272. ** Cleans up the mapped region of the specified file, if any.
  3273. */
  3274. #if SQLITE_MAX_MMAP_SIZE>0
  3275. static int winUnmapfile(winFile *pFile){
  3276. assert( pFile!=0 );
  3277. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  3278. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  3279. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  3280. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  3281. if( pFile->pMapRegion ){
  3282. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  3283. pFile->lastErrno = osGetLastError();
  3284. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  3285. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  3286. pFile->pMapRegion));
  3287. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  3288. "winUnmapfile1", pFile->zPath);
  3289. }
  3290. pFile->pMapRegion = 0;
  3291. pFile->mmapSize = 0;
  3292. pFile->mmapSizeActual = 0;
  3293. }
  3294. if( pFile->hMap!=NULL ){
  3295. if( !osCloseHandle(pFile->hMap) ){
  3296. pFile->lastErrno = osGetLastError();
  3297. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  3298. osGetCurrentProcessId(), pFile, pFile->hMap));
  3299. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  3300. "winUnmapfile2", pFile->zPath);
  3301. }
  3302. pFile->hMap = NULL;
  3303. }
  3304. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  3305. osGetCurrentProcessId(), pFile));
  3306. return SQLITE_OK;
  3307. }
  3308. /*
  3309. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  3310. ** is already mapped, the existing mapping is replaced by the new). Or, if
  3311. ** there already exists a mapping for this file, and there are still
  3312. ** outstanding xFetch() references to it, this function is a no-op.
  3313. **
  3314. ** If parameter nByte is non-negative, then it is the requested size of
  3315. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  3316. ** requested size is the size of the file on disk. The actual size of the
  3317. ** created mapping is either the requested size or the value configured
  3318. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  3319. **
  3320. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  3321. ** recreated as a result of outstanding references) or an SQLite error
  3322. ** code otherwise.
  3323. */
  3324. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  3325. sqlite3_int64 nMap = nByte;
  3326. int rc;
  3327. assert( nMap>=0 || pFd->nFetchOut==0 );
  3328. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  3329. osGetCurrentProcessId(), pFd, nByte));
  3330. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  3331. if( nMap<0 ){
  3332. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  3333. if( rc ){
  3334. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  3335. osGetCurrentProcessId(), pFd));
  3336. return SQLITE_IOERR_FSTAT;
  3337. }
  3338. }
  3339. if( nMap>pFd->mmapSizeMax ){
  3340. nMap = pFd->mmapSizeMax;
  3341. }
  3342. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  3343. if( nMap==0 && pFd->mmapSize>0 ){
  3344. winUnmapfile(pFd);
  3345. }
  3346. if( nMap!=pFd->mmapSize ){
  3347. void *pNew = 0;
  3348. DWORD protect = PAGE_READONLY;
  3349. DWORD flags = FILE_MAP_READ;
  3350. winUnmapfile(pFd);
  3351. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  3352. protect = PAGE_READWRITE;
  3353. flags |= FILE_MAP_WRITE;
  3354. }
  3355. #if SQLITE_OS_WINRT
  3356. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  3357. #elif defined(SQLITE_WIN32_HAS_WIDE)
  3358. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  3359. (DWORD)((nMap>>32) & 0xffffffff),
  3360. (DWORD)(nMap & 0xffffffff), NULL);
  3361. #elif defined(SQLITE_WIN32_HAS_ANSI)
  3362. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  3363. (DWORD)((nMap>>32) & 0xffffffff),
  3364. (DWORD)(nMap & 0xffffffff), NULL);
  3365. #endif
  3366. if( pFd->hMap==NULL ){
  3367. pFd->lastErrno = osGetLastError();
  3368. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  3369. "winMapfile1", pFd->zPath);
  3370. /* Log the error, but continue normal operation using xRead/xWrite */
  3371. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  3372. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  3373. return SQLITE_OK;
  3374. }
  3375. assert( (nMap % winSysInfo.dwPageSize)==0 );
  3376. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  3377. #if SQLITE_OS_WINRT
  3378. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  3379. #else
  3380. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  3381. #endif
  3382. if( pNew==NULL ){
  3383. osCloseHandle(pFd->hMap);
  3384. pFd->hMap = NULL;
  3385. pFd->lastErrno = osGetLastError();
  3386. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  3387. "winMapfile2", pFd->zPath);
  3388. /* Log the error, but continue normal operation using xRead/xWrite */
  3389. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  3390. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  3391. return SQLITE_OK;
  3392. }
  3393. pFd->pMapRegion = pNew;
  3394. pFd->mmapSize = nMap;
  3395. pFd->mmapSizeActual = nMap;
  3396. }
  3397. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  3398. osGetCurrentProcessId(), pFd));
  3399. return SQLITE_OK;
  3400. }
  3401. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  3402. /*
  3403. ** If possible, return a pointer to a mapping of file fd starting at offset
  3404. ** iOff. The mapping must be valid for at least nAmt bytes.
  3405. **
  3406. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  3407. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  3408. ** Finally, if an error does occur, return an SQLite error code. The final
  3409. ** value of *pp is undefined in this case.
  3410. **
  3411. ** If this function does return a pointer, the caller must eventually
  3412. ** release the reference by calling winUnfetch().
  3413. */
  3414. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  3415. #if SQLITE_MAX_MMAP_SIZE>0
  3416. winFile *pFd = (winFile*)fd; /* The underlying database file */
  3417. #endif
  3418. *pp = 0;
  3419. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  3420. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  3421. #if SQLITE_MAX_MMAP_SIZE>0
  3422. if( pFd->mmapSizeMax>0 ){
  3423. if( pFd->pMapRegion==0 ){
  3424. int rc = winMapfile(pFd, -1);
  3425. if( rc!=SQLITE_OK ){
  3426. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  3427. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  3428. return rc;
  3429. }
  3430. }
  3431. if( pFd->mmapSize >= iOff+nAmt ){
  3432. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  3433. pFd->nFetchOut++;
  3434. }
  3435. }
  3436. #endif
  3437. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  3438. osGetCurrentProcessId(), fd, pp, *pp));
  3439. return SQLITE_OK;
  3440. }
  3441. /*
  3442. ** If the third argument is non-NULL, then this function releases a
  3443. ** reference obtained by an earlier call to winFetch(). The second
  3444. ** argument passed to this function must be the same as the corresponding
  3445. ** argument that was passed to the winFetch() invocation.
  3446. **
  3447. ** Or, if the third argument is NULL, then this function is being called
  3448. ** to inform the VFS layer that, according to POSIX, any existing mapping
  3449. ** may now be invalid and should be unmapped.
  3450. */
  3451. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  3452. #if SQLITE_MAX_MMAP_SIZE>0
  3453. winFile *pFd = (winFile*)fd; /* The underlying database file */
  3454. /* If p==0 (unmap the entire file) then there must be no outstanding
  3455. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  3456. ** then there must be at least one outstanding. */
  3457. assert( (p==0)==(pFd->nFetchOut==0) );
  3458. /* If p!=0, it must match the iOff value. */
  3459. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  3460. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  3461. osGetCurrentProcessId(), pFd, iOff, p));
  3462. if( p ){
  3463. pFd->nFetchOut--;
  3464. }else{
  3465. /* FIXME: If Windows truly always prevents truncating or deleting a
  3466. ** file while a mapping is held, then the following winUnmapfile() call
  3467. ** is unnecessary can can be omitted - potentially improving
  3468. ** performance. */
  3469. winUnmapfile(pFd);
  3470. }
  3471. assert( pFd->nFetchOut>=0 );
  3472. #endif
  3473. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  3474. osGetCurrentProcessId(), fd));
  3475. return SQLITE_OK;
  3476. }
  3477. /*
  3478. ** Here ends the implementation of all sqlite3_file methods.
  3479. **
  3480. ********************** End sqlite3_file Methods *******************************
  3481. ******************************************************************************/
  3482. /*
  3483. ** This vector defines all the methods that can operate on an
  3484. ** sqlite3_file for win32.
  3485. */
  3486. static const sqlite3_io_methods winIoMethod = {
  3487. 3, /* iVersion */
  3488. winClose, /* xClose */
  3489. winRead, /* xRead */
  3490. winWrite, /* xWrite */
  3491. winTruncate, /* xTruncate */
  3492. winSync, /* xSync */
  3493. winFileSize, /* xFileSize */
  3494. winLock, /* xLock */
  3495. winUnlock, /* xUnlock */
  3496. winCheckReservedLock, /* xCheckReservedLock */
  3497. winFileControl, /* xFileControl */
  3498. winSectorSize, /* xSectorSize */
  3499. winDeviceCharacteristics, /* xDeviceCharacteristics */
  3500. winShmMap, /* xShmMap */
  3501. winShmLock, /* xShmLock */
  3502. winShmBarrier, /* xShmBarrier */
  3503. winShmUnmap, /* xShmUnmap */
  3504. winFetch, /* xFetch */
  3505. winUnfetch /* xUnfetch */
  3506. };
  3507. /****************************************************************************
  3508. **************************** sqlite3_vfs methods ****************************
  3509. **
  3510. ** This division contains the implementation of methods on the
  3511. ** sqlite3_vfs object.
  3512. */
  3513. #if 0
  3514. /*
  3515. ** Convert a filename from whatever the underlying operating system
  3516. ** supports for filenames into UTF-8. Space to hold the result is
  3517. ** obtained from malloc and must be freed by the calling function.
  3518. */
  3519. static char *winConvertToUtf8Filename(const void *zFilename){
  3520. char *zConverted = 0;
  3521. if( osIsNT() ){
  3522. zConverted = winUnicodeToUtf8(zFilename);
  3523. }
  3524. #ifdef SQLITE_WIN32_HAS_ANSI
  3525. else{
  3526. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  3527. }
  3528. #endif
  3529. /* caller will handle out of memory */
  3530. return zConverted;
  3531. }
  3532. #endif
  3533. /*
  3534. ** Convert a UTF-8 filename into whatever form the underlying
  3535. ** operating system wants filenames in. Space to hold the result
  3536. ** is obtained from malloc and must be freed by the calling
  3537. ** function.
  3538. */
  3539. static void *winConvertFromUtf8Filename(const char *zFilename){
  3540. void *zConverted = 0;
  3541. if( osIsNT() ){
  3542. zConverted = winUtf8ToUnicode(zFilename);
  3543. }
  3544. #ifdef SQLITE_WIN32_HAS_ANSI
  3545. else{
  3546. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  3547. }
  3548. #endif
  3549. /* caller will handle out of memory */
  3550. return zConverted;
  3551. }
  3552. /*
  3553. ** This function returns non-zero if the specified UTF-8 string buffer
  3554. ** ends with a directory separator character.
  3555. */
  3556. static int winEndsInDirSep(char *zBuf){
  3557. if( zBuf ){
  3558. int nLen = sqlite3Strlen30(zBuf);
  3559. return nLen>0 && winIsDirSep(zBuf[nLen-1]);
  3560. }
  3561. return 0;
  3562. }
  3563. /*
  3564. ** Create a temporary file name and store the resulting pointer into pzBuf.
  3565. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  3566. */
  3567. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  3568. static char zChars[] =
  3569. "abcdefghijklmnopqrstuvwxyz"
  3570. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3571. "0123456789";
  3572. size_t i, j;
  3573. int nBuf, nLen;
  3574. char *zBuf;
  3575. /* It's odd to simulate an io-error here, but really this is just
  3576. ** using the io-error infrastructure to test that SQLite handles this
  3577. ** function failing.
  3578. */
  3579. SimulateIOError( return SQLITE_IOERR );
  3580. /* Allocate a temporary buffer to store the fully qualified file
  3581. ** name for the temporary file. If this fails, we cannot continue.
  3582. */
  3583. nBuf = pVfs->mxPathname;
  3584. zBuf = sqlite3MallocZero( nBuf+2 );
  3585. if( !zBuf ){
  3586. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3587. return SQLITE_IOERR_NOMEM;
  3588. }
  3589. /* Figure out the effective temporary directory. First, check if one
  3590. ** has been explicitly set by the application; otherwise, use the one
  3591. ** configured by the operating system.
  3592. */
  3593. assert( nBuf>30 );
  3594. if( sqlite3_temp_directory ){
  3595. sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory,
  3596. winEndsInDirSep(sqlite3_temp_directory) ? "" :
  3597. winGetDirDep());
  3598. }
  3599. #if defined(__CYGWIN__)
  3600. else{
  3601. static const char *azDirs[] = {
  3602. 0, /* getenv("SQLITE_TMPDIR") */
  3603. 0, /* getenv("TMPDIR") */
  3604. 0, /* getenv("TMP") */
  3605. 0, /* getenv("TEMP") */
  3606. 0, /* getenv("USERPROFILE") */
  3607. "/var/tmp",
  3608. "/usr/tmp",
  3609. "/tmp",
  3610. ".",
  3611. 0 /* List terminator */
  3612. };
  3613. unsigned int i;
  3614. const char *zDir = 0;
  3615. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  3616. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  3617. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  3618. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  3619. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  3620. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  3621. void *zConverted;
  3622. if( zDir==0 ) continue;
  3623. /* If the path starts with a drive letter followed by the colon
  3624. ** character, assume it is already a native Win32 path; otherwise,
  3625. ** it must be converted to a native Win32 path prior via the Cygwin
  3626. ** API prior to using it.
  3627. */
  3628. if( winIsDriveLetterAndColon(zDir) ){
  3629. zConverted = winConvertFromUtf8Filename(zDir);
  3630. if( !zConverted ){
  3631. sqlite3_free(zBuf);
  3632. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3633. return SQLITE_IOERR_NOMEM;
  3634. }
  3635. if( winIsDir(zConverted) ){
  3636. sqlite3_snprintf(nBuf-30, zBuf, "%s", zDir);
  3637. sqlite3_free(zConverted);
  3638. break;
  3639. }
  3640. sqlite3_free(zConverted);
  3641. }else{
  3642. zConverted = sqlite3MallocZero( nBuf+1 );
  3643. if( !zConverted ){
  3644. sqlite3_free(zBuf);
  3645. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3646. return SQLITE_IOERR_NOMEM;
  3647. }
  3648. if( cygwin_conv_path(
  3649. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  3650. zConverted, nBuf+1)<0 ){
  3651. sqlite3_free(zConverted);
  3652. sqlite3_free(zBuf);
  3653. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  3654. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  3655. "winGetTempname1", zDir);
  3656. }
  3657. if( winIsDir(zConverted) ){
  3658. /* At this point, we know the candidate directory exists and should
  3659. ** be used. However, we may need to convert the string containing
  3660. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  3661. */
  3662. if( osIsNT() ){
  3663. char *zUtf8 = winUnicodeToUtf8(zConverted);
  3664. if( !zUtf8 ){
  3665. sqlite3_free(zConverted);
  3666. sqlite3_free(zBuf);
  3667. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3668. return SQLITE_IOERR_NOMEM;
  3669. }
  3670. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  3671. sqlite3_free(zUtf8);
  3672. sqlite3_free(zConverted);
  3673. break;
  3674. }else{
  3675. sqlite3_snprintf(nBuf-30, zBuf, "%s", zConverted);
  3676. sqlite3_free(zConverted);
  3677. break;
  3678. }
  3679. }
  3680. sqlite3_free(zConverted);
  3681. }
  3682. }
  3683. }
  3684. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  3685. else if( osIsNT() ){
  3686. char *zMulti;
  3687. LPWSTR zWidePath = sqlite3MallocZero( nBuf*sizeof(WCHAR) );
  3688. if( !zWidePath ){
  3689. sqlite3_free(zBuf);
  3690. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3691. return SQLITE_IOERR_NOMEM;
  3692. }
  3693. if( osGetTempPathW(nBuf, zWidePath)==0 ){
  3694. sqlite3_free(zWidePath);
  3695. sqlite3_free(zBuf);
  3696. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  3697. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  3698. "winGetTempname1", 0);
  3699. }
  3700. zMulti = winUnicodeToUtf8(zWidePath);
  3701. if( zMulti ){
  3702. sqlite3_snprintf(nBuf-30, zBuf, "%s", zMulti);
  3703. sqlite3_free(zMulti);
  3704. sqlite3_free(zWidePath);
  3705. }else{
  3706. sqlite3_free(zWidePath);
  3707. sqlite3_free(zBuf);
  3708. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3709. return SQLITE_IOERR_NOMEM;
  3710. }
  3711. }
  3712. #ifdef SQLITE_WIN32_HAS_ANSI
  3713. else{
  3714. char *zUtf8;
  3715. char *zMbcsPath = sqlite3MallocZero( nBuf );
  3716. if( !zMbcsPath ){
  3717. sqlite3_free(zBuf);
  3718. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3719. return SQLITE_IOERR_NOMEM;
  3720. }
  3721. if( osGetTempPathA(nBuf, zMbcsPath)==0 ){
  3722. sqlite3_free(zBuf);
  3723. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  3724. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  3725. "winGetTempname2", 0);
  3726. }
  3727. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  3728. if( zUtf8 ){
  3729. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  3730. sqlite3_free(zUtf8);
  3731. }else{
  3732. sqlite3_free(zBuf);
  3733. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3734. return SQLITE_IOERR_NOMEM;
  3735. }
  3736. }
  3737. #endif /* SQLITE_WIN32_HAS_ANSI */
  3738. #endif /* !SQLITE_OS_WINRT */
  3739. /* Check that the output buffer is large enough for the temporary file
  3740. ** name. If it is not, return SQLITE_ERROR.
  3741. */
  3742. nLen = sqlite3Strlen30(zBuf);
  3743. if( (nLen + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  3744. sqlite3_free(zBuf);
  3745. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  3746. return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0);
  3747. }
  3748. sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  3749. j = sqlite3Strlen30(zBuf);
  3750. sqlite3_randomness(15, &zBuf[j]);
  3751. for(i=0; i<15; i++, j++){
  3752. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  3753. }
  3754. zBuf[j] = 0;
  3755. zBuf[j+1] = 0;
  3756. *pzBuf = zBuf;
  3757. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  3758. return SQLITE_OK;
  3759. }
  3760. /*
  3761. ** Return TRUE if the named file is really a directory. Return false if
  3762. ** it is something other than a directory, or if there is any kind of memory
  3763. ** allocation failure.
  3764. */
  3765. static int winIsDir(const void *zConverted){
  3766. DWORD attr;
  3767. int rc = 0;
  3768. DWORD lastErrno;
  3769. if( osIsNT() ){
  3770. int cnt = 0;
  3771. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  3772. memset(&sAttrData, 0, sizeof(sAttrData));
  3773. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  3774. GetFileExInfoStandard,
  3775. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  3776. if( !rc ){
  3777. return 0; /* Invalid name? */
  3778. }
  3779. attr = sAttrData.dwFileAttributes;
  3780. #if SQLITE_OS_WINCE==0
  3781. }else{
  3782. attr = osGetFileAttributesA((char*)zConverted);
  3783. #endif
  3784. }
  3785. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  3786. }
  3787. /*
  3788. ** Open a file.
  3789. */
  3790. static int winOpen(
  3791. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  3792. const char *zName, /* Name of the file (UTF-8) */
  3793. sqlite3_file *id, /* Write the SQLite file handle here */
  3794. int flags, /* Open mode flags */
  3795. int *pOutFlags /* Status return flags */
  3796. ){
  3797. HANDLE h;
  3798. DWORD lastErrno;
  3799. DWORD dwDesiredAccess;
  3800. DWORD dwShareMode;
  3801. DWORD dwCreationDisposition;
  3802. DWORD dwFlagsAndAttributes = 0;
  3803. #if SQLITE_OS_WINCE
  3804. int isTemp = 0;
  3805. #endif
  3806. winFile *pFile = (winFile*)id;
  3807. void *zConverted; /* Filename in OS encoding */
  3808. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  3809. int cnt = 0;
  3810. /* If argument zPath is a NULL pointer, this function is required to open
  3811. ** a temporary file. Use this buffer to store the file name in.
  3812. */
  3813. char *zTmpname = 0; /* For temporary filename, if necessary. */
  3814. int rc = SQLITE_OK; /* Function Return Code */
  3815. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  3816. int eType = flags&0xFFFFFF00; /* Type of file to open */
  3817. #endif
  3818. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  3819. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  3820. int isCreate = (flags & SQLITE_OPEN_CREATE);
  3821. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  3822. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  3823. #ifndef NDEBUG
  3824. int isOpenJournal = (isCreate && (
  3825. eType==SQLITE_OPEN_MASTER_JOURNAL
  3826. || eType==SQLITE_OPEN_MAIN_JOURNAL
  3827. || eType==SQLITE_OPEN_WAL
  3828. ));
  3829. #endif
  3830. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  3831. zUtf8Name, id, flags, pOutFlags));
  3832. /* Check the following statements are true:
  3833. **
  3834. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  3835. ** (b) if CREATE is set, then READWRITE must also be set, and
  3836. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  3837. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  3838. */
  3839. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  3840. assert(isCreate==0 || isReadWrite);
  3841. assert(isExclusive==0 || isCreate);
  3842. assert(isDelete==0 || isCreate);
  3843. /* The main DB, main journal, WAL file and master journal are never
  3844. ** automatically deleted. Nor are they ever temporary files. */
  3845. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  3846. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  3847. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  3848. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  3849. /* Assert that the upper layer has set one of the "file-type" flags. */
  3850. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  3851. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  3852. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  3853. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  3854. );
  3855. assert( pFile!=0 );
  3856. memset(pFile, 0, sizeof(winFile));
  3857. pFile->h = INVALID_HANDLE_VALUE;
  3858. #if SQLITE_OS_WINRT
  3859. if( !zUtf8Name && !sqlite3_temp_directory ){
  3860. sqlite3_log(SQLITE_ERROR,
  3861. "sqlite3_temp_directory variable should be set for WinRT");
  3862. }
  3863. #endif
  3864. /* If the second argument to this function is NULL, generate a
  3865. ** temporary file name to use
  3866. */
  3867. if( !zUtf8Name ){
  3868. assert( isDelete && !isOpenJournal );
  3869. rc = winGetTempname(pVfs, &zTmpname);
  3870. if( rc!=SQLITE_OK ){
  3871. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  3872. return rc;
  3873. }
  3874. zUtf8Name = zTmpname;
  3875. }
  3876. /* Database filenames are double-zero terminated if they are not
  3877. ** URIs with parameters. Hence, they can always be passed into
  3878. ** sqlite3_uri_parameter().
  3879. */
  3880. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  3881. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  3882. /* Convert the filename to the system encoding. */
  3883. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  3884. if( zConverted==0 ){
  3885. sqlite3_free(zTmpname);
  3886. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  3887. return SQLITE_IOERR_NOMEM;
  3888. }
  3889. if( winIsDir(zConverted) ){
  3890. sqlite3_free(zConverted);
  3891. sqlite3_free(zTmpname);
  3892. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  3893. return SQLITE_CANTOPEN_ISDIR;
  3894. }
  3895. if( isReadWrite ){
  3896. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  3897. }else{
  3898. dwDesiredAccess = GENERIC_READ;
  3899. }
  3900. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  3901. ** created. SQLite doesn't use it to indicate "exclusive access"
  3902. ** as it is usually understood.
  3903. */
  3904. if( isExclusive ){
  3905. /* Creates a new file, only if it does not already exist. */
  3906. /* If the file exists, it fails. */
  3907. dwCreationDisposition = CREATE_NEW;
  3908. }else if( isCreate ){
  3909. /* Open existing file, or create if it doesn't exist */
  3910. dwCreationDisposition = OPEN_ALWAYS;
  3911. }else{
  3912. /* Opens a file, only if it exists. */
  3913. dwCreationDisposition = OPEN_EXISTING;
  3914. }
  3915. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  3916. if( isDelete ){
  3917. #if SQLITE_OS_WINCE
  3918. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  3919. isTemp = 1;
  3920. #else
  3921. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  3922. | FILE_ATTRIBUTE_HIDDEN
  3923. | FILE_FLAG_DELETE_ON_CLOSE;
  3924. #endif
  3925. }else{
  3926. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  3927. }
  3928. /* Reports from the internet are that performance is always
  3929. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  3930. #if SQLITE_OS_WINCE
  3931. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  3932. #endif
  3933. if( osIsNT() ){
  3934. #if SQLITE_OS_WINRT
  3935. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  3936. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  3937. extendedParameters.dwFileAttributes =
  3938. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  3939. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  3940. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  3941. extendedParameters.lpSecurityAttributes = NULL;
  3942. extendedParameters.hTemplateFile = NULL;
  3943. while( (h = osCreateFile2((LPCWSTR)zConverted,
  3944. dwDesiredAccess,
  3945. dwShareMode,
  3946. dwCreationDisposition,
  3947. &extendedParameters))==INVALID_HANDLE_VALUE &&
  3948. winRetryIoerr(&cnt, &lastErrno) ){
  3949. /* Noop */
  3950. }
  3951. #else
  3952. while( (h = osCreateFileW((LPCWSTR)zConverted,
  3953. dwDesiredAccess,
  3954. dwShareMode, NULL,
  3955. dwCreationDisposition,
  3956. dwFlagsAndAttributes,
  3957. NULL))==INVALID_HANDLE_VALUE &&
  3958. winRetryIoerr(&cnt, &lastErrno) ){
  3959. /* Noop */
  3960. }
  3961. #endif
  3962. }
  3963. #ifdef SQLITE_WIN32_HAS_ANSI
  3964. else{
  3965. while( (h = osCreateFileA((LPCSTR)zConverted,
  3966. dwDesiredAccess,
  3967. dwShareMode, NULL,
  3968. dwCreationDisposition,
  3969. dwFlagsAndAttributes,
  3970. NULL))==INVALID_HANDLE_VALUE &&
  3971. winRetryIoerr(&cnt, &lastErrno) ){
  3972. /* Noop */
  3973. }
  3974. }
  3975. #endif
  3976. winLogIoerr(cnt);
  3977. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  3978. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  3979. if( h==INVALID_HANDLE_VALUE ){
  3980. pFile->lastErrno = lastErrno;
  3981. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  3982. sqlite3_free(zConverted);
  3983. sqlite3_free(zTmpname);
  3984. if( isReadWrite && !isExclusive ){
  3985. return winOpen(pVfs, zName, id,
  3986. ((flags|SQLITE_OPEN_READONLY) &
  3987. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  3988. pOutFlags);
  3989. }else{
  3990. return SQLITE_CANTOPEN_BKPT;
  3991. }
  3992. }
  3993. if( pOutFlags ){
  3994. if( isReadWrite ){
  3995. *pOutFlags = SQLITE_OPEN_READWRITE;
  3996. }else{
  3997. *pOutFlags = SQLITE_OPEN_READONLY;
  3998. }
  3999. }
  4000. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  4001. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  4002. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  4003. #if SQLITE_OS_WINCE
  4004. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  4005. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  4006. ){
  4007. osCloseHandle(h);
  4008. sqlite3_free(zConverted);
  4009. sqlite3_free(zTmpname);
  4010. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  4011. return rc;
  4012. }
  4013. if( isTemp ){
  4014. pFile->zDeleteOnClose = zConverted;
  4015. }else
  4016. #endif
  4017. {
  4018. sqlite3_free(zConverted);
  4019. }
  4020. sqlite3_free(zTmpname);
  4021. pFile->pMethod = &winIoMethod;
  4022. pFile->pVfs = pVfs;
  4023. pFile->h = h;
  4024. if( isReadonly ){
  4025. pFile->ctrlFlags |= WINFILE_RDONLY;
  4026. }
  4027. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  4028. pFile->ctrlFlags |= WINFILE_PSOW;
  4029. }
  4030. pFile->lastErrno = NO_ERROR;
  4031. pFile->zPath = zName;
  4032. #if SQLITE_MAX_MMAP_SIZE>0
  4033. pFile->hMap = NULL;
  4034. pFile->pMapRegion = 0;
  4035. pFile->mmapSize = 0;
  4036. pFile->mmapSizeActual = 0;
  4037. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  4038. #endif
  4039. OpenCounter(+1);
  4040. return rc;
  4041. }
  4042. /*
  4043. ** Delete the named file.
  4044. **
  4045. ** Note that Windows does not allow a file to be deleted if some other
  4046. ** process has it open. Sometimes a virus scanner or indexing program
  4047. ** will open a journal file shortly after it is created in order to do
  4048. ** whatever it does. While this other process is holding the
  4049. ** file open, we will be unable to delete it. To work around this
  4050. ** problem, we delay 100 milliseconds and try to delete again. Up
  4051. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  4052. ** up and returning an error.
  4053. */
  4054. static int winDelete(
  4055. sqlite3_vfs *pVfs, /* Not used on win32 */
  4056. const char *zFilename, /* Name of file to delete */
  4057. int syncDir /* Not used on win32 */
  4058. ){
  4059. int cnt = 0;
  4060. int rc;
  4061. DWORD attr;
  4062. DWORD lastErrno;
  4063. void *zConverted;
  4064. UNUSED_PARAMETER(pVfs);
  4065. UNUSED_PARAMETER(syncDir);
  4066. SimulateIOError(return SQLITE_IOERR_DELETE);
  4067. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  4068. zConverted = winConvertFromUtf8Filename(zFilename);
  4069. if( zConverted==0 ){
  4070. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  4071. return SQLITE_IOERR_NOMEM;
  4072. }
  4073. if( osIsNT() ){
  4074. do {
  4075. #if SQLITE_OS_WINRT
  4076. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  4077. memset(&sAttrData, 0, sizeof(sAttrData));
  4078. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  4079. &sAttrData) ){
  4080. attr = sAttrData.dwFileAttributes;
  4081. }else{
  4082. lastErrno = osGetLastError();
  4083. if( lastErrno==ERROR_FILE_NOT_FOUND
  4084. || lastErrno==ERROR_PATH_NOT_FOUND ){
  4085. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  4086. }else{
  4087. rc = SQLITE_ERROR;
  4088. }
  4089. break;
  4090. }
  4091. #else
  4092. attr = osGetFileAttributesW(zConverted);
  4093. #endif
  4094. if ( attr==INVALID_FILE_ATTRIBUTES ){
  4095. lastErrno = osGetLastError();
  4096. if( lastErrno==ERROR_FILE_NOT_FOUND
  4097. || lastErrno==ERROR_PATH_NOT_FOUND ){
  4098. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  4099. }else{
  4100. rc = SQLITE_ERROR;
  4101. }
  4102. break;
  4103. }
  4104. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  4105. rc = SQLITE_ERROR; /* Files only. */
  4106. break;
  4107. }
  4108. if ( osDeleteFileW(zConverted) ){
  4109. rc = SQLITE_OK; /* Deleted OK. */
  4110. break;
  4111. }
  4112. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  4113. rc = SQLITE_ERROR; /* No more retries. */
  4114. break;
  4115. }
  4116. } while(1);
  4117. }
  4118. #ifdef SQLITE_WIN32_HAS_ANSI
  4119. else{
  4120. do {
  4121. attr = osGetFileAttributesA(zConverted);
  4122. if ( attr==INVALID_FILE_ATTRIBUTES ){
  4123. lastErrno = osGetLastError();
  4124. if( lastErrno==ERROR_FILE_NOT_FOUND
  4125. || lastErrno==ERROR_PATH_NOT_FOUND ){
  4126. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  4127. }else{
  4128. rc = SQLITE_ERROR;
  4129. }
  4130. break;
  4131. }
  4132. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  4133. rc = SQLITE_ERROR; /* Files only. */
  4134. break;
  4135. }
  4136. if ( osDeleteFileA(zConverted) ){
  4137. rc = SQLITE_OK; /* Deleted OK. */
  4138. break;
  4139. }
  4140. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  4141. rc = SQLITE_ERROR; /* No more retries. */
  4142. break;
  4143. }
  4144. } while(1);
  4145. }
  4146. #endif
  4147. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  4148. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  4149. }else{
  4150. winLogIoerr(cnt);
  4151. }
  4152. sqlite3_free(zConverted);
  4153. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  4154. return rc;
  4155. }
  4156. /*
  4157. ** Check the existence and status of a file.
  4158. */
  4159. static int winAccess(
  4160. sqlite3_vfs *pVfs, /* Not used on win32 */
  4161. const char *zFilename, /* Name of file to check */
  4162. int flags, /* Type of test to make on this file */
  4163. int *pResOut /* OUT: Result */
  4164. ){
  4165. DWORD attr;
  4166. int rc = 0;
  4167. DWORD lastErrno;
  4168. void *zConverted;
  4169. UNUSED_PARAMETER(pVfs);
  4170. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  4171. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  4172. zFilename, flags, pResOut));
  4173. zConverted = winConvertFromUtf8Filename(zFilename);
  4174. if( zConverted==0 ){
  4175. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  4176. return SQLITE_IOERR_NOMEM;
  4177. }
  4178. if( osIsNT() ){
  4179. int cnt = 0;
  4180. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  4181. memset(&sAttrData, 0, sizeof(sAttrData));
  4182. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  4183. GetFileExInfoStandard,
  4184. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  4185. if( rc ){
  4186. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  4187. ** as if it does not exist.
  4188. */
  4189. if( flags==SQLITE_ACCESS_EXISTS
  4190. && sAttrData.nFileSizeHigh==0
  4191. && sAttrData.nFileSizeLow==0 ){
  4192. attr = INVALID_FILE_ATTRIBUTES;
  4193. }else{
  4194. attr = sAttrData.dwFileAttributes;
  4195. }
  4196. }else{
  4197. winLogIoerr(cnt);
  4198. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  4199. sqlite3_free(zConverted);
  4200. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  4201. zFilename);
  4202. }else{
  4203. attr = INVALID_FILE_ATTRIBUTES;
  4204. }
  4205. }
  4206. }
  4207. #ifdef SQLITE_WIN32_HAS_ANSI
  4208. else{
  4209. attr = osGetFileAttributesA((char*)zConverted);
  4210. }
  4211. #endif
  4212. sqlite3_free(zConverted);
  4213. switch( flags ){
  4214. case SQLITE_ACCESS_READ:
  4215. case SQLITE_ACCESS_EXISTS:
  4216. rc = attr!=INVALID_FILE_ATTRIBUTES;
  4217. break;
  4218. case SQLITE_ACCESS_READWRITE:
  4219. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  4220. (attr & FILE_ATTRIBUTE_READONLY)==0;
  4221. break;
  4222. default:
  4223. assert(!"Invalid flags argument");
  4224. }
  4225. *pResOut = rc;
  4226. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  4227. zFilename, pResOut, *pResOut));
  4228. return SQLITE_OK;
  4229. }
  4230. /*
  4231. ** Returns non-zero if the specified path name starts with a drive letter
  4232. ** followed by a colon character.
  4233. */
  4234. static BOOL winIsDriveLetterAndColon(
  4235. const char *zPathname
  4236. ){
  4237. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  4238. }
  4239. /*
  4240. ** Returns non-zero if the specified path name should be used verbatim. If
  4241. ** non-zero is returned from this function, the calling function must simply
  4242. ** use the provided path name verbatim -OR- resolve it into a full path name
  4243. ** using the GetFullPathName Win32 API function (if available).
  4244. */
  4245. static BOOL winIsVerbatimPathname(
  4246. const char *zPathname
  4247. ){
  4248. /*
  4249. ** If the path name starts with a forward slash or a backslash, it is either
  4250. ** a legal UNC name, a volume relative path, or an absolute path name in the
  4251. ** "Unix" format on Windows. There is no easy way to differentiate between
  4252. ** the final two cases; therefore, we return the safer return value of TRUE
  4253. ** so that callers of this function will simply use it verbatim.
  4254. */
  4255. if ( winIsDirSep(zPathname[0]) ){
  4256. return TRUE;
  4257. }
  4258. /*
  4259. ** If the path name starts with a letter and a colon it is either a volume
  4260. ** relative path or an absolute path. Callers of this function must not
  4261. ** attempt to treat it as a relative path name (i.e. they should simply use
  4262. ** it verbatim).
  4263. */
  4264. if ( winIsDriveLetterAndColon(zPathname) ){
  4265. return TRUE;
  4266. }
  4267. /*
  4268. ** If we get to this point, the path name should almost certainly be a purely
  4269. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  4270. */
  4271. return FALSE;
  4272. }
  4273. /*
  4274. ** Turn a relative pathname into a full pathname. Write the full
  4275. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  4276. ** bytes in size.
  4277. */
  4278. static int winFullPathname(
  4279. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  4280. const char *zRelative, /* Possibly relative input path */
  4281. int nFull, /* Size of output buffer in bytes */
  4282. char *zFull /* Output buffer */
  4283. ){
  4284. #if defined(__CYGWIN__)
  4285. SimulateIOError( return SQLITE_ERROR );
  4286. UNUSED_PARAMETER(nFull);
  4287. assert( nFull>=pVfs->mxPathname );
  4288. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  4289. /*
  4290. ** NOTE: We are dealing with a relative path name and the data
  4291. ** directory has been set. Therefore, use it as the basis
  4292. ** for converting the relative path name to an absolute
  4293. ** one by prepending the data directory and a slash.
  4294. */
  4295. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  4296. if( !zOut ){
  4297. return SQLITE_IOERR_NOMEM;
  4298. }
  4299. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  4300. pVfs->mxPathname+1)<0 ){
  4301. sqlite3_free(zOut);
  4302. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  4303. "winFullPathname1", zRelative);
  4304. }
  4305. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  4306. sqlite3_data_directory, winGetDirDep(), zOut);
  4307. sqlite3_free(zOut);
  4308. }else{
  4309. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
  4310. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  4311. "winFullPathname2", zRelative);
  4312. }
  4313. }
  4314. return SQLITE_OK;
  4315. #endif
  4316. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  4317. SimulateIOError( return SQLITE_ERROR );
  4318. /* WinCE has no concept of a relative pathname, or so I am told. */
  4319. /* WinRT has no way to convert a relative path to an absolute one. */
  4320. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  4321. /*
  4322. ** NOTE: We are dealing with a relative path name and the data
  4323. ** directory has been set. Therefore, use it as the basis
  4324. ** for converting the relative path name to an absolute
  4325. ** one by prepending the data directory and a backslash.
  4326. */
  4327. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  4328. sqlite3_data_directory, winGetDirDep(), zRelative);
  4329. }else{
  4330. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  4331. }
  4332. return SQLITE_OK;
  4333. #endif
  4334. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  4335. DWORD nByte;
  4336. void *zConverted;
  4337. char *zOut;
  4338. /* If this path name begins with "/X:", where "X" is any alphabetic
  4339. ** character, discard the initial "/" from the pathname.
  4340. */
  4341. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  4342. zRelative++;
  4343. }
  4344. /* It's odd to simulate an io-error here, but really this is just
  4345. ** using the io-error infrastructure to test that SQLite handles this
  4346. ** function failing. This function could fail if, for example, the
  4347. ** current working directory has been unlinked.
  4348. */
  4349. SimulateIOError( return SQLITE_ERROR );
  4350. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  4351. /*
  4352. ** NOTE: We are dealing with a relative path name and the data
  4353. ** directory has been set. Therefore, use it as the basis
  4354. ** for converting the relative path name to an absolute
  4355. ** one by prepending the data directory and a backslash.
  4356. */
  4357. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  4358. sqlite3_data_directory, winGetDirDep(), zRelative);
  4359. return SQLITE_OK;
  4360. }
  4361. zConverted = winConvertFromUtf8Filename(zRelative);
  4362. if( zConverted==0 ){
  4363. return SQLITE_IOERR_NOMEM;
  4364. }
  4365. if( osIsNT() ){
  4366. LPWSTR zTemp;
  4367. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  4368. if( nByte==0 ){
  4369. sqlite3_free(zConverted);
  4370. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  4371. "winFullPathname1", zRelative);
  4372. }
  4373. nByte += 3;
  4374. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  4375. if( zTemp==0 ){
  4376. sqlite3_free(zConverted);
  4377. return SQLITE_IOERR_NOMEM;
  4378. }
  4379. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  4380. if( nByte==0 ){
  4381. sqlite3_free(zConverted);
  4382. sqlite3_free(zTemp);
  4383. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  4384. "winFullPathname2", zRelative);
  4385. }
  4386. sqlite3_free(zConverted);
  4387. zOut = winUnicodeToUtf8(zTemp);
  4388. sqlite3_free(zTemp);
  4389. }
  4390. #ifdef SQLITE_WIN32_HAS_ANSI
  4391. else{
  4392. char *zTemp;
  4393. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  4394. if( nByte==0 ){
  4395. sqlite3_free(zConverted);
  4396. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  4397. "winFullPathname3", zRelative);
  4398. }
  4399. nByte += 3;
  4400. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  4401. if( zTemp==0 ){
  4402. sqlite3_free(zConverted);
  4403. return SQLITE_IOERR_NOMEM;
  4404. }
  4405. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  4406. if( nByte==0 ){
  4407. sqlite3_free(zConverted);
  4408. sqlite3_free(zTemp);
  4409. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  4410. "winFullPathname4", zRelative);
  4411. }
  4412. sqlite3_free(zConverted);
  4413. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  4414. sqlite3_free(zTemp);
  4415. }
  4416. #endif
  4417. if( zOut ){
  4418. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  4419. sqlite3_free(zOut);
  4420. return SQLITE_OK;
  4421. }else{
  4422. return SQLITE_IOERR_NOMEM;
  4423. }
  4424. #endif
  4425. }
  4426. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  4427. /*
  4428. ** Interfaces for opening a shared library, finding entry points
  4429. ** within the shared library, and closing the shared library.
  4430. */
  4431. /*
  4432. ** Interfaces for opening a shared library, finding entry points
  4433. ** within the shared library, and closing the shared library.
  4434. */
  4435. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  4436. HANDLE h;
  4437. void *zConverted = winConvertFromUtf8Filename(zFilename);
  4438. UNUSED_PARAMETER(pVfs);
  4439. if( zConverted==0 ){
  4440. return 0;
  4441. }
  4442. if( osIsNT() ){
  4443. #if SQLITE_OS_WINRT
  4444. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  4445. #else
  4446. h = osLoadLibraryW((LPCWSTR)zConverted);
  4447. #endif
  4448. }
  4449. #ifdef SQLITE_WIN32_HAS_ANSI
  4450. else{
  4451. h = osLoadLibraryA((char*)zConverted);
  4452. }
  4453. #endif
  4454. sqlite3_free(zConverted);
  4455. return (void*)h;
  4456. }
  4457. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  4458. UNUSED_PARAMETER(pVfs);
  4459. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  4460. }
  4461. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  4462. UNUSED_PARAMETER(pVfs);
  4463. return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
  4464. }
  4465. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  4466. UNUSED_PARAMETER(pVfs);
  4467. osFreeLibrary((HANDLE)pHandle);
  4468. }
  4469. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  4470. #define winDlOpen 0
  4471. #define winDlError 0
  4472. #define winDlSym 0
  4473. #define winDlClose 0
  4474. #endif
  4475. /*
  4476. ** Write up to nBuf bytes of randomness into zBuf.
  4477. */
  4478. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  4479. int n = 0;
  4480. UNUSED_PARAMETER(pVfs);
  4481. #if defined(SQLITE_TEST)
  4482. n = nBuf;
  4483. memset(zBuf, 0, nBuf);
  4484. #else
  4485. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  4486. SYSTEMTIME x;
  4487. osGetSystemTime(&x);
  4488. memcpy(&zBuf[n], &x, sizeof(x));
  4489. n += sizeof(x);
  4490. }
  4491. if( sizeof(DWORD)<=nBuf-n ){
  4492. DWORD pid = osGetCurrentProcessId();
  4493. memcpy(&zBuf[n], &pid, sizeof(pid));
  4494. n += sizeof(pid);
  4495. }
  4496. #if SQLITE_OS_WINRT
  4497. if( sizeof(ULONGLONG)<=nBuf-n ){
  4498. ULONGLONG cnt = osGetTickCount64();
  4499. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  4500. n += sizeof(cnt);
  4501. }
  4502. #else
  4503. if( sizeof(DWORD)<=nBuf-n ){
  4504. DWORD cnt = osGetTickCount();
  4505. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  4506. n += sizeof(cnt);
  4507. }
  4508. #endif
  4509. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  4510. LARGE_INTEGER i;
  4511. osQueryPerformanceCounter(&i);
  4512. memcpy(&zBuf[n], &i, sizeof(i));
  4513. n += sizeof(i);
  4514. }
  4515. #endif
  4516. return n;
  4517. }
  4518. /*
  4519. ** Sleep for a little while. Return the amount of time slept.
  4520. */
  4521. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  4522. sqlite3_win32_sleep((microsec+999)/1000);
  4523. UNUSED_PARAMETER(pVfs);
  4524. return ((microsec+999)/1000)*1000;
  4525. }
  4526. /*
  4527. ** The following variable, if set to a non-zero value, is interpreted as
  4528. ** the number of seconds since 1970 and is used to set the result of
  4529. ** sqlite3OsCurrentTime() during testing.
  4530. */
  4531. #ifdef SQLITE_TEST
  4532. int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  4533. #endif
  4534. /*
  4535. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  4536. ** the current time and date as a Julian Day number times 86_400_000. In
  4537. ** other words, write into *piNow the number of milliseconds since the Julian
  4538. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  4539. ** proleptic Gregorian calendar.
  4540. **
  4541. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  4542. ** cannot be found.
  4543. */
  4544. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  4545. /* FILETIME structure is a 64-bit value representing the number of
  4546. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  4547. */
  4548. FILETIME ft;
  4549. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  4550. #ifdef SQLITE_TEST
  4551. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  4552. #endif
  4553. /* 2^32 - to avoid use of LL and warnings in gcc */
  4554. static const sqlite3_int64 max32BitValue =
  4555. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  4556. (sqlite3_int64)294967296;
  4557. #if SQLITE_OS_WINCE
  4558. SYSTEMTIME time;
  4559. osGetSystemTime(&time);
  4560. /* if SystemTimeToFileTime() fails, it returns zero. */
  4561. if (!osSystemTimeToFileTime(&time,&ft)){
  4562. return SQLITE_ERROR;
  4563. }
  4564. #else
  4565. osGetSystemTimeAsFileTime( &ft );
  4566. #endif
  4567. *piNow = winFiletimeEpoch +
  4568. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  4569. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  4570. #ifdef SQLITE_TEST
  4571. if( sqlite3_current_time ){
  4572. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  4573. }
  4574. #endif
  4575. UNUSED_PARAMETER(pVfs);
  4576. return SQLITE_OK;
  4577. }
  4578. /*
  4579. ** Find the current time (in Universal Coordinated Time). Write the
  4580. ** current time and date as a Julian Day number into *prNow and
  4581. ** return 0. Return 1 if the time and date cannot be found.
  4582. */
  4583. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  4584. int rc;
  4585. sqlite3_int64 i;
  4586. rc = winCurrentTimeInt64(pVfs, &i);
  4587. if( !rc ){
  4588. *prNow = i/86400000.0;
  4589. }
  4590. return rc;
  4591. }
  4592. /*
  4593. ** The idea is that this function works like a combination of
  4594. ** GetLastError() and FormatMessage() on Windows (or errno and
  4595. ** strerror_r() on Unix). After an error is returned by an OS
  4596. ** function, SQLite calls this function with zBuf pointing to
  4597. ** a buffer of nBuf bytes. The OS layer should populate the
  4598. ** buffer with a nul-terminated UTF-8 encoded error message
  4599. ** describing the last IO error to have occurred within the calling
  4600. ** thread.
  4601. **
  4602. ** If the error message is too large for the supplied buffer,
  4603. ** it should be truncated. The return value of xGetLastError
  4604. ** is zero if the error message fits in the buffer, or non-zero
  4605. ** otherwise (if the message was truncated). If non-zero is returned,
  4606. ** then it is not necessary to include the nul-terminator character
  4607. ** in the output buffer.
  4608. **
  4609. ** Not supplying an error message will have no adverse effect
  4610. ** on SQLite. It is fine to have an implementation that never
  4611. ** returns an error message:
  4612. **
  4613. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  4614. ** assert(zBuf[0]=='\0');
  4615. ** return 0;
  4616. ** }
  4617. **
  4618. ** However if an error message is supplied, it will be incorporated
  4619. ** by sqlite into the error message available to the user using
  4620. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  4621. */
  4622. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  4623. UNUSED_PARAMETER(pVfs);
  4624. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  4625. }
  4626. /*
  4627. ** Initialize and deinitialize the operating system interface.
  4628. */
  4629. int sqlite3_os_init(void){
  4630. static sqlite3_vfs winVfs = {
  4631. 3, /* iVersion */
  4632. sizeof(winFile), /* szOsFile */
  4633. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  4634. 0, /* pNext */
  4635. "win32", /* zName */
  4636. 0, /* pAppData */
  4637. winOpen, /* xOpen */
  4638. winDelete, /* xDelete */
  4639. winAccess, /* xAccess */
  4640. winFullPathname, /* xFullPathname */
  4641. winDlOpen, /* xDlOpen */
  4642. winDlError, /* xDlError */
  4643. winDlSym, /* xDlSym */
  4644. winDlClose, /* xDlClose */
  4645. winRandomness, /* xRandomness */
  4646. winSleep, /* xSleep */
  4647. winCurrentTime, /* xCurrentTime */
  4648. winGetLastError, /* xGetLastError */
  4649. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  4650. winSetSystemCall, /* xSetSystemCall */
  4651. winGetSystemCall, /* xGetSystemCall */
  4652. winNextSystemCall, /* xNextSystemCall */
  4653. };
  4654. #if defined(SQLITE_WIN32_HAS_WIDE)
  4655. static sqlite3_vfs winLongPathVfs = {
  4656. 3, /* iVersion */
  4657. sizeof(winFile), /* szOsFile */
  4658. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  4659. 0, /* pNext */
  4660. "win32-longpath", /* zName */
  4661. 0, /* pAppData */
  4662. winOpen, /* xOpen */
  4663. winDelete, /* xDelete */
  4664. winAccess, /* xAccess */
  4665. winFullPathname, /* xFullPathname */
  4666. winDlOpen, /* xDlOpen */
  4667. winDlError, /* xDlError */
  4668. winDlSym, /* xDlSym */
  4669. winDlClose, /* xDlClose */
  4670. winRandomness, /* xRandomness */
  4671. winSleep, /* xSleep */
  4672. winCurrentTime, /* xCurrentTime */
  4673. winGetLastError, /* xGetLastError */
  4674. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  4675. winSetSystemCall, /* xSetSystemCall */
  4676. winGetSystemCall, /* xGetSystemCall */
  4677. winNextSystemCall, /* xNextSystemCall */
  4678. };
  4679. #endif
  4680. /* Double-check that the aSyscall[] array has been constructed
  4681. ** correctly. See ticket [bb3a86e890c8e96ab] */
  4682. assert( ArraySize(aSyscall)==75 );
  4683. /* get memory map allocation granularity */
  4684. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  4685. #if SQLITE_OS_WINRT
  4686. osGetNativeSystemInfo(&winSysInfo);
  4687. #else
  4688. osGetSystemInfo(&winSysInfo);
  4689. #endif
  4690. assert( winSysInfo.dwAllocationGranularity>0 );
  4691. assert( winSysInfo.dwPageSize>0 );
  4692. sqlite3_vfs_register(&winVfs, 1);
  4693. #if defined(SQLITE_WIN32_HAS_WIDE)
  4694. sqlite3_vfs_register(&winLongPathVfs, 0);
  4695. #endif
  4696. return SQLITE_OK;
  4697. }
  4698. int sqlite3_os_end(void){
  4699. #if SQLITE_OS_WINRT
  4700. if( sleepObj!=NULL ){
  4701. osCloseHandle(sleepObj);
  4702. sleepObj = NULL;
  4703. }
  4704. #endif
  4705. return SQLITE_OK;
  4706. }
  4707. #endif /* SQLITE_OS_WIN */