Platform.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652
  1. #define INITKNOWNFOLDERS
  2. #include <guiddef.h>
  3. #include <KnownFolders.h>
  4. #undef INITKNOWNFOLDERS
  5. #pragma warning(disable:4065)
  6. #pragma warning(disable:4996)
  7. #include "Common.h"
  8. #ifndef BF_NO_BFAPP
  9. #include "BFApp.h"
  10. #endif
  11. #include <mmsystem.h>
  12. #include <shellapi.h>
  13. #include <Objbase.h>
  14. #include <signal.h>
  15. #include <ntsecapi.h> // UNICODE_STRING
  16. #include <psapi.h>
  17. #include <shlobj.h>
  18. #include "../PlatformInterface.h"
  19. #include "../PlatformHelper.h"
  20. #include "CrashCatcher.h"
  21. #include "../util/CritSect.h"
  22. #include "../util/Dictionary.h"
  23. #include "../util/HashSet.h"
  24. #include "../../third_party/putty/wildcard.h"
  25. #include "util/AllocDebug.h"
  26. #pragma comment(lib, "ole32.lib")
  27. #pragma comment(lib, "shell32.lib")
  28. #pragma comment(lib, "user32.lib")
  29. #pragma comment(lib, "gdi32.lib")
  30. #pragma comment(lib, "rpcrt4.lib")
  31. #define NOT_IMPL BF_FATAL("Not implemented")
  32. USING_NS_BF;
  33. static bool gTimerInitialized = false;
  34. static int gTimerDivisor = 0;
  35. CritSect gBfpCritSect;
  36. struct WindowsSharedInfo
  37. {
  38. int mThreadAcc;
  39. uint32 mTickStart;
  40. };
  41. static WindowsSharedInfo* gGlobalPlatformInfo = NULL;
  42. static HANDLE gGlobalMutex = 0;
  43. #define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
  44. typedef LONG KPRIORITY;
  45. enum SYSTEM_INFORMATION_CLASS
  46. {
  47. SystemProcessInformation = 5
  48. }; // SYSTEM_INFORMATION_CLASS
  49. struct CLIENT_ID
  50. {
  51. HANDLE UniqueProcess;
  52. HANDLE UniqueThread;
  53. }; // struct CLIENT_ID
  54. enum THREAD_STATE
  55. {
  56. StateInitialized,
  57. StateReady,
  58. StateRunning,
  59. StateStandby,
  60. StateTerminated,
  61. StateWait,
  62. StateTransition,
  63. StateUnknown
  64. };
  65. struct VM_COUNTERS
  66. {
  67. SIZE_T PeakVirtualSize;
  68. SIZE_T VirtualSize;
  69. ULONG PageFaultCount;
  70. SIZE_T PeakWorkingSetSize;
  71. SIZE_T WorkingSetSize;
  72. SIZE_T QuotaPeakPagedPoolUsage;
  73. SIZE_T QuotaPagedPoolUsage;
  74. SIZE_T QuotaPeakNonPagedPoolUsage;
  75. SIZE_T QuotaNonPagedPoolUsage;
  76. SIZE_T PagefileUsage;
  77. SIZE_T PeakPagefileUsage;
  78. SIZE_T PrivatePageCount;
  79. };
  80. struct SYSTEM_THREAD {
  81. LARGE_INTEGER KernelTime;
  82. LARGE_INTEGER UserTime;
  83. LARGE_INTEGER CreateTime;
  84. ULONG WaitTime;
  85. LPVOID StartAddress;
  86. CLIENT_ID ClientId;
  87. DWORD Priority;
  88. LONG BasePriority;
  89. ULONG ContextSwitchCount;
  90. THREAD_STATE State;
  91. ULONG WaitReason;
  92. };
  93. struct SYSTEM_PROCESS_INFORMATION
  94. {
  95. ULONG NextEntryOffset;
  96. ULONG NumberOfThreads;
  97. LARGE_INTEGER Reserved[3];
  98. LARGE_INTEGER CreateTime;
  99. LARGE_INTEGER UserTime;
  100. LARGE_INTEGER KernelTime;
  101. UNICODE_STRING ImageName;
  102. KPRIORITY BasePriority;
  103. HANDLE ProcessId;
  104. HANDLE InheritedFromProcessId;
  105. ULONG HandleCount;
  106. ULONG Reserved2[2];
  107. ULONG PrivatePageCount;
  108. VM_COUNTERS VirtualMemoryCounters;
  109. IO_COUNTERS IoCounters;
  110. SYSTEM_THREAD Threads[1];
  111. };
  112. class BfpManager
  113. {
  114. public:
  115. BfpManager* mNext;
  116. BfpManager()
  117. {
  118. mNext = NULL;
  119. }
  120. virtual ~BfpManager()
  121. {
  122. }
  123. };
  124. BfpManager* gManagerTail;
  125. static void BfpRecordManager(BfpManager* manager)
  126. {
  127. AutoCrit autoCrit(gBfpCritSect);
  128. manager->mNext = gManagerTail;
  129. gManagerTail = manager;
  130. }
  131. typedef NTSTATUS(NTAPI* NtQuerySystemInformation_t)(SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG);
  132. static NtQuerySystemInformation_t gNtQuerySystemInformation = NULL;
  133. static HMODULE gNTDll = NULL;
  134. static void ImportNTDll()
  135. {
  136. if (gNTDll != NULL)
  137. return;
  138. WCHAR path[MAX_PATH];
  139. GetSystemDirectory(path, MAX_PATH);
  140. wcscat(path, L"\\ntdll.dll");
  141. gNTDll = GetModuleHandle(path);
  142. if (gNTDll == NULL)
  143. {
  144. return;
  145. }
  146. gNtQuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(gNTDll, "NtQuerySystemInformation");
  147. }
  148. typedef HRESULT(WINAPI* SetThreadDescription_t)(HANDLE hThread, PCWSTR lpThreadDescription);
  149. typedef HRESULT(WINAPI* GetThreadDescription_t)(HANDLE hThread, PWSTR* lpThreadDescription);
  150. static SetThreadDescription_t gSetThreadDescription = NULL;
  151. static GetThreadDescription_t gGetThreadDescription = NULL;
  152. static HMODULE gKernelDll = NULL;
  153. static void ImportKernel()
  154. {
  155. if (gKernelDll != NULL)
  156. return;
  157. WCHAR path[MAX_PATH];
  158. GetSystemDirectory(path, MAX_PATH);
  159. wcscat(path, L"\\kernel32.dll");
  160. gKernelDll = GetModuleHandle(path);
  161. if (gKernelDll == NULL)
  162. {
  163. return;
  164. }
  165. gSetThreadDescription = (SetThreadDescription_t)GetProcAddress(gKernelDll, "SetThreadDescription");
  166. gGetThreadDescription = (GetThreadDescription_t)GetProcAddress(gKernelDll, "GetThreadDescription");
  167. }
  168. #ifdef BF_MINGW
  169. #define timeGetTime GetTickCount
  170. #endif
  171. static bool IsHandleValid(HANDLE handle)
  172. {
  173. return (handle != NULL) && (handle != INVALID_HANDLE_VALUE);
  174. }
  175. WindowsSharedInfo* GetSharedInfo()
  176. {
  177. if (gGlobalPlatformInfo != NULL)
  178. return gGlobalPlatformInfo;
  179. String sharedName = StrFormat("BfpSharedInfo_%d", GetCurrentProcessId());
  180. bool created = false;
  181. HANDLE sharedFileMapping = ::OpenFileMappingA(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, sharedName.c_str());
  182. if (sharedFileMapping == NULL)
  183. {
  184. sharedFileMapping = ::CreateFileMappingA(
  185. INVALID_HANDLE_VALUE,
  186. NULL,
  187. PAGE_READWRITE,
  188. 0,
  189. sizeof(WindowsSharedInfo),
  190. sharedName.c_str());
  191. created = true;
  192. }
  193. BF_ASSERT(sharedFileMapping != NULL);
  194. gGlobalPlatformInfo = (WindowsSharedInfo*)MapViewOfFile(sharedFileMapping,
  195. FILE_MAP_READ | FILE_MAP_WRITE,
  196. 0,
  197. 0,
  198. sizeof(WindowsSharedInfo));
  199. if (created)
  200. {
  201. memset(gGlobalPlatformInfo, 0, sizeof(WindowsSharedInfo));
  202. gGlobalPlatformInfo->mTickStart = timeGetTime();
  203. }
  204. timeBeginPeriod(1);
  205. return gGlobalPlatformInfo;
  206. }
  207. uint32 Beefy::BFTickCount()
  208. {
  209. return timeGetTime() - GetSharedInfo()->mTickStart;
  210. }
  211. /*#ifdef BF_MINGW
  212. uint64 __rdtsc( )
  213. {
  214. #if defined i386
  215. long long a;
  216. asm volatile("rdtsc":"=A" (a));
  217. return a;
  218. #elif defined __x86_64
  219. unsigned int _hi,_lo;
  220. asm volatile("rdtsc":"=a"(_lo),"=d"(_hi));
  221. return ((unsigned long long int)_hi << 32) | _lo;
  222. #endif
  223. }
  224. #endif*/
  225. #ifdef BF_MINGW
  226. #define ALL_PROCESSOR_GROUPS 0xffff
  227. WINBASEAPI DWORD WINAPI GetActiveProcessorCount(WORD GroupNumber);
  228. #endif
  229. static int IntCompare(const void* a, const void* b)
  230. {
  231. return *(int*)a - *(int*)b;
  232. }
  233. uint64 Beefy::BFGetTickCountMicroFast()
  234. {
  235. if (!gTimerInitialized)
  236. {
  237. WindowsSharedInfo* windowsSharedInfo = GetSharedInfo();
  238. windowsSharedInfo->mThreadAcc++;
  239. #ifdef BF_MINGW
  240. //TODO: Fix (needs new libkernel32.a)
  241. int processorCount = 4;
  242. #else
  243. int processorCount = (int) ::GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  244. #endif
  245. ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  246. ::SetThreadAffinityMask(::GetCurrentThread(), (int64)1 << (windowsSharedInfo->mThreadAcc % processorCount));
  247. uint64 deltaMicro = 0;
  248. uint64 startMicroA = __rdtsc();
  249. uint32 outStartMS = timeGetTime();
  250. int timingSet[30];
  251. uint32 prevQPFMicro = 0;
  252. LARGE_INTEGER frequency = { 0, 1 };
  253. QueryPerformanceFrequency(&frequency);
  254. uint64 startMicro = __rdtsc();
  255. for (int i = 0; i < BF_ARRAY_COUNT(timingSet); i++)
  256. {
  257. uint32 qPFMicro;
  258. do
  259. {
  260. LARGE_INTEGER timeNow;
  261. QueryPerformanceCounter(&timeNow);
  262. qPFMicro = (uint32)((timeNow.QuadPart * 100000000) / frequency.QuadPart);
  263. } while (qPFMicro - prevQPFMicro < 100000);
  264. prevQPFMicro = qPFMicro;
  265. int64 curMicro = __rdtsc();
  266. int aDivisor = (int)(curMicro - startMicro);
  267. startMicro = curMicro;
  268. timingSet[i] = aDivisor;
  269. }
  270. qsort(timingSet, BF_ARRAY_COUNT(timingSet), sizeof(timingSet[0]), IntCompare);
  271. gTimerDivisor = timingSet[BF_ARRAY_COUNT(timingSet) / 3];
  272. //gTimerDivisor = *gTimingSet.rbegin();
  273. OutputDebugStrF("BFGetTickCountMicro divisor: %d\n", gTimerDivisor);
  274. ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  275. uint32 outEndMS = timeGetTime();
  276. uint64 endMicroA = __rdtsc();
  277. // It's possible we can run this test in multiple threads at once, we could wrap a CritSect around it but
  278. // at least this fence will avoid the case where we have a zero gTimerDivisor
  279. BF_FULL_MEMORY_FENCE();
  280. gTimerInitialized = true;
  281. }
  282. uint64 clock = __rdtsc();
  283. return (clock * 1000) / gTimerDivisor;
  284. }
  285. uint64 Beefy::BFGetTickCountMicro()
  286. {
  287. static LARGE_INTEGER freq;
  288. static UINT64 startTime;
  289. UINT64 curTime;
  290. LARGE_INTEGER value;
  291. if (!freq.QuadPart)
  292. {
  293. if (!QueryPerformanceFrequency(&freq))
  294. {
  295. ULARGE_INTEGER fileTime;
  296. GetSystemTimeAsFileTime((FILETIME*)&fileTime);
  297. return fileTime.QuadPart / 10;
  298. }
  299. QueryPerformanceCounter(&value);
  300. startTime = value.QuadPart;
  301. }
  302. QueryPerformanceCounter(&value);
  303. curTime = value.QuadPart;
  304. return (int64)((curTime - startTime) * (double)1000000 / freq.QuadPart);
  305. }
  306. static uint64 WinConvertFILETIME(const FILETIME& ft)
  307. {
  308. LONGLONG ll = (int64)ft.dwHighDateTime << 32;
  309. ll = ll + ft.dwLowDateTime - 116444736000000000;
  310. return (uint64)(ll / 10000000);
  311. }
  312. int64 Beefy::GetFileTimeWrite(const StringImpl& path)
  313. {
  314. WIN32_FILE_ATTRIBUTE_DATA data;
  315. if (GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &data))
  316. return (int64)WinConvertFILETIME(data.ftLastWriteTime);
  317. else
  318. return 0;
  319. }
  320. bool Beefy::FileExists(const StringImpl& path, String* outActualName)
  321. {
  322. WIN32_FIND_DATAW findData;
  323. HANDLE handleVal = FindFirstFileW(UTF8Decode(path).c_str(), &findData);
  324. if (handleVal == INVALID_HANDLE_VALUE)
  325. return false;
  326. FindClose(handleVal);
  327. if (outActualName != NULL)
  328. *outActualName = UTF8Encode(findData.cFileName);
  329. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
  330. }
  331. bool Beefy::DirectoryExists(const StringImpl& path, String* outActualName)
  332. {
  333. WIN32_FIND_DATAW findData;
  334. HANDLE handleVal = FindFirstFileW(UTF8Decode(path).c_str(), &findData);
  335. if (handleVal == INVALID_HANDLE_VALUE)
  336. return false;
  337. FindClose(handleVal);
  338. if (outActualName != NULL)
  339. *outActualName = UTF8Encode(findData.cFileName);
  340. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  341. }
  342. void Beefy::BFFatalError(const StringImpl& message, const StringImpl& file, int line)
  343. {
  344. #ifndef BF_NO_BFAPP
  345. if (gBFApp != NULL)
  346. gBFApp->mSysDialogCnt++;
  347. #endif
  348. String failMsg = StrFormat("%s in %s:%d", message.c_str(), file.c_str(), line);
  349. BfpSystem_FatalError(failMsg.c_str(), "FATAL ERROR");
  350. #ifndef BF_NO_BFAPP
  351. if (gBFApp != NULL)
  352. gBFApp->mSysDialogCnt--;
  353. #endif
  354. }
  355. //////////////////////////////////////////////////
  356. static bool GetFileInfo(const char* path, BfpTimeStamp* lastWriteTime, uint32* fileAttributes)
  357. {
  358. if (lastWriteTime != NULL)
  359. *lastWriteTime = 0;
  360. if (fileAttributes != NULL)
  361. *fileAttributes = 0;
  362. // Fast Path
  363. WIN32_FILE_ATTRIBUTE_DATA data = { 0 };
  364. if (::GetFileAttributesExW(UTF8Decode(path).c_str(), GetFileExInfoStandard, &data))
  365. {
  366. if (lastWriteTime != NULL)
  367. *lastWriteTime = *(BfpTimeStamp*)&data.ftLastWriteTime;
  368. if (fileAttributes != NULL)
  369. *fileAttributes = data.dwFileAttributes;
  370. return true;
  371. }
  372. int error = ::GetLastError();
  373. if ((error == ERROR_FILE_NOT_FOUND) ||
  374. (error == ERROR_PATH_NOT_FOUND) ||
  375. (error == ERROR_NOT_READY))
  376. {
  377. return false;
  378. }
  379. // Slow Path- This case is in case someone latched onto the file. In this case, GetFileAttributes will fail but
  380. // FindFirstFile will not (though it is slower)
  381. WIN32_FIND_DATAW findData = { 0 };
  382. HANDLE findHandleFrom = ::FindFirstFileW(UTF8Decode(path).c_str(), &findData);
  383. if (!IsHandleValid(findHandleFrom))
  384. return false;
  385. if (lastWriteTime != NULL)
  386. *lastWriteTime = *(BfpTimeStamp*)&findData.ftLastWriteTime;
  387. if (fileAttributes != NULL)
  388. *fileAttributes = findData.dwFileAttributes;
  389. ::FindClose(findHandleFrom);
  390. return true;
  391. }
  392. static BfpFileAttributes FileAttributes_WinToBFP(uint32 fileAttributes)
  393. {
  394. BfpFileAttributes attrs = BfpFileAttribute_None;
  395. if ((fileAttributes & FILE_ATTRIBUTE_NORMAL) != 0)
  396. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Normal);
  397. if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  398. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Directory);
  399. if ((fileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
  400. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Hidden);
  401. if ((fileAttributes & FILE_ATTRIBUTE_SYSTEM) != 0)
  402. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_System);
  403. if ((fileAttributes & FILE_ATTRIBUTE_TEMPORARY) != 0)
  404. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Temporary);
  405. if ((fileAttributes & FILE_ATTRIBUTE_OFFLINE) != 0)
  406. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Offline);
  407. if ((fileAttributes & FILE_ATTRIBUTE_ENCRYPTED) != 0)
  408. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Encrypted);
  409. if ((fileAttributes & FILE_ATTRIBUTE_ARCHIVE) != 0)
  410. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_Archive);
  411. if ((fileAttributes & FILE_ATTRIBUTE_READONLY) != 0)
  412. attrs = (BfpFileAttributes)(attrs | BfpFileAttribute_ReadOnly);
  413. return attrs;
  414. }
  415. static uint32 FileAttributes_BFPToWin(BfpFileAttributes fileAttributes)
  416. {
  417. uint32 attributes = 0;
  418. if ((fileAttributes & BfpFileAttribute_ReadOnly) != 0)
  419. attributes |= FILE_ATTRIBUTE_READONLY;
  420. if ((fileAttributes & BfpFileAttribute_Hidden) != 0)
  421. attributes |= FILE_ATTRIBUTE_HIDDEN;
  422. if ((fileAttributes & BfpFileAttribute_System) != 0)
  423. attributes |= FILE_ATTRIBUTE_SYSTEM;
  424. if ((fileAttributes & BfpFileAttribute_Temporary) != 0)
  425. attributes |= FILE_ATTRIBUTE_TEMPORARY;
  426. if ((fileAttributes & BfpFileAttribute_Offline) != 0)
  427. attributes |= FILE_ATTRIBUTE_OFFLINE;
  428. if ((fileAttributes & BfpFileAttribute_Encrypted) != 0)
  429. attributes |= FILE_ATTRIBUTE_ENCRYPTED;
  430. if ((fileAttributes & BfpFileAttribute_Archive) != 0)
  431. attributes |= FILE_ATTRIBUTE_ARCHIVE;
  432. if ((fileAttributes & BfpFileAttribute_Normal) != 0)
  433. attributes |= FILE_ATTRIBUTE_NORMAL;
  434. return attributes;
  435. }
  436. enum BfpOverlappedKind
  437. {
  438. BfpOverlappedKind_FileWatcher,
  439. BfpOverlappedKind_File
  440. };
  441. struct BfpOverlapped
  442. {
  443. BfpOverlappedKind mKind;
  444. volatile HANDLE mHandle;
  445. OVERLAPPED mOverlapped;
  446. virtual ~BfpOverlapped()
  447. {
  448. }
  449. virtual void Completed(int errorCode, int numBytes, OVERLAPPED* overlapped)
  450. {
  451. }
  452. };
  453. struct BfpOverlappedFile : BfpOverlapped
  454. {
  455. Array<uint8> mRecvBuffer;
  456. BfpOverlappedFile()
  457. {
  458. mKind = BfpOverlappedKind_File;
  459. }
  460. };
  461. struct BfpAsyncData
  462. {
  463. HANDLE mEvent;
  464. BfpAsyncData()
  465. {
  466. mEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
  467. }
  468. ~BfpAsyncData()
  469. {
  470. ::CloseHandle(mEvent);
  471. }
  472. void SetEvent()
  473. {
  474. ::SetEvent(mEvent);
  475. }
  476. bool WaitAndResetEvent(int timeoutMS)
  477. {
  478. while (true)
  479. {
  480. auto result = ::WaitForSingleObjectEx(mEvent, (DWORD)timeoutMS, TRUE);
  481. if (result == STATUS_USER_APC)
  482. continue; // Retry
  483. if (result == WAIT_OBJECT_0)
  484. {
  485. ::ResetEvent(mEvent);
  486. return true;
  487. }
  488. return false;
  489. }
  490. }
  491. };
  492. struct BfpFile
  493. {
  494. HANDLE mHandle;
  495. BfpAsyncData* mAsyncData;
  496. bool mIsPipe;
  497. bool mIsStd;
  498. BfpFile(HANDLE handle)
  499. {
  500. mHandle = handle;
  501. mAsyncData = NULL;
  502. mIsPipe = false;
  503. mIsStd = false;
  504. }
  505. BfpFile()
  506. {
  507. mHandle = 0;
  508. mAsyncData = NULL;
  509. mIsPipe = false;
  510. mIsStd = false;
  511. }
  512. ~BfpFile()
  513. {
  514. delete mAsyncData;
  515. }
  516. };
  517. struct BfpFileWatcher : public BfpOverlapped
  518. {
  519. String mPath;
  520. BfpDirectoryChangeFunc mDirectoryChangeFunc;
  521. BfpFileWatcherFlags mFlags;
  522. void* mUserData;
  523. char mBuffer[0x10000];
  524. void Monitor()
  525. {
  526. mOverlapped = { 0 };
  527. DWORD filter = FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY;
  528. DWORD size;
  529. DWORD success = ::ReadDirectoryChangesW(mHandle,
  530. mBuffer, 0x10000,
  531. (mFlags & BfpFileWatcherFlag_IncludeSubdirectories) != 0,
  532. filter,
  533. &size,
  534. &mOverlapped,
  535. NULL);
  536. if (!success)
  537. {
  538. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Failed, mPath.c_str(), NULL, NULL);
  539. }
  540. }
  541. void Restart()
  542. {
  543. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Failed, mPath.c_str(), NULL, NULL);
  544. OutputDebugStrF("Restarting directory monitor for %s\n", mPath.c_str());
  545. Monitor();
  546. }
  547. virtual void Completed(int errorCode, int numBytes, OVERLAPPED* overlapped) override
  548. {
  549. if (errorCode != 0)
  550. {
  551. if (errorCode == 995 /* ERROR_OPERATION_ABORTED */)
  552. {
  553. // Win2000 inside a service the first completion status is false?
  554. // Restart file monitoring?
  555. return;
  556. }
  557. else
  558. {
  559. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Failed, mPath.c_str(), NULL, NULL);
  560. return;
  561. }
  562. }
  563. if (numBytes == 0)
  564. {
  565. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Failed, mPath.c_str(), NULL, NULL);
  566. return;
  567. }
  568. FILE_NOTIFY_INFORMATION* fileNotifyInformation = (FILE_NOTIFY_INFORMATION*)mBuffer;
  569. String oldName;
  570. while (true)
  571. {
  572. String fileName = UTF8Encode(UTF16String(fileNotifyInformation->FileName, fileNotifyInformation->FileNameLength / 2));
  573. if (fileNotifyInformation->Action == FILE_ACTION_RENAMED_OLD_NAME)
  574. oldName = fileName;
  575. else if (fileNotifyInformation->Action == FILE_ACTION_RENAMED_NEW_NAME)
  576. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Renamed, mPath.c_str(), oldName.c_str(), fileName.c_str());
  577. else if (fileNotifyInformation->Action == FILE_ACTION_ADDED)
  578. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Added, mPath.c_str(), fileName.c_str(), NULL);
  579. else if (fileNotifyInformation->Action == FILE_ACTION_REMOVED)
  580. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Removed, mPath.c_str(), fileName.c_str(), NULL);
  581. else if (fileNotifyInformation->Action == FILE_ACTION_MODIFIED)
  582. mDirectoryChangeFunc(this, mUserData, BfpFileChangeKind_Modified, mPath.c_str(), fileName.c_str(), NULL);
  583. if (fileNotifyInformation->NextEntryOffset == 0)
  584. break;
  585. fileNotifyInformation = (FILE_NOTIFY_INFORMATION*)((uint8*)fileNotifyInformation + fileNotifyInformation->NextEntryOffset);
  586. }
  587. Monitor();
  588. }
  589. };
  590. class IOCPManager;
  591. static IOCPManager* gIOCPManager;
  592. class IOCPManager : public BfpManager
  593. {
  594. public:
  595. HANDLE mIOCompletionPort;
  596. Array<HANDLE> mWorkerThreads;
  597. CritSect mCritSect;
  598. bool mShuttingDown;
  599. public:
  600. IOCPManager()
  601. {
  602. mIOCompletionPort = NULL;
  603. mShuttingDown = false;
  604. }
  605. ~IOCPManager()
  606. {
  607. Shutdown();
  608. }
  609. void Shutdown()
  610. {
  611. OutputDebugStrF("IOCP.Shutdown Start\n");
  612. //
  613. {
  614. AutoCrit autoCrit(mCritSect);
  615. if (mShuttingDown)
  616. return;
  617. mShuttingDown = true;
  618. if (!IsHandleValid(mIOCompletionPort))
  619. return;
  620. }
  621. for (int i = 0; i < (int)mWorkerThreads.size(); i++)
  622. ::PostQueuedCompletionStatus(mIOCompletionPort, 0, (ULONG_PTR)1, NULL);
  623. for (int i = 0; i < (int)mWorkerThreads.size(); i++)
  624. {
  625. ::WaitForSingleObject(mWorkerThreads[i], INFINITE);
  626. ::CloseHandle(mWorkerThreads[i]);
  627. }
  628. ::CloseHandle(mIOCompletionPort);
  629. mIOCompletionPort = 0;
  630. OutputDebugStrF("IOCP.Shutdown Done\n");
  631. }
  632. void AddWorkerThread()
  633. {
  634. AutoCrit autoCrit(mCritSect);
  635. if (mShuttingDown)
  636. return;
  637. DWORD threadId;
  638. HANDLE handle = ::CreateThread(NULL, 0, WorkerProcThunk, (void*)this, 0, &threadId);
  639. mWorkerThreads.Add(handle);
  640. }
  641. void EnsureInitialized()
  642. {
  643. AutoCrit autoCrit(mCritSect);
  644. if ((mShuttingDown) || (mIOCompletionPort != NULL))
  645. return;
  646. mIOCompletionPort = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
  647. int workerThreads = 1;
  648. for (int i = 0; i < workerThreads; i++)
  649. AddWorkerThread();
  650. }
  651. void Add(BfpFileWatcher* fileWatcher)
  652. {
  653. //OutputDebugStrF("IOCP.Add %@\n", fileWatcher);
  654. EnsureInitialized();
  655. auto handle = ::CreateIoCompletionPort(fileWatcher->mHandle, mIOCompletionPort, (ULONG_PTR)fileWatcher, 0);
  656. BF_ASSERT(handle == mIOCompletionPort);
  657. }
  658. void Kill(BfpFileWatcher* fileWatcher)
  659. {
  660. //OutputDebugStrF("IOCP.Kill %@\n", fileWatcher);
  661. BF_ASSERT(fileWatcher->mHandle == NULL);
  662. delete fileWatcher;
  663. }
  664. void Remove(BfpOverlapped* bfpOverlapped)
  665. {
  666. /*if (mShuttingDown)
  667. {
  668. Kill(fileWatcher);
  669. return;
  670. } */
  671. //QueueRemove(fileWatcher);
  672. //OutputDebugStrF("IOCP.Remove %@\n", fileWatcher);
  673. AutoCrit autoCrit(mCritSect);
  674. auto handle = bfpOverlapped->mHandle;
  675. bfpOverlapped->mHandle = NULL;
  676. BF_FULL_MEMORY_FENCE();
  677. ::CloseHandle(handle);
  678. ::PostQueuedCompletionStatus(mIOCompletionPort, 0, (ULONG_PTR)bfpOverlapped | 1, NULL);
  679. }
  680. void WorkerProc()
  681. {
  682. while (true)
  683. {
  684. DWORD numBytes;
  685. ULONG_PTR completionKey;
  686. OVERLAPPED* overlapped;
  687. int error = 0;
  688. if (!::GetQueuedCompletionStatus(mIOCompletionPort, &numBytes, &completionKey, &overlapped, INFINITE))
  689. {
  690. error = GetLastError();
  691. if ((error == ERROR_INVALID_HANDLE) || (error == ERROR_ABANDONED_WAIT_0))
  692. break;
  693. continue;
  694. }
  695. int32 keyFlags = (int32)completionKey & 3;
  696. BfpOverlapped* bfpOverlapped = (BfpOverlapped*)(completionKey & ~3);
  697. if (keyFlags == 0) // Normal
  698. {
  699. // Check to see if we have released this
  700. {
  701. AutoCrit autoCrit(mCritSect);
  702. if (bfpOverlapped->mHandle == NULL)
  703. continue;
  704. }
  705. if (numBytes == 0)
  706. {
  707. if (bfpOverlapped->mKind == BfpOverlappedKind_FileWatcher)
  708. {
  709. auto fileWatcher = (BfpFileWatcher*)bfpOverlapped;
  710. if (fileWatcher->mHandle != NULL)
  711. fileWatcher->Restart();
  712. else
  713. Kill(fileWatcher);
  714. }
  715. continue;
  716. }
  717. bfpOverlapped->Completed(error, numBytes, overlapped);
  718. }
  719. else if (keyFlags == 1)
  720. {
  721. if (bfpOverlapped == NULL)
  722. break; // Normal shutdown
  723. if (bfpOverlapped->mKind == BfpOverlappedKind_FileWatcher)
  724. Kill((BfpFileWatcher*)bfpOverlapped);
  725. }
  726. }
  727. }
  728. static DWORD __stdcall WorkerProcThunk(void* _this)
  729. {
  730. BfpThread_SetName(NULL, "IOCPManager", NULL);
  731. ((IOCPManager*)_this)->WorkerProc();
  732. return 0;
  733. }
  734. static IOCPManager* Get()
  735. {
  736. AutoCrit autoCrit(gBfpCritSect);
  737. if (gIOCPManager == NULL)
  738. {
  739. gIOCPManager = new IOCPManager();
  740. BfpRecordManager(gIOCPManager);
  741. }
  742. return gIOCPManager;
  743. }
  744. };
  745. static void __cdecl HandlePureVirtualFunctionCall()
  746. {
  747. BfpSystem_FatalError("Pure virtual function call", NULL);
  748. }
  749. static void __cdecl HandleInvalidParameter(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
  750. {
  751. BfpSystem_FatalError("Invalid parameter", NULL);
  752. }
  753. static void __cdecl AbortHandler(int)
  754. {
  755. BfpSystem_FatalError("Abort handler", NULL);
  756. }
  757. static int64 gCPUFreq = -1;
  758. static int64 gStartCPUTick = -1;
  759. static int64 gStartQPF = -1;
  760. static void InitCPUFreq()
  761. {
  762. if (gStartCPUTick == -1)
  763. {
  764. gStartCPUTick = __rdtsc();
  765. LARGE_INTEGER largeVal = { 0 };
  766. QueryPerformanceCounter(&largeVal);
  767. gStartQPF = largeVal.QuadPart;
  768. }
  769. }
  770. static void(*sOldSIGABRTHandler)(int signal) = nullptr;
  771. BFP_EXPORT void BFP_CALLTYPE BfpSystem_Init(int version, BfpSystemInitFlags flags)
  772. {
  773. InitCPUFreq();
  774. ::_set_error_mode(_OUT_TO_STDERR);
  775. #ifdef _DEBUG
  776. ::_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
  777. #endif
  778. ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  779. ::SetErrorMode(SEM_FAILCRITICALERRORS);
  780. if (version != BFP_VERSION)
  781. {
  782. BfpSystem_FatalError(StrFormat("Bfp build version '%d' does not match requested version '%d'", BFP_VERSION, version).c_str(), "BFP FATAL ERROR");
  783. }
  784. if ((flags & BfpSystemInitFlag_InstallCrashCatcher) != 0)
  785. {
  786. // Set up a handler for pure virtual function calls
  787. _set_purecall_handler(HandlePureVirtualFunctionCall);
  788. // Set up a handler for invalid parameters such as printf(NULL);
  789. _set_invalid_parameter_handler(HandleInvalidParameter);
  790. // Set up a handler for abort(). This is done in two steps.
  791. // First we ask the CRT to call an abort handler. This is the
  792. // default, but explicitly setting it seems like a good idea.
  793. _set_abort_behavior(_CALL_REPORTFAULT, _CALL_REPORTFAULT);
  794. // Then we install our abort handler.
  795. sOldSIGABRTHandler = signal(SIGABRT, &AbortHandler);
  796. if (sOldSIGABRTHandler == SIG_ERR)
  797. sOldSIGABRTHandler = nullptr;
  798. CrashCatcher::Get()->Init();
  799. if ((flags & BfpSystemInitFlag_SilentCrash) != 0)
  800. CrashCatcher::Get()->SetCrashReportKind(BfpCrashReportKind_None);
  801. }
  802. }
  803. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCommandLine(int argc, char** argv)
  804. {
  805. // This isn't required on Windows, but it is on Linux
  806. }
  807. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashReportKind(BfpCrashReportKind crashReportKind)
  808. {
  809. CrashCatcher::Get()->SetCrashReportKind(crashReportKind);
  810. }
  811. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfoFunc(BfpCrashInfoFunc crashInfoFunc)
  812. {
  813. CrashCatcher::Get()->AddCrashInfoFunc(crashInfoFunc);
  814. }
  815. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfo(const char* str)
  816. {
  817. CrashCatcher::Get()->AddInfo(str);
  818. }
  819. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashRelaunchCmd(const char* str)
  820. {
  821. CrashCatcher::Get()->SetRelaunchCmd(str);
  822. }
  823. BFP_EXPORT void BFP_CALLTYPE BfpSystem_Shutdown()
  824. {
  825. while (gManagerTail != NULL)
  826. {
  827. auto next = gManagerTail->mNext;
  828. delete gManagerTail;
  829. gManagerTail = next;
  830. }
  831. if (CrashCatcher::Shutdown())
  832. {
  833. _set_purecall_handler(nullptr);
  834. _set_invalid_parameter_handler(nullptr);
  835. signal(SIGABRT, sOldSIGABRTHandler);
  836. }
  837. }
  838. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_TickCount()
  839. {
  840. return BFTickCount();
  841. }
  842. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpSystem_GetTimeStamp()
  843. {
  844. BfpTimeStamp timeStamp = 0;
  845. GetSystemTimeAsFileTime((FILETIME*)&timeStamp);
  846. return timeStamp;
  847. }
  848. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_EndianSwap16(uint16 val)
  849. {
  850. return _byteswap_ushort(val);
  851. }
  852. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_EndianSwap32(uint32 val)
  853. {
  854. return _byteswap_ulong(val);
  855. }
  856. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_EndianSwap64(uint64 val)
  857. {
  858. return _byteswap_uint64(val);
  859. }
  860. BFP_EXPORT uint8 BFP_CALLTYPE BfpSystem_InterlockedExchange8(uint8* ptr, uint8 val) // Returns the initial value in 'ptr'
  861. {
  862. return ::InterlockedExchange8((volatile char*)ptr, val);
  863. }
  864. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedExchange16(uint16* ptr, uint16 val) // Returns the initial value in 'ptr'
  865. {
  866. return ::InterlockedExchange16((volatile short*)ptr, val);
  867. }
  868. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchange32(uint32* ptr, uint32 val) // Returns the initial value in 'ptr'
  869. {
  870. return ::InterlockedExchange((volatile uint32*)ptr, val);
  871. }
  872. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchange64(uint64* ptr, uint64 val)
  873. {
  874. return ::InterlockedExchange((volatile uint64*)ptr, val);
  875. }
  876. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd8(uint8* ptr, uint8 val) // Returns the initial value in 'ptr'
  877. {
  878. return ::InterlockedExchangeAdd8((volatile char*)ptr, val);
  879. }
  880. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd16(uint16* ptr, uint16 val) // Returns the initial value in 'ptr'
  881. {
  882. return ::_InterlockedExchangeAdd16((volatile short*)ptr, val);
  883. }
  884. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd32(uint32* ptr, uint32 val) // Returns the initial value in 'ptr'
  885. {
  886. return ::InterlockedExchangeAdd((volatile uint32*)ptr, val);
  887. }
  888. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd64(uint64* ptr, uint64 val)
  889. {
  890. return ::InterlockedExchangeAdd((volatile uint64*)ptr, val);
  891. }
  892. BFP_EXPORT uint8 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange8(uint8* ptr, uint8 oldVal, uint8 newVal)
  893. {
  894. return ::_InterlockedCompareExchange8((volatile char*)ptr, newVal, oldVal);
  895. }
  896. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange16(uint16* ptr, uint16 oldVal, uint16 newVal)
  897. {
  898. return ::_InterlockedCompareExchange16((volatile short*)ptr, newVal, oldVal);
  899. }
  900. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange32(uint32* ptr, uint32 oldVal, uint32 newVal)
  901. {
  902. return ::InterlockedCompareExchange((volatile uint32*)ptr, newVal, oldVal);
  903. }
  904. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange64(uint64* ptr, uint64 oldVal, uint64 newVal)
  905. {
  906. return ::InterlockedCompareExchange64((volatile int64*)ptr, newVal, oldVal);
  907. }
  908. BFP_EXPORT void BFP_CALLTYPE BfpSystem_FatalError(const char* error, const char* title)
  909. {
  910. if (title != NULL)
  911. CrashCatcher::Get()->Crash(String(title) + "\n" + String(error));
  912. else
  913. CrashCatcher::Get()->Crash(error);
  914. }
  915. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetCommandLine(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  916. {
  917. WCHAR* ptr = ::GetCommandLineW();
  918. UTF16String wString(ptr);
  919. String env = UTF8Encode(wString);
  920. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  921. }
  922. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetExecutablePath(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  923. {
  924. WCHAR path[MAX_PATH];
  925. GetModuleFileNameW(NULL, path, MAX_PATH);
  926. String env = UTF8Encode(path);
  927. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  928. }
  929. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetEnvironmentStrings(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  930. {
  931. WCHAR* ptr = ::GetEnvironmentStringsW();
  932. WCHAR* endPtr = ptr;
  933. while (true)
  934. {
  935. if ((endPtr[0] == 0) && (endPtr[1] == 0))
  936. break;
  937. endPtr++;
  938. }
  939. UTF16String wString(ptr, (int)(endPtr - ptr + 2));
  940. String env = UTF8Encode(wString);
  941. ::FreeEnvironmentStringsW(ptr);
  942. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  943. }
  944. BFP_EXPORT int BFP_CALLTYPE BfpSystem_GetNumLogicalCPUs(BfpSystemResult* outResult)
  945. {
  946. SYSTEM_INFO sysInfo;
  947. GetSystemInfo(&sysInfo);
  948. OUTRESULT(BfpSystemResult_Ok);
  949. return sysInfo.dwNumberOfProcessors;
  950. }
  951. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTick()
  952. {
  953. return __rdtsc();
  954. }
  955. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTickFreq()
  956. {
  957. LARGE_INTEGER largeVal = { 0 };
  958. QueryPerformanceFrequency(&largeVal);
  959. int64 qpfFreq = largeVal.QuadPart;
  960. if (gStartCPUTick == -1)
  961. {
  962. InitCPUFreq();
  963. Sleep(10);
  964. }
  965. int64 cpuTick1 = __rdtsc();
  966. QueryPerformanceCounter(&largeVal);
  967. int64 slowTick1 = largeVal.QuadPart;
  968. int64 cpuElapsed = cpuTick1 - gStartCPUTick;
  969. int64 slowElapsed = slowTick1 - gStartQPF;
  970. double elapsedSeconds = slowElapsed / (double)qpfFreq;
  971. int64 freq = (int64)(cpuElapsed / elapsedSeconds);
  972. gCPUFreq = freq;
  973. return gCPUFreq;
  974. }
  975. BFP_EXPORT void BFP_CALLTYPE BfpSystem_CreateGUID(BfpGUID* outGuid)
  976. {
  977. memset(outGuid, 0, sizeof(BfpGUID));
  978. UuidCreate((UUID*)outGuid);
  979. }
  980. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetComputerName(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  981. {
  982. char computerName[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
  983. DWORD computerNameSize = MAX_COMPUTERNAME_LENGTH;
  984. GetComputerNameA(computerName, &computerNameSize);
  985. TryStringOut(computerName, outStr, inOutStrSize, (BfpResult*)outResult);
  986. }
  987. /// BfpFileWatcher
  988. BFP_EXPORT BfpFileWatcher* BFP_CALLTYPE BfpFileWatcher_WatchDirectory(const char* path, BfpDirectoryChangeFunc callback, BfpFileWatcherFlags flags, void* userData, BfpFileResult* outResult)
  989. {
  990. HANDLE directoryHandle = CreateFileW(
  991. UTF8Decode(path).c_str(), // Directory name
  992. FILE_LIST_DIRECTORY, // access (read-write) mode
  993. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  994. NULL, // security descriptor
  995. OPEN_EXISTING,
  996. FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // file attributes
  997. NULL // file with attributes to copy
  998. );
  999. if (!IsHandleValid(directoryHandle))
  1000. {
  1001. OUTRESULT(BfpFileResult_UnknownError);
  1002. return NULL;
  1003. }
  1004. BfpFileWatcher* fileWatcher = new BfpFileWatcher();
  1005. fileWatcher->mKind = BfpOverlappedKind_FileWatcher;
  1006. fileWatcher->mPath = path;
  1007. fileWatcher->mDirectoryChangeFunc = callback;
  1008. fileWatcher->mHandle = directoryHandle;
  1009. fileWatcher->mFlags = flags;
  1010. fileWatcher->mUserData = userData;
  1011. IOCPManager::Get()->Add(fileWatcher);
  1012. fileWatcher->Monitor();
  1013. return fileWatcher;
  1014. }
  1015. BFP_EXPORT void BFP_CALLTYPE BfpFileWatcher_Release(BfpFileWatcher* fileWatcher)
  1016. {
  1017. IOCPManager::Get()->Remove(fileWatcher);
  1018. //::CloseHandle(fileWatcher->mFileHandle);
  1019. //fileWatcher->mFileHandle = NULL;
  1020. //delete fileWatcher;
  1021. }
  1022. /// BfpProcess
  1023. BFP_EXPORT intptr BFP_CALLTYPE BfpProcess_GetCurrentId()
  1024. {
  1025. return ::GetCurrentProcessId();
  1026. }
  1027. struct BfpProcess
  1028. {
  1029. int mProcessId;
  1030. SYSTEM_PROCESS_INFORMATION* mInfo;
  1031. String mImageName;
  1032. };
  1033. BFP_EXPORT bool BFP_CALLTYPE BfpProcess_IsRemoteMachine(const char* machineName)
  1034. {
  1035. return false;
  1036. }
  1037. BFP_EXPORT BfpProcess* BFP_CALLTYPE BfpProcess_GetById(const char* machineName, int processId, BfpProcessResult* outResult)
  1038. {
  1039. BfpProcess* process = new BfpProcess();
  1040. process->mProcessId = processId;
  1041. process->mInfo = NULL;
  1042. return process;
  1043. }
  1044. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Enumerate(const char* machineName, BfpProcess** outProcesses, int* inOutProcessesSize, BfpProcessResult* outResult)
  1045. {
  1046. ImportNTDll();
  1047. if (gNtQuerySystemInformation == NULL)
  1048. {
  1049. *inOutProcessesSize = 0;
  1050. return;
  1051. }
  1052. uint allocSize = 1024;
  1053. uint8* data = NULL;
  1054. while (true)
  1055. {
  1056. data = new uint8[allocSize];
  1057. ULONG wantSize = 0;
  1058. NTSTATUS status = gNtQuerySystemInformation(SystemProcessInformation, data, allocSize, &wantSize);
  1059. if (status != STATUS_INFO_LENGTH_MISMATCH)
  1060. {
  1061. auto processInfo = (SYSTEM_PROCESS_INFORMATION*)data;
  1062. auto curProcessInfo = processInfo;
  1063. int count = 0;
  1064. while (true)
  1065. {
  1066. if (curProcessInfo == NULL)
  1067. break;
  1068. count++;
  1069. if (curProcessInfo->NextEntryOffset == 0)
  1070. break;
  1071. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1072. }
  1073. if (count > *inOutProcessesSize)
  1074. {
  1075. *inOutProcessesSize = count;
  1076. OUTRESULT(BfpProcessResult_InsufficientBuffer);
  1077. delete data;
  1078. return;
  1079. }
  1080. curProcessInfo = processInfo;
  1081. count = 0;
  1082. while (true)
  1083. {
  1084. if (curProcessInfo == NULL)
  1085. break;
  1086. if (curProcessInfo->ProcessId != 0)
  1087. {
  1088. BfpProcess* process = new BfpProcess();
  1089. int dataSize = sizeof(SYSTEM_PROCESS_INFORMATION) + sizeof(SYSTEM_THREAD) * (curProcessInfo->NumberOfThreads - 1);
  1090. process->mProcessId = (int)(intptr)curProcessInfo->ProcessId;
  1091. process->mInfo = (SYSTEM_PROCESS_INFORMATION*)malloc(dataSize);
  1092. memcpy(process->mInfo, curProcessInfo, dataSize);
  1093. UTF16String utf16;
  1094. utf16.Set(curProcessInfo->ImageName.Buffer, curProcessInfo->ImageName.Length / 2);
  1095. process->mImageName = UTF8Encode(utf16);
  1096. outProcesses[count++] = process;
  1097. }
  1098. if (curProcessInfo->NextEntryOffset == 0)
  1099. break;
  1100. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1101. }
  1102. *inOutProcessesSize = count;
  1103. OUTRESULT(BfpProcessResult_Ok);
  1104. delete data;
  1105. return;
  1106. }
  1107. allocSize = wantSize + 4096;
  1108. delete data;
  1109. }
  1110. }
  1111. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Release(BfpProcess* process)
  1112. {
  1113. if (process->mInfo != NULL)
  1114. free(process->mInfo);
  1115. delete process;
  1116. }
  1117. //struct EnumWndData
  1118. //{
  1119. // HWND mBestHandle;
  1120. // uint32 mProcessId;
  1121. //};
  1122. struct MainWindowCache
  1123. {
  1124. Dictionary<uint32, HWND> mMap;
  1125. uint32 mLastUpdate;
  1126. MainWindowCache()
  1127. {
  1128. mLastUpdate = 0;
  1129. }
  1130. };
  1131. static MainWindowCache gMainWindowCache;
  1132. static BOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM param)
  1133. {
  1134. //EnumWndData* enumWndData = (EnumWndData*)param;
  1135. DWORD processId = 0;
  1136. ::GetWindowThreadProcessId(hWnd, &processId);
  1137. if (gMainWindowCache.mMap.ContainsKey(processId))
  1138. {
  1139. //if (processId == 6720)
  1140. //OutputDebugStrF("Bailed\n");
  1141. return TRUE;
  1142. }
  1143. if ((::IsWindowVisible(hWnd)) && (::GetWindow(hWnd, GW_OWNER) == NULL))
  1144. {
  1145. //if (processId == 6720)
  1146. //OutputDebugStrF("Set\n");
  1147. gMainWindowCache.mMap[processId] = hWnd;
  1148. }
  1149. return TRUE;
  1150. }
  1151. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetMainWindowTitle(BfpProcess* process, char* outTitle, int* inOutTitleSize, BfpProcessResult* outResult)
  1152. {
  1153. HWND mainWindow = NULL;
  1154. //
  1155. {
  1156. AutoCrit autoCrit(gBfpCritSect);
  1157. if ((gMainWindowCache.mLastUpdate == 0) || (BFTickCount() - gMainWindowCache.mLastUpdate > 100))
  1158. {
  1159. gMainWindowCache.mMap.Clear();
  1160. ::EnumWindows(EnumWndProc, 0);
  1161. gMainWindowCache.mLastUpdate = BFTickCount();
  1162. }
  1163. gMainWindowCache.mMap.TryGetValue(process->mProcessId, &mainWindow);
  1164. }
  1165. /*EnumWndData enumWndData;
  1166. enumWndData.mBestHandle = NULL;
  1167. enumWndData.mProcessId = process->mProcessId;*/
  1168. String title;
  1169. if (mainWindow != NULL)
  1170. {
  1171. int wantSize = 128;
  1172. while (true)
  1173. {
  1174. WCHAR* str = new WCHAR[wantSize];
  1175. int size = ::GetWindowTextW(mainWindow, str, wantSize) + 1;
  1176. if (size <= 0)
  1177. {
  1178. delete str;
  1179. break;
  1180. }
  1181. if (size <= wantSize)
  1182. {
  1183. title = UTF8Encode(str);
  1184. delete str;
  1185. break;
  1186. }
  1187. delete str;
  1188. wantSize = size;
  1189. }
  1190. }
  1191. TryStringOut(title, outTitle, inOutTitleSize, (BfpResult*)outResult);
  1192. }
  1193. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetProcessName(BfpProcess* process, char* outName, int* inOutNameSize, BfpProcessResult* outResult)
  1194. {
  1195. if (process->mImageName.IsEmpty())
  1196. {
  1197. HANDLE hProc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process->mProcessId);
  1198. if (hProc == INVALID_HANDLE_VALUE)
  1199. {
  1200. OUTRESULT(BfpProcessResult_UnknownError);
  1201. return;
  1202. }
  1203. WCHAR wName[MAX_PATH];
  1204. ::GetModuleFileNameExW(hProc, NULL, wName, MAX_PATH);
  1205. ::CloseHandle(hProc);
  1206. String name = UTF8Encode(wName);
  1207. process->mImageName = name;
  1208. }
  1209. TryStringOut(process->mImageName, outName, inOutNameSize, (BfpResult*)outResult);
  1210. }
  1211. BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetProcessId(BfpProcess* process)
  1212. {
  1213. return process->mProcessId;
  1214. }
  1215. BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetRunningTime(BfpProcess* process)
  1216. {
  1217. if (process->mInfo == NULL)
  1218. return -1;
  1219. return (int)(process->mInfo->CreateTime.QuadPart / 10);
  1220. }
  1221. /// BfpSpawn
  1222. struct BfpSpawn
  1223. {
  1224. public:
  1225. String mArgsParamFilePath;
  1226. HANDLE mHProcess;
  1227. DWORD mProcessId;
  1228. HANDLE mStandardInputWritePipeHandle;
  1229. HANDLE mStandardOutputReadPipeHandle;
  1230. HANDLE mStandardErrorReadPipeHandle;
  1231. bool mIsDone;
  1232. public:
  1233. BfpSpawn()
  1234. {
  1235. mHProcess = 0;
  1236. mProcessId = 0;
  1237. mStandardInputWritePipeHandle = 0;
  1238. mStandardOutputReadPipeHandle = 0;
  1239. mStandardErrorReadPipeHandle = 0;
  1240. mIsDone = false;
  1241. }
  1242. ~BfpSpawn()
  1243. {
  1244. if (IsHandleValid(mHProcess))
  1245. ::CloseHandle(mHProcess);
  1246. if (IsHandleValid(mStandardInputWritePipeHandle))
  1247. ::CloseHandle(mStandardInputWritePipeHandle);
  1248. if (IsHandleValid(mStandardOutputReadPipeHandle))
  1249. ::CloseHandle(mStandardOutputReadPipeHandle);
  1250. if (IsHandleValid(mStandardErrorReadPipeHandle))
  1251. ::CloseHandle(mStandardErrorReadPipeHandle);
  1252. }
  1253. static bool CreatePipeWithSecurityAttributes(HANDLE& hReadPipe, HANDLE& hWritePipe, SECURITY_ATTRIBUTES* lpPipeAttributes, int32 nSize)
  1254. {
  1255. hReadPipe = 0;
  1256. hWritePipe = 0;
  1257. bool ret = ::CreatePipe(&hReadPipe, &hWritePipe, lpPipeAttributes, nSize);
  1258. if (!ret || (hReadPipe == INVALID_HANDLE_VALUE) || (hWritePipe == INVALID_HANDLE_VALUE))
  1259. return false;
  1260. return true;
  1261. }
  1262. // Using synchronous Anonymous pipes for process input/output redirection means we would end up
  1263. // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since
  1264. // it will take advantage of the NT IO completion port infrastructure. But we can't really use
  1265. // Overlapped I/O for process input/output as it would break Console apps (managed Console class
  1266. // methods such as WriteLine as well as native CRT functions like printf) which are making an
  1267. // assumption that the console standard handles (obtained via GetStdHandle()) are opened
  1268. // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchrnously!
  1269. bool CreatePipe(HANDLE& parentHandle, HANDLE& childHandle, bool parentInputs)
  1270. {
  1271. SECURITY_ATTRIBUTES securityAttributesParent = { 0 };
  1272. securityAttributesParent.bInheritHandle = 1;
  1273. HANDLE hTmp = INVALID_HANDLE_VALUE;
  1274. if (parentInputs)
  1275. CreatePipeWithSecurityAttributes(childHandle, hTmp, &securityAttributesParent, 0);
  1276. else
  1277. CreatePipeWithSecurityAttributes(hTmp, childHandle, &securityAttributesParent, 0);
  1278. HANDLE dupHandle = 0;
  1279. // Duplicate the parent handle to be non-inheritable so that the child process
  1280. // doesn't have access. This is done for correctness sake, exact reason is unclear.
  1281. // One potential theory is that child process can do something brain dead like
  1282. // closing the parent end of the pipe and there by getting into a blocking situation
  1283. // as parent will not be draining the pipe at the other end anymore.
  1284. if (!::DuplicateHandle(GetCurrentProcess(), hTmp,
  1285. GetCurrentProcess(), &dupHandle,
  1286. 0, false, DUPLICATE_SAME_ACCESS))
  1287. {
  1288. return false;
  1289. }
  1290. parentHandle = dupHandle;
  1291. if (hTmp != INVALID_HANDLE_VALUE)
  1292. ::CloseHandle(hTmp);
  1293. return true;
  1294. }
  1295. bool StartWithCreateProcess(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1296. {
  1297. String fileName = targetPath;
  1298. String commandLine;
  1299. if ((flags & BfpSpawnFlag_ArgsIncludesTarget) == 0)
  1300. {
  1301. if ((!fileName.StartsWith("\"")) && (!fileName.EndsWith("\"")))
  1302. {
  1303. bool needsQuoting = false;
  1304. for (int i = 0; i < (int)fileName.length(); i++)
  1305. {
  1306. char c = fileName[i];
  1307. if (c == ' ')
  1308. needsQuoting = true;
  1309. }
  1310. if (needsQuoting)
  1311. {
  1312. commandLine.Append('\"');
  1313. commandLine.Append(fileName);
  1314. commandLine.Append('\"');
  1315. }
  1316. else
  1317. {
  1318. commandLine.Append(fileName);
  1319. }
  1320. }
  1321. else
  1322. {
  1323. commandLine.Append(fileName);
  1324. }
  1325. }
  1326. if ((args != NULL) && (args[0] != '0'))
  1327. {
  1328. if (!commandLine.IsEmpty())
  1329. commandLine.Append(' ');
  1330. commandLine.Append(args);
  1331. }
  1332. STARTUPINFOW startupInfo = { 0 };
  1333. PROCESS_INFORMATION processInfo = { 0 };
  1334. bool retVal;
  1335. int32 errorCode = 0;
  1336. //
  1337. {
  1338. // set up the streams
  1339. if ((flags & (BfpSpawnFlag_RedirectStdInput | BfpSpawnFlag_RedirectStdOutput | BfpSpawnFlag_RedirectStdError)) != 0)
  1340. {
  1341. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  1342. CreatePipe(mStandardInputWritePipeHandle, startupInfo.hStdInput, true);
  1343. else if (::GetConsoleWindow() != NULL)
  1344. startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  1345. else
  1346. startupInfo.hStdInput = INVALID_HANDLE_VALUE;
  1347. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  1348. CreatePipe(mStandardOutputReadPipeHandle, startupInfo.hStdOutput, false);
  1349. else
  1350. startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  1351. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  1352. CreatePipe(mStandardErrorReadPipeHandle, startupInfo.hStdError, false);
  1353. else
  1354. startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  1355. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  1356. }
  1357. // set up the creation flags paramater
  1358. int32 creationFlags = 0;
  1359. if ((flags & BfpSpawnFlag_NoWindow) != 0)
  1360. creationFlags |= CREATE_NO_WINDOW;
  1361. // set up the environment block parameter
  1362. WCHAR* targetStrPtr = NULL;
  1363. UTF16String targetStrW;
  1364. if ((flags & BfpSpawnFlag_ArgsIncludesTarget) != 0)
  1365. {
  1366. // If we already included the target in the args then the actual target may be different, so we need to explicitly pass that
  1367. targetStrW = UTF8Decode(targetPath);
  1368. targetStrPtr = (WCHAR*)targetStrW.c_str();
  1369. }
  1370. WCHAR* dirStrPtr = NULL;
  1371. UTF16String dirStrW;
  1372. if ((workingDir != NULL) && (workingDir[0] != 0))
  1373. {
  1374. dirStrW = UTF8Decode(workingDir);
  1375. dirStrPtr = (WCHAR*)dirStrW.c_str();
  1376. }
  1377. UTF16String envW;
  1378. void* envVoidPtr = NULL;
  1379. if ((env != NULL) && (env[0] != 0))
  1380. {
  1381. bool useUnicodeEnv = false;
  1382. if (useUnicodeEnv)
  1383. {
  1384. const char* envPtr = env;
  1385. while (true)
  1386. {
  1387. if ((envPtr[0] == 0) && (envPtr[1] == 0))
  1388. break;
  1389. envPtr++;
  1390. }
  1391. int envSize = (int)(envPtr - env) + 2;
  1392. String str8(env, envSize);
  1393. envW = UTF8Decode(str8);
  1394. envVoidPtr = (void*)envW.c_str();
  1395. startupInfo.dwFlags |= CREATE_UNICODE_ENVIRONMENT;
  1396. }
  1397. else
  1398. {
  1399. envVoidPtr = (void*)env;
  1400. }
  1401. }
  1402. retVal = ::CreateProcessW(
  1403. targetStrPtr,
  1404. (WCHAR*)UTF8Decode(commandLine).c_str(), // pointer to the command line string
  1405. NULL, // pointer to process security attributes, we don't need to inherit the handle
  1406. NULL, // pointer to thread security attributes
  1407. true, // handle inheritance flag
  1408. creationFlags, // creation flags
  1409. envVoidPtr, // pointer to new environment block
  1410. dirStrPtr, // pointer to current directory name
  1411. &startupInfo, // pointer to STARTUPINFO
  1412. &processInfo // pointer to PROCESS_INFORMATION
  1413. );
  1414. if (!retVal)
  1415. errorCode = ::GetLastError();
  1416. if (processInfo.hThread != INVALID_HANDLE_VALUE)
  1417. ::CloseHandle(processInfo.hThread);
  1418. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  1419. ::CloseHandle(startupInfo.hStdInput);
  1420. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  1421. ::CloseHandle(startupInfo.hStdOutput);
  1422. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  1423. ::CloseHandle(startupInfo.hStdError);
  1424. if (!retVal)
  1425. {
  1426. if (IsHandleValid(mStandardInputWritePipeHandle))
  1427. {
  1428. ::CloseHandle(mStandardInputWritePipeHandle);
  1429. mStandardInputWritePipeHandle = 0;
  1430. }
  1431. if (IsHandleValid(mStandardOutputReadPipeHandle))
  1432. {
  1433. ::CloseHandle(mStandardOutputReadPipeHandle);
  1434. mStandardOutputReadPipeHandle = 0;
  1435. }
  1436. if (IsHandleValid(mStandardErrorReadPipeHandle))
  1437. {
  1438. ::CloseHandle(mStandardErrorReadPipeHandle);
  1439. mStandardErrorReadPipeHandle = 0;
  1440. }
  1441. OUTRESULT(BfpSpawnResult_UnknownError);
  1442. if (errorCode == ERROR_BAD_EXE_FORMAT || errorCode == ERROR_EXE_MACHINE_TYPE_MISMATCH)
  1443. {
  1444. return false;
  1445. }
  1446. return false;
  1447. }
  1448. }
  1449. bool ret = false;
  1450. if (IsHandleValid(processInfo.hProcess))
  1451. {
  1452. mHProcess = processInfo.hProcess;
  1453. mProcessId = processInfo.dwProcessId;
  1454. ret = true;
  1455. }
  1456. if (!ret)
  1457. {
  1458. OUTRESULT(BfpSpawnResult_UnknownError);
  1459. return false;
  1460. }
  1461. return true;
  1462. }
  1463. bool StartWithShellExecute(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1464. {
  1465. SHELLEXECUTEINFOW shellExecuteInfo = { 0 };
  1466. shellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
  1467. shellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  1468. if ((flags & BfpSpawnFlag_ErrorDialog) != 0)
  1469. {
  1470. //shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle;
  1471. }
  1472. else
  1473. {
  1474. shellExecuteInfo.fMask |= SEE_MASK_FLAG_NO_UI;
  1475. }
  1476. if ((flags & BfpSpawnFlag_NoWindow) != 0)
  1477. shellExecuteInfo.nShow = SW_HIDE;
  1478. else
  1479. shellExecuteInfo.nShow = SW_SHOWNORMAL;
  1480. UTF16String fileW;
  1481. UTF16String verbW;
  1482. UTF16String argsW;
  1483. UTF16String dirW;
  1484. String target = targetPath;
  1485. int barPos = (int)target.IndexOf('|');
  1486. if (barPos != -1)
  1487. {
  1488. fileW = UTF8Decode(target.Substring(0, barPos));
  1489. shellExecuteInfo.lpFile = fileW.c_str();
  1490. verbW = UTF8Decode(target.Substring(barPos + 1));
  1491. shellExecuteInfo.lpVerb = verbW.c_str();
  1492. }
  1493. else
  1494. {
  1495. fileW = UTF8Decode(target);
  1496. shellExecuteInfo.lpFile = fileW.c_str();
  1497. }
  1498. if ((args != NULL) && (args[0] != 0))
  1499. {
  1500. argsW = UTF8Decode(args);
  1501. shellExecuteInfo.lpParameters = argsW.c_str();
  1502. }
  1503. if ((workingDir != NULL) && (workingDir[0] != 0))
  1504. {
  1505. dirW = UTF8Decode(workingDir);
  1506. shellExecuteInfo.lpDirectory = dirW.c_str();
  1507. }
  1508. shellExecuteInfo.fMask |= SEE_MASK_FLAG_DDEWAIT;
  1509. BOOL success = ::ShellExecuteExW(&shellExecuteInfo);
  1510. if (!success)
  1511. {
  1512. int lastError = ::GetLastError();
  1513. OUTRESULT(BfpSpawnResult_UnknownError);
  1514. return false;
  1515. }
  1516. mHProcess = shellExecuteInfo.hProcess;
  1517. return true;
  1518. }
  1519. };
  1520. BFP_EXPORT BfpSpawn* BFP_CALLTYPE BfpSpawn_Create(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1521. {
  1522. String newArgs;
  1523. String tempFileName;
  1524. if ((flags & BfpSpawnFlag_UseArgsFile) != 0)
  1525. {
  1526. char tempPathStr[MAX_PATH];
  1527. ::GetTempPathA(MAX_PATH, tempPathStr);
  1528. char tempFileNameStr[MAX_PATH];
  1529. ::GetTempFileNameA(tempPathStr, "BFP", 0, tempFileNameStr);
  1530. tempFileName = tempFileNameStr;
  1531. BfpFileResult fileResult;
  1532. BfpFile* file = BfpFile_Create(tempFileNameStr, BfpFileCreateKind_CreateAlways, BfpFileCreateFlag_Write, BfpFileAttribute_Normal, &fileResult);
  1533. if (file == NULL)
  1534. {
  1535. OUTRESULT(BfpSpawnResult_TempFileError);
  1536. return NULL;
  1537. }
  1538. if ((flags & BfpSpawnFlag_UseArgsFile_Native) != 0)
  1539. {
  1540. UTF16String wStr = UTF8Decode(args);
  1541. if ((flags & BfpSpawnFlag_UseArgsFile_BOM) != 0)
  1542. {
  1543. uint8 bom[2] = { 0xFF, 0xFE };
  1544. BfpFile_Write(file, bom, 2, -1, NULL);
  1545. }
  1546. BfpFile_Write(file, wStr.c_str(), wStr.length() * 2, -1, NULL);
  1547. }
  1548. else
  1549. BfpFile_Write(file, args, strlen(args), -1, NULL);
  1550. BfpFile_Release(file);
  1551. newArgs.Append("@");
  1552. newArgs.Append(tempFileName);
  1553. if (newArgs.Contains(' '))
  1554. {
  1555. newArgs.Insert(0, '\"');
  1556. newArgs.Append('\"');
  1557. }
  1558. args = newArgs.c_str();
  1559. }
  1560. BfpSpawn* spawn = new BfpSpawn();
  1561. bool success = false;
  1562. if ((flags & BfpSpawnFlag_UseShellExecute) != 0)
  1563. success = spawn->StartWithShellExecute(targetPath, args, workingDir, env, flags, outResult);
  1564. else
  1565. success = spawn->StartWithCreateProcess(targetPath, args, workingDir, env, flags, outResult);
  1566. if (!success)
  1567. {
  1568. delete spawn;
  1569. return NULL;
  1570. }
  1571. spawn->mArgsParamFilePath = tempFileName;
  1572. return spawn;
  1573. }
  1574. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_Release(BfpSpawn* spawn)
  1575. {
  1576. if ((!spawn->mArgsParamFilePath.IsEmpty()) && (spawn->mIsDone))
  1577. BfpFile_Delete(spawn->mArgsParamFilePath.c_str(), NULL);
  1578. delete spawn;
  1579. }
  1580. // static BOOL CALLBACK TerminateAppEnum(HWND hwnd, LPARAM lParam)
  1581. // {
  1582. // DWORD dwID;
  1583. // GetWindowThreadProcessId(hwnd, &dwID);
  1584. //
  1585. // if (dwID == (DWORD)lParam)
  1586. // {
  1587. // PostMessage(hwnd, WM_CLOSE, 0, 0);
  1588. // }
  1589. //
  1590. // return TRUE;
  1591. // }
  1592. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_Kill(BfpSpawn* spawn, int exitCode, BfpKillFlags killFlags, BfpSpawnResult* outResult)
  1593. {
  1594. //::EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM)spawn->mProcessId);
  1595. if ((killFlags & BfpKillFlag_KillChildren) != 0)
  1596. {
  1597. ImportNTDll();
  1598. HashSet<int> killSet;
  1599. killSet.Add(spawn->mProcessId);
  1600. HashSet<int> killedSet;
  1601. killedSet.Add(spawn->mProcessId);
  1602. // New child processes can launch between the NtQuerySystemInformation call and the actual process termination,
  1603. // so we need to run multiple loops until we stop finding child processes
  1604. while (true)
  1605. {
  1606. uint allocSize = 8192;
  1607. uint8* data;
  1608. while (true)
  1609. {
  1610. data = new uint8[allocSize];
  1611. ULONG wantSize = 0;
  1612. NTSTATUS status = gNtQuerySystemInformation(SystemProcessInformation, data, allocSize, &wantSize);
  1613. if (status != STATUS_INFO_LENGTH_MISMATCH)
  1614. {
  1615. bool foundNew;
  1616. do
  1617. {
  1618. foundNew = false;
  1619. auto processInfo = (SYSTEM_PROCESS_INFORMATION*)data;
  1620. auto curProcessInfo = processInfo;
  1621. while (true)
  1622. {
  1623. if (curProcessInfo == NULL)
  1624. break;
  1625. if (killSet.Contains((int)(intptr)curProcessInfo->InheritedFromProcessId))
  1626. {
  1627. if (killSet.Add((int)(intptr)curProcessInfo->ProcessId))
  1628. foundNew = true;
  1629. }
  1630. if (curProcessInfo->NextEntryOffset == 0)
  1631. break;
  1632. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1633. }
  1634. } while (foundNew);
  1635. delete data;
  1636. break;
  1637. }
  1638. allocSize = wantSize + 4096;
  1639. delete data;
  1640. }
  1641. if (killedSet.size() == killSet.size())
  1642. break;
  1643. for (auto pid : killSet)
  1644. {
  1645. if (!killedSet.Add(pid))
  1646. continue;
  1647. HANDLE procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  1648. if (procHandle != NULL)
  1649. {
  1650. ::TerminateProcess(procHandle, exitCode);
  1651. // DWORD threadId = 0;
  1652. // ::CreateRemoteThread(procHandle, NULL, 0, (LPTHREAD_START_ROUTINE)ExitProcess, (void*)(intptr)exitCode, 0, &threadId);
  1653. // if (pid != spawn->mProcessId)
  1654. // ::CloseHandle(procHandle);
  1655. }
  1656. }
  1657. }
  1658. }
  1659. if (!::TerminateProcess(spawn->mHProcess, (UINT)exitCode))
  1660. {
  1661. int lastError = ::GetLastError();
  1662. OUTRESULT(BfpSpawnResult_UnknownError);
  1663. return;
  1664. }
  1665. // BOOL hadConsole = ::FreeConsole();
  1666. // ::AttachConsole(spawn->mProcessId);
  1667. // ::SetConsoleCtrlHandler(NULL, true);
  1668. // ::GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
  1669. // //::Sleep(2000);
  1670. // ::FreeConsole();
  1671. // ::SetConsoleCtrlHandler(NULL, false);
  1672. // if (!::TerminateProcess(spawn->mHProcess, (UINT)exitCode))
  1673. // {
  1674. // int lastError = ::GetLastError();
  1675. // OUTRESULT(BfpSpawnResult_UnknownError);
  1676. // return;
  1677. // }
  1678. OUTRESULT(BfpSpawnResult_Ok);
  1679. }
  1680. BFP_EXPORT bool BFP_CALLTYPE BfpSpawn_WaitFor(BfpSpawn* spawn, int waitMS, int* outExitCode, BfpSpawnResult* outResult)
  1681. {
  1682. if (::WaitForSingleObject(spawn->mHProcess, waitMS) != WAIT_OBJECT_0)
  1683. {
  1684. OUTRESULT(BfpSpawnResult_UnknownError);
  1685. return false;
  1686. }
  1687. spawn->mIsDone = true;
  1688. ::GetExitCodeProcess(spawn->mHProcess, (DWORD*)outExitCode);
  1689. OUTRESULT(BfpSpawnResult_Ok);
  1690. return true;
  1691. }
  1692. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_GetStdHandles(BfpSpawn* spawn, BfpFile** outStdIn, BfpFile** outStdOut, BfpFile** outStdErr)
  1693. {
  1694. if (outStdIn != NULL)
  1695. {
  1696. *outStdIn = new BfpFile(spawn->mStandardInputWritePipeHandle);
  1697. spawn->mStandardInputWritePipeHandle = 0;
  1698. }
  1699. if (outStdOut != NULL)
  1700. {
  1701. *outStdOut = new BfpFile(spawn->mStandardOutputReadPipeHandle);
  1702. spawn->mStandardOutputReadPipeHandle = 0;
  1703. }
  1704. if (outStdErr != NULL)
  1705. {
  1706. *outStdErr = new BfpFile(spawn->mStandardErrorReadPipeHandle);
  1707. spawn->mStandardErrorReadPipeHandle = 0;
  1708. }
  1709. }
  1710. /// BfpThread
  1711. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_Create(BfpThreadStartProc startProc, void* threadParam, intptr stackSize, BfpThreadCreateFlags flags, BfpThreadId* outThreadId)
  1712. {
  1713. DWORD creationFlags = 0;
  1714. if ((flags & BfpThreadCreateFlag_Suspended) != 0)
  1715. creationFlags |= CREATE_SUSPENDED;
  1716. if (((flags & BfpThreadCreateFlag_StackSizeReserve) != 0) && (stackSize != 0))
  1717. creationFlags |= STACK_SIZE_PARAM_IS_A_RESERVATION;
  1718. DWORD threadId;
  1719. // We have an explicit LPTHREAD_START_ROUTINE cast because BfpThreadStartProc returns 'void'. This doesn't break the calling convention, it just means
  1720. // the return register value is garbage
  1721. HANDLE handle = ::CreateThread(NULL, (SIZE_T)stackSize, (LPTHREAD_START_ROUTINE)startProc, threadParam, creationFlags, &threadId);
  1722. if (outThreadId != NULL)
  1723. *outThreadId = threadId;
  1724. return (BfpThread*)handle;
  1725. }
  1726. BFP_EXPORT void BFP_CALLTYPE BfpThread_Release(BfpThread* thread)
  1727. {
  1728. ::CloseHandle((HANDLE)thread);
  1729. }
  1730. static void SetThreadName(DWORD threadId, const char* name)
  1731. {
  1732. const DWORD MS_VC_EXCEPTION = 0x406D1388;
  1733. typedef struct tagTHREADNAME_INFO
  1734. {
  1735. DWORD dwType; // Must be 0x1000.
  1736. LPCSTR szName; // Pointer to name (in user addr space).
  1737. DWORD dwThreadID; // Thread ID (-1=caller thread).
  1738. DWORD dwFlags; // Reserved for future use, must be zero.
  1739. } THREADNAME_INFO;
  1740. THREADNAME_INFO info;
  1741. info.dwType = 0x1000;
  1742. info.szName = name;
  1743. info.dwThreadID = threadId;
  1744. info.dwFlags = 0;
  1745. __try
  1746. {
  1747. RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
  1748. }
  1749. __except (EXCEPTION_EXECUTE_HANDLER)
  1750. {
  1751. }
  1752. }
  1753. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetName(BfpThread* thread, const char* name, BfpThreadResult* outResult)
  1754. {
  1755. ImportKernel();
  1756. HANDLE hThread = (HANDLE)thread;
  1757. if (hThread == NULL)
  1758. hThread = ::GetCurrentThread();
  1759. if (gSetThreadDescription != NULL)
  1760. {
  1761. gSetThreadDescription(hThread, UTF8Decode(name).c_str());
  1762. OUTRESULT(BfpThreadResult_Ok);
  1763. return;
  1764. }
  1765. SetThreadName(::GetThreadId(hThread), name);
  1766. OUTRESULT(BfpThreadResult_UnknownError);
  1767. }
  1768. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetName(BfpThread* thread, char* outName, int* inOutNameSize, BfpThreadResult* outResult)
  1769. {
  1770. ImportKernel();
  1771. PWSTR wStr = NULL;
  1772. if (gGetThreadDescription != NULL)
  1773. {
  1774. gGetThreadDescription((HANDLE)thread, &wStr);
  1775. if (wStr == NULL)
  1776. {
  1777. OUTRESULT(BfpThreadResult_UnknownError);
  1778. return;
  1779. }
  1780. String str = UTF8Encode(wStr);
  1781. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  1782. LocalFree(wStr);
  1783. return;
  1784. }
  1785. OUTRESULT(BfpThreadResult_UnknownError);
  1786. }
  1787. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_GetCurrent()
  1788. {
  1789. return (BfpThread*)::OpenThread(THREAD_ALL_ACCESS, TRUE, ::GetCurrentThreadId());
  1790. }
  1791. BFP_EXPORT BfpThreadId BFP_CALLTYPE BfpThread_GetCurrentId()
  1792. {
  1793. return (BfpThreadId)::GetCurrentThreadId();
  1794. }
  1795. BFP_EXPORT bool BFP_CALLTYPE BfpThread_WaitFor(BfpThread* thread, int waitMS)
  1796. {
  1797. return ::WaitForSingleObject((HANDLE)thread, waitMS) == WAIT_OBJECT_0;
  1798. }
  1799. BFP_EXPORT BfpThreadPriority BFP_CALLTYPE BfpThread_GetPriority(BfpThread* thread, BfpThreadResult* outResult)
  1800. {
  1801. return (BfpThreadPriority)::GetThreadPriority((HANDLE)thread);
  1802. }
  1803. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetPriority(BfpThread* thread, BfpThreadPriority threadPriority, BfpThreadResult* outResult)
  1804. {
  1805. // Coincidentally, our priority values map to (THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST)
  1806. if (::SetThreadPriority((HANDLE)thread, (int)threadPriority))
  1807. OUTRESULT(BfpThreadResult_Ok);
  1808. else
  1809. OUTRESULT(BfpThreadResult_UnknownError);
  1810. }
  1811. BFP_EXPORT void BFP_CALLTYPE BfpThread_Suspend(BfpThread* thread, BfpThreadResult* outResult)
  1812. {
  1813. DWORD suspendCount = ::SuspendThread((HANDLE)thread);
  1814. if (suspendCount == (DWORD)-1)
  1815. {
  1816. int error = GetLastError();
  1817. BF_DBG_FATAL("Failed BfpThread_Suspend");
  1818. OUTRESULT(BfpThreadResult_UnknownError);
  1819. return;
  1820. }
  1821. OUTRESULT(BfpThreadResult_Ok);
  1822. }
  1823. BFP_EXPORT void BFP_CALLTYPE BfpThread_Resume(BfpThread* thread, BfpThreadResult* outResult)
  1824. {
  1825. DWORD suspendCount = ::ResumeThread((HANDLE)thread);
  1826. if (suspendCount == (DWORD)-1)
  1827. {
  1828. int error = GetLastError();
  1829. BF_DBG_FATAL("Failed BfpThread_Resume");
  1830. OUTRESULT(BfpThreadResult_UnknownError);
  1831. return;
  1832. }
  1833. OUTRESULT(BfpThreadResult_Ok);
  1834. }
  1835. // Windows 7 SP1 is the first version of Windows to support the AVX API.
  1836. // The value for CONTEXT_XSTATE has changed between Windows 7 and
  1837. // Windows 7 SP1 and greater.
  1838. // While the value will be correct for future SDK headers, we need to set
  1839. // this value manually when building with a Windows 7 SDK for running on
  1840. // Windows 7 SPI OS bits.
  1841. #undef CONTEXT_XSTATE
  1842. #if defined(_M_X64)
  1843. #define CONTEXT_XSTATE (0x00100040)
  1844. #else
  1845. #define CONTEXT_XSTATE (0x00010040)
  1846. #endif
  1847. // Since the AVX API is not declared in the Windows 7 SDK headers and
  1848. // since we don't have the proper libs to work with, we will declare
  1849. // the API as function pointers and get them with GetProcAddress calls
  1850. // from kernel32.dll. We also need to set some #defines.
  1851. #define XSTATE_AVX (XSTATE_GSSE)
  1852. #define XSTATE_MASK_AVX (XSTATE_MASK_GSSE)
  1853. typedef DWORD64(WINAPI* PGETENABLEDXSTATEFEATURES)();
  1854. static PGETENABLEDXSTATEFEATURES pfnGetEnabledXStateFeatures = NULL;
  1855. typedef BOOL(WINAPI* PINITIALIZECONTEXT)(PVOID Buffer, DWORD ContextFlags, PCONTEXT* Context, PDWORD ContextLength);
  1856. static PINITIALIZECONTEXT pfnInitializeContext = NULL;
  1857. typedef BOOL(WINAPI* PGETXSTATEFEATURESMASK)(PCONTEXT Context, PDWORD64 FeatureMask);
  1858. static PGETXSTATEFEATURESMASK pfnGetXStateFeaturesMask = NULL;
  1859. typedef PVOID(WINAPI* LOCATEXSTATEFEATURE)(PCONTEXT Context, DWORD FeatureId, PDWORD Length);
  1860. static LOCATEXSTATEFEATURE pfnLocateXStateFeature = NULL;
  1861. typedef BOOL(WINAPI* SETXSTATEFEATURESMASK)(PCONTEXT Context, DWORD64 FeatureMask);
  1862. static SETXSTATEFEATURESMASK pfnSetXStateFeaturesMask = NULL;
  1863. static uint8 ContextBuffer[4096];
  1864. static CONTEXT* CaptureRegistersEx(HANDLE hThread, intptr*& curPtr)
  1865. {
  1866. PCONTEXT Context;
  1867. DWORD ContextSize;
  1868. DWORD64 FeatureMask;
  1869. DWORD FeatureLength;
  1870. BOOL Success;
  1871. PM128A Xmm;
  1872. PM128A Ymm;
  1873. if (pfnGetEnabledXStateFeatures == (PGETENABLEDXSTATEFEATURES)-1)
  1874. return NULL;
  1875. if (pfnGetEnabledXStateFeatures == NULL)
  1876. {
  1877. HMODULE hm = GetModuleHandleA("kernel32.dll");
  1878. if (hm == NULL)
  1879. {
  1880. pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)-1;
  1881. return NULL;
  1882. }
  1883. pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)GetProcAddress(hm, "GetEnabledXStateFeatures");
  1884. pfnInitializeContext = (PINITIALIZECONTEXT)GetProcAddress(hm, "InitializeContext");
  1885. pfnGetXStateFeaturesMask = (PGETXSTATEFEATURESMASK)GetProcAddress(hm, "GetXStateFeaturesMask");
  1886. pfnLocateXStateFeature = (LOCATEXSTATEFEATURE)GetProcAddress(hm, "LocateXStateFeature");
  1887. pfnSetXStateFeaturesMask = (SETXSTATEFEATURESMASK)GetProcAddress(hm, "SetXStateFeaturesMask");
  1888. if (pfnGetEnabledXStateFeatures == NULL
  1889. || pfnInitializeContext == NULL
  1890. || pfnGetXStateFeaturesMask == NULL
  1891. || pfnLocateXStateFeature == NULL
  1892. || pfnSetXStateFeaturesMask == NULL)
  1893. {
  1894. pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)-1;
  1895. return NULL;
  1896. }
  1897. }
  1898. FeatureMask = pfnGetEnabledXStateFeatures();
  1899. if ((FeatureMask & XSTATE_MASK_AVX) == 0)
  1900. return NULL;
  1901. ContextSize = 0;
  1902. Success = pfnInitializeContext(NULL,
  1903. CONTEXT_ALL | CONTEXT_XSTATE | CONTEXT_EXCEPTION_REQUEST,
  1904. NULL,
  1905. &ContextSize);
  1906. if (ContextSize > sizeof(ContextBuffer))
  1907. return NULL;
  1908. Success = pfnInitializeContext(ContextBuffer,
  1909. CONTEXT_ALL | CONTEXT_XSTATE | CONTEXT_EXCEPTION_REQUEST,
  1910. &Context,
  1911. &ContextSize);
  1912. if (Success == FALSE)
  1913. return NULL;
  1914. Success = pfnSetXStateFeaturesMask(Context, XSTATE_MASK_AVX);
  1915. if (Success == FALSE)
  1916. return Context;
  1917. Success = GetThreadContext(hThread, Context);
  1918. if (Success == FALSE)
  1919. return Context;
  1920. Success = pfnGetXStateFeaturesMask(Context, &FeatureMask);
  1921. if (Success == FALSE)
  1922. return Context;
  1923. if ((FeatureMask & XSTATE_MASK_AVX) == 0)
  1924. return Context;
  1925. Xmm = (PM128A)pfnLocateXStateFeature(Context, XSTATE_LEGACY_SSE, &FeatureLength);
  1926. Ymm = (PM128A)pfnLocateXStateFeature(Context, XSTATE_AVX, NULL);
  1927. memcpy(curPtr, Ymm, FeatureLength);
  1928. curPtr += FeatureLength / sizeof(intptr);
  1929. return Context;
  1930. }
  1931. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetIntRegisters(BfpThread* thread, intptr* outStackPtr, intptr* outIntRegs, int* inOutIntRegCount, BfpThreadResult* outResult)
  1932. {
  1933. CONTEXT ctx;
  1934. intptr* curPtr = outIntRegs;
  1935. CONTEXT* ctxPtr = NULL;
  1936. if (*inOutIntRegCount > 48)
  1937. ctxPtr = CaptureRegistersEx((HANDLE)thread, curPtr);
  1938. if (ctxPtr == NULL)
  1939. {
  1940. memset(&ctx, 0, sizeof(CONTEXT));
  1941. ctx.ContextFlags = CONTEXT_ALL;
  1942. BOOL success = ::GetThreadContext((HANDLE)thread, (CONTEXT*)&ctx);
  1943. if (!success)
  1944. {
  1945. int error = GetLastError();
  1946. OUTRESULT(BfpThreadResult_UnknownError);
  1947. return;
  1948. }
  1949. ctxPtr = &ctx;
  1950. DWORD lastError = GetLastError();
  1951. BF_ASSERT(success);
  1952. }
  1953. #ifdef BF32
  1954. * outStackPtr = (intptr)ctxPtr->Esp;
  1955. if (*inOutIntRegCount < (int)(curPtr - outIntRegs) + 7)
  1956. {
  1957. OUTRESULT(BfpThreadResult_InsufficientBuffer);
  1958. return;
  1959. }
  1960. #else
  1961. * outStackPtr = (intptr)ctxPtr->Rsp;
  1962. if (*inOutIntRegCount < (int)(curPtr - outIntRegs) + 48)
  1963. {
  1964. OUTRESULT(BfpThreadResult_InsufficientBuffer);
  1965. return;
  1966. }
  1967. #endif
  1968. OUTRESULT(BfpThreadResult_Ok);
  1969. if (outIntRegs == NULL)
  1970. return;
  1971. #ifdef BF32
  1972. * (curPtr++) = (intptr)ctxPtr->Eax;
  1973. *(curPtr++) = (intptr)ctxPtr->Ebx;
  1974. *(curPtr++) = (intptr)ctxPtr->Ecx;
  1975. *(curPtr++) = (intptr)ctxPtr->Edx;
  1976. *(curPtr++) = (intptr)ctxPtr->Esi;
  1977. *(curPtr++) = (intptr)ctxPtr->Edi;
  1978. *(curPtr++) = (intptr)ctxPtr->Ebp;
  1979. #else
  1980. * (curPtr++) = (intptr)ctxPtr->SegFs; // Testing
  1981. *(curPtr++) = (intptr)ctxPtr->Rax;
  1982. *(curPtr++) = (intptr)ctxPtr->Rbx;
  1983. *(curPtr++) = (intptr)ctxPtr->Rcx;
  1984. *(curPtr++) = (intptr)ctxPtr->Rdx;
  1985. *(curPtr++) = (intptr)ctxPtr->Rsi;
  1986. *(curPtr++) = (intptr)ctxPtr->Rdi;
  1987. *(curPtr++) = (intptr)ctxPtr->Rbp;
  1988. *(curPtr++) = (intptr)ctxPtr->R8;
  1989. *(curPtr++) = (intptr)ctxPtr->R9;
  1990. *(curPtr++) = (intptr)ctxPtr->R10;
  1991. *(curPtr++) = (intptr)ctxPtr->R11;
  1992. *(curPtr++) = (intptr)ctxPtr->R12;
  1993. *(curPtr++) = (intptr)ctxPtr->R13;
  1994. *(curPtr++) = (intptr)ctxPtr->R14;
  1995. *(curPtr++) = (intptr)ctxPtr->R15;
  1996. memcpy(curPtr, &ctxPtr->Xmm0, 16 * 16);
  1997. curPtr += (16 * 16) / sizeof(intptr);
  1998. #endif
  1999. * inOutIntRegCount = (int)(curPtr - outIntRegs);
  2000. }
  2001. struct BfpCritSect
  2002. {
  2003. CRITICAL_SECTION mCritSect;
  2004. };
  2005. BFP_EXPORT void BFP_CALLTYPE BfpThread_Sleep(int sleepMS)
  2006. {
  2007. ::Sleep(sleepMS);
  2008. }
  2009. BFP_EXPORT bool BFP_CALLTYPE BfpThread_Yield()
  2010. {
  2011. return ::SwitchToThread();
  2012. }
  2013. ///
  2014. struct BfpThreadInfo
  2015. {
  2016. intptr mStackBase;
  2017. intptr mStackLimit;
  2018. NT_TIB* mTeb;
  2019. };
  2020. BFP_EXPORT BfpThreadInfo* BFP_CALLTYPE BfpThreadInfo_Create()
  2021. {
  2022. BfpThreadInfo* threadInfo = new BfpThreadInfo();
  2023. threadInfo->mStackBase = 0;
  2024. threadInfo->mStackLimit = 0;
  2025. threadInfo->mTeb = (NT_TIB*)NtCurrentTeb();
  2026. return threadInfo;
  2027. }
  2028. BFP_EXPORT void BFP_CALLTYPE BfpThreadInfo_Release(BfpThreadInfo* threadInfo)
  2029. {
  2030. delete threadInfo;
  2031. }
  2032. static __declspec(thread) BfpThreadInfo gThreadStackInfo;
  2033. BFP_EXPORT void BFP_CALLTYPE BfpThreadInfo_GetStackInfo(BfpThreadInfo* threadInfo, intptr* outStackBase, int* outStackLimit, BfpThreadInfoFlags flags, BfpThreadResult* outResult)
  2034. {
  2035. if (threadInfo == NULL)
  2036. {
  2037. threadInfo = &gThreadStackInfo;
  2038. if (threadInfo->mTeb == NULL)
  2039. threadInfo->mTeb = (NT_TIB*)NtCurrentTeb();
  2040. }
  2041. if ((threadInfo->mStackBase == 0) || ((flags & BfpThreadInfoFlags_NoCache) != 0))
  2042. {
  2043. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  2044. // We subtract one page for our request. VirtualQuery rounds UP to the next page.
  2045. // Unfortunately, the stack grows down. If we're on the first page (last page in the
  2046. // VirtualAlloc), we'll be moved to the next page, which is off the stack! Note this
  2047. // doesn't work right for IA64 due to bigger pages.
  2048. void* currentAddr = (void*)((intptr_t)&stackInfo - 4096);
  2049. // Query for the current stack allocation information.
  2050. VirtualQuery(currentAddr, &stackInfo, sizeof(MEMORY_BASIC_INFORMATION));
  2051. threadInfo->mStackBase = (uintptr_t)threadInfo->mTeb->StackBase;
  2052. threadInfo->mStackLimit = (uintptr_t)stackInfo.AllocationBase;
  2053. }
  2054. *outStackBase = (intptr)threadInfo->mStackBase;
  2055. *outStackLimit = (int)(threadInfo->mStackBase - threadInfo->mStackLimit);
  2056. OUTRESULT(BfpThreadResult_Ok);
  2057. return;
  2058. }
  2059. ///
  2060. BFP_EXPORT BfpCritSect* BFP_CALLTYPE BfpCritSect_Create()
  2061. {
  2062. BfpCritSect* critSect = new BfpCritSect();
  2063. ::InitializeCriticalSection(&critSect->mCritSect);
  2064. return critSect;
  2065. }
  2066. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Release(BfpCritSect* critSect)
  2067. {
  2068. ::DeleteCriticalSection(&critSect->mCritSect);
  2069. delete critSect;
  2070. }
  2071. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Enter(BfpCritSect* critSect)
  2072. {
  2073. ::EnterCriticalSection(&critSect->mCritSect);
  2074. }
  2075. BFP_EXPORT bool BFP_CALLTYPE BfpCritSect_TryEnter(BfpCritSect* critSect, int waitMS)
  2076. {
  2077. if (waitMS == 0)
  2078. {
  2079. return ::TryEnterCriticalSection(&critSect->mCritSect);
  2080. }
  2081. else if (waitMS == -1)
  2082. {
  2083. BfpCritSect_Enter(critSect);
  2084. return true;
  2085. }
  2086. // This is a poor implementation. We should use a mutex if this is required
  2087. uint32 start = BFTickCount();
  2088. while ((int)(BFTickCount() - start) < waitMS)
  2089. {
  2090. if (::TryEnterCriticalSection(&critSect->mCritSect))
  2091. return true;
  2092. BfpThread_Yield();
  2093. }
  2094. return false;
  2095. }
  2096. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Leave(BfpCritSect* critSect)
  2097. {
  2098. ::LeaveCriticalSection(&critSect->mCritSect);
  2099. }
  2100. #define DWORD_TO_BFPTLS(val) ((BfpTLS*)(intptr)(val))
  2101. #define BFPTLS_TO_DWORD(val) ((DWORD)(intptr)(val))
  2102. struct BfpTLS;
  2103. BFP_EXPORT BfpTLS* BFP_CALLTYPE BfpTLS_Create(BfpTLSProc exitProc)
  2104. {
  2105. return DWORD_TO_BFPTLS(::FlsAlloc(exitProc));
  2106. }
  2107. BFP_EXPORT void BFP_CALLTYPE BfpTLS_Release(BfpTLS* tls)
  2108. {
  2109. ::FlsFree(BFPTLS_TO_DWORD(tls));
  2110. }
  2111. BFP_EXPORT void BFP_CALLTYPE BfpTLS_SetValue(BfpTLS* tls, void* value)
  2112. {
  2113. ::FlsSetValue(BFPTLS_TO_DWORD(tls), value);
  2114. }
  2115. BFP_EXPORT void* BFP_CALLTYPE BfpTLS_GetValue(BfpTLS* tls)
  2116. {
  2117. return ::FlsGetValue(BFPTLS_TO_DWORD(tls));
  2118. }
  2119. BFP_EXPORT BfpEvent* BFP_CALLTYPE BfpEvent_Create(BfpEventFlags flags)
  2120. {
  2121. BfpEvent* event = new BfpEvent();
  2122. ::InitializeCriticalSection(&event->mCritSect);
  2123. ::InitializeConditionVariable(&event->mCondVariable);
  2124. event->mSet = (flags & (BfpEventFlag_InitiallySet_Auto | BfpEventFlag_InitiallySet_Manual)) != 0;
  2125. event->mManualReset = (flags & BfpEventFlag_InitiallySet_Manual) != 0;
  2126. return event;
  2127. }
  2128. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Release(BfpEvent* event)
  2129. {
  2130. ::DeleteCriticalSection(&event->mCritSect);
  2131. delete event;
  2132. }
  2133. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Set(BfpEvent* event, bool requireManualReset)
  2134. {
  2135. ::EnterCriticalSection(&event->mCritSect);
  2136. event->mSet = true;
  2137. if (requireManualReset)
  2138. event->mManualReset = true;
  2139. if (event->mManualReset)
  2140. ::WakeAllConditionVariable(&event->mCondVariable);
  2141. else
  2142. ::WakeConditionVariable(&event->mCondVariable);
  2143. ::LeaveCriticalSection(&event->mCritSect);
  2144. }
  2145. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Reset(BfpEvent* event, BfpEventResult* outResult)
  2146. {
  2147. event->mSet = false;
  2148. event->mManualReset = false;
  2149. }
  2150. BFP_EXPORT bool BFP_CALLTYPE BfpEvent_WaitFor(BfpEvent* event, int waitMS)
  2151. {
  2152. ::EnterCriticalSection(&event->mCritSect);
  2153. while (!event->mSet)
  2154. {
  2155. if (!SleepConditionVariableCS(&event->mCondVariable, &event->mCritSect, waitMS))
  2156. {
  2157. if (GetLastError() == ERROR_TIMEOUT)
  2158. {
  2159. // Timeout
  2160. LeaveCriticalSection(&event->mCritSect);
  2161. return false;
  2162. }
  2163. }
  2164. }
  2165. if (!event->mManualReset)
  2166. event->mSet = false;
  2167. ::LeaveCriticalSection(&event->mCritSect);
  2168. return true;
  2169. }
  2170. struct BfpDynLib;
  2171. BFP_EXPORT BfpDynLib* BFP_CALLTYPE BfpDynLib_Load(const char* fileName)
  2172. {
  2173. UTF16String wPath = UTF8Decode(fileName);
  2174. return (BfpDynLib*)::LoadLibraryW(wPath.c_str());
  2175. }
  2176. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_Release(BfpDynLib* lib)
  2177. {
  2178. ::FreeLibrary((HMODULE)lib);
  2179. }
  2180. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_GetFilePath(BfpDynLib* lib, char* outPath, int* inOutPathSize, BfpLibResult* outResult)
  2181. {
  2182. Beefy::String path;
  2183. WCHAR cPath[4096];
  2184. ::GetModuleFileNameW((HMODULE)lib, cPath, 4096);
  2185. path = UTF8Encode(cPath);
  2186. TryStringOut(path, outPath, inOutPathSize, (BfpResult*)outResult);
  2187. }
  2188. BFP_EXPORT void* BFP_CALLTYPE BfpDynLib_GetProcAddress(BfpDynLib* lib, const char* name)
  2189. {
  2190. return ::GetProcAddress((HMODULE)lib, name);
  2191. }
  2192. struct BfpFindFileData;
  2193. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Create(const char* path, BfpFileResult* outResult)
  2194. {
  2195. UTF16String wPath = UTF8Decode(path);
  2196. if (!::CreateDirectoryW(wPath.c_str(), NULL))
  2197. {
  2198. int lastError = ::GetLastError();
  2199. switch (lastError)
  2200. {
  2201. case ERROR_ALREADY_EXISTS:
  2202. OUTRESULT(BfpFileResult_AlreadyExists);
  2203. break;
  2204. case ERROR_PATH_NOT_FOUND:
  2205. OUTRESULT(BfpFileResult_NotFound);
  2206. break;
  2207. default:
  2208. OUTRESULT(BfpFileResult_UnknownError);
  2209. break;
  2210. }
  2211. }
  2212. else
  2213. {
  2214. OUTRESULT(BfpFileResult_Ok);
  2215. }
  2216. }
  2217. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Rename(const char* oldName, const char* newName, BfpFileResult* outResult)
  2218. {
  2219. UTF16String wOldPath = UTF8Decode(oldName);
  2220. UTF16String wNewPath = UTF8Decode(newName);
  2221. if (!::MoveFileW(wOldPath.c_str(), wNewPath.c_str()))
  2222. {
  2223. int err = ::GetLastError();
  2224. switch (err)
  2225. {
  2226. case ERROR_ALREADY_EXISTS:
  2227. OUTRESULT(BfpFileResult_AlreadyExists);
  2228. break;
  2229. case ERROR_FILE_NOT_FOUND:
  2230. case ERROR_PATH_NOT_FOUND:
  2231. OUTRESULT(BfpFileResult_NotFound);
  2232. break;
  2233. default:
  2234. OUTRESULT(BfpFileResult_UnknownError);
  2235. break;
  2236. }
  2237. }
  2238. else
  2239. {
  2240. OUTRESULT(BfpFileResult_Ok);
  2241. }
  2242. }
  2243. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Delete(const char* path, BfpFileResult* outResult)
  2244. {
  2245. UTF16String wPath = UTF8Decode(path);
  2246. if (!::RemoveDirectoryW(wPath.c_str()))
  2247. {
  2248. switch (GetLastError())
  2249. {
  2250. case ERROR_FILE_NOT_FOUND:
  2251. OUTRESULT(BfpFileResult_NotFound);
  2252. break;
  2253. case ERROR_DIR_NOT_EMPTY:
  2254. OUTRESULT(BfpFileResult_NotEmpty);
  2255. break;
  2256. default:
  2257. OUTRESULT(BfpFileResult_UnknownError);
  2258. break;
  2259. }
  2260. }
  2261. else
  2262. {
  2263. OUTRESULT(BfpFileResult_Ok);
  2264. }
  2265. }
  2266. BFP_EXPORT bool BFP_CALLTYPE BfpDirectory_Exists(const char* path)
  2267. {
  2268. WIN32_FIND_DATAW findData;
  2269. UTF16String wpath = UTF8Decode(path);
  2270. if (wpath.length() > 0)
  2271. {
  2272. uint16& endC = wpath[wpath.length() - 1];
  2273. if ((endC == '\\') || (endC == '/'))
  2274. {
  2275. wpath.pop_back();
  2276. }
  2277. }
  2278. HANDLE handleVal = FindFirstFileW(wpath.c_str(), &findData);
  2279. if (handleVal == INVALID_HANDLE_VALUE)
  2280. return false;
  2281. FindClose(handleVal);
  2282. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  2283. }
  2284. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetSysDirectory(BfpSysDirectoryKind sysDirKind, char* outPath, int* inOutPathLen, BfpFileResult* outResult)
  2285. {
  2286. String path;
  2287. auto _GetKnownFolder = [&](REFKNOWNFOLDERID rfid)
  2288. {
  2289. PWSTR pStrPtr;
  2290. int result = SHGetKnownFolderPath(rfid, KF_FLAG_CREATE | KF_FLAG_SIMPLE_IDLIST, NULL, &pStrPtr);
  2291. if (result != 0)
  2292. {
  2293. OUTRESULT(BfpFileResult_UnknownError);
  2294. return;
  2295. }
  2296. path = UTF8Encode(pStrPtr);
  2297. CoTaskMemFree(pStrPtr);
  2298. TryStringOut(path, outPath, inOutPathLen, (BfpResult*)outResult);
  2299. };
  2300. switch (sysDirKind)
  2301. {
  2302. case BfpSysDirectoryKind_Default:
  2303. _GetKnownFolder(FOLDERID_Desktop);
  2304. break;
  2305. case BfpSysDirectoryKind_Home:
  2306. _GetKnownFolder(FOLDERID_Profile);
  2307. break;
  2308. case BfpSysDirectoryKind_System:
  2309. _GetKnownFolder(FOLDERID_System);
  2310. break;
  2311. case BfpSysDirectoryKind_Desktop:
  2312. _GetKnownFolder(FOLDERID_Desktop);
  2313. return;
  2314. case BfpSysDirectoryKind_Desktop_Common:
  2315. _GetKnownFolder(FOLDERID_PublicDesktop);
  2316. return;
  2317. case BfpSysDirectoryKind_AppData_Local:
  2318. _GetKnownFolder(FOLDERID_LocalAppData);
  2319. return;
  2320. case BfpSysDirectoryKind_AppData_LocalLow:
  2321. _GetKnownFolder(FOLDERID_LocalAppDataLow);
  2322. return;
  2323. case BfpSysDirectoryKind_AppData_Roaming:
  2324. _GetKnownFolder(FOLDERID_RoamingAppData);
  2325. return;
  2326. case BfpSysDirectoryKind_Programs:
  2327. _GetKnownFolder(FOLDERID_Programs);
  2328. return;
  2329. case BfpSysDirectoryKind_Programs_Common:
  2330. _GetKnownFolder(FOLDERID_CommonPrograms);
  2331. return;
  2332. case BfpSysDirectoryKind_Documents:
  2333. _GetKnownFolder(FOLDERID_Documents);
  2334. return;
  2335. }
  2336. TryStringOut(path, outPath, inOutPathLen, (BfpResult*)outResult);
  2337. }
  2338. //////////////////////////////////////////////////////////////////////////
  2339. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_Create(const char* path, BfpFileCreateKind createKind, BfpFileCreateFlags createFlags, BfpFileAttributes createdFileAttrs, BfpFileResult* outResult)
  2340. {
  2341. UTF16String wPath = UTF8Decode(path);
  2342. //OVERLAPPED
  2343. if ((createFlags & BfpFileCreateFlag_Pipe) != 0)
  2344. {
  2345. String pipeName = StrFormat("\\\\%s\\pipe\\%s", ".", path);
  2346. wPath = UTF8Decode(pipeName);
  2347. if ((createKind == BfpFileCreateKind_CreateIfNotExists) ||
  2348. (createKind == BfpFileCreateKind_CreateAlways))
  2349. {
  2350. bool isOverlapped = false;
  2351. DWORD openMode = 0;
  2352. DWORD desiredAccess = 0;
  2353. if ((createFlags & BfpFileCreateFlag_Read) != 0)
  2354. openMode |= PIPE_ACCESS_INBOUND;
  2355. if ((createFlags & BfpFileCreateFlag_Write) != 0)
  2356. openMode |= PIPE_ACCESS_OUTBOUND;
  2357. if (createKind == BfpFileCreateKind_CreateIfNotExists)
  2358. openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
  2359. int pipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
  2360. if ((createFlags & BfpFileCreateFlag_AllowTimeouts) != 0)
  2361. {
  2362. openMode |= FILE_FLAG_OVERLAPPED;
  2363. isOverlapped = true;
  2364. }
  2365. else if ((createFlags & BfpFileCreateFlag_NonBlocking) != 0)
  2366. pipeMode |= PIPE_NOWAIT;
  2367. HANDLE handle = ::CreateNamedPipeW(wPath.c_str(), openMode, pipeMode, PIPE_UNLIMITED_INSTANCES, 8192, 8192, 0, NULL);
  2368. if (handle == INVALID_HANDLE_VALUE)
  2369. {
  2370. if (outResult != NULL)
  2371. {
  2372. int lastError = GetLastError();
  2373. switch (lastError)
  2374. {
  2375. default:
  2376. *outResult = BfpFileResult_UnknownError;
  2377. break;
  2378. }
  2379. }
  2380. return NULL;
  2381. }
  2382. OUTRESULT(BfpFileResult_Ok);
  2383. BfpFile* bfpFile = new BfpFile();
  2384. bfpFile->mHandle = handle;
  2385. bfpFile->mIsPipe = true;
  2386. if (isOverlapped)
  2387. {
  2388. bfpFile->mAsyncData = new BfpAsyncData();
  2389. }
  2390. return bfpFile;
  2391. }
  2392. }
  2393. DWORD desiredAccess = 0;
  2394. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  2395. desiredAccess |= FILE_APPEND_DATA;
  2396. else
  2397. {
  2398. if ((createFlags & BfpFileCreateFlag_Read) != 0)
  2399. desiredAccess |= GENERIC_READ;
  2400. if ((createFlags & BfpFileCreateFlag_Write) != 0)
  2401. desiredAccess |= GENERIC_WRITE;
  2402. }
  2403. DWORD shareMode = 0;
  2404. if ((createFlags & BfpFileCreateFlag_ShareRead) != 0)
  2405. shareMode |= FILE_SHARE_READ;
  2406. if ((createFlags & BfpFileCreateFlag_ShareWrite) != 0)
  2407. shareMode |= FILE_SHARE_WRITE;
  2408. if ((createFlags & BfpFileCreateFlag_ShareDelete) != 0)
  2409. shareMode |= FILE_SHARE_DELETE;
  2410. DWORD creationDisposition = 0;
  2411. if (createKind == BfpFileCreateKind_CreateAlways)
  2412. {
  2413. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  2414. creationDisposition = OPEN_ALWAYS;
  2415. else
  2416. creationDisposition = CREATE_ALWAYS;
  2417. }
  2418. else if (createKind == BfpFileCreateKind_CreateIfNotExists)
  2419. {
  2420. creationDisposition = CREATE_NEW;
  2421. }
  2422. else if (createKind == BfpFileCreateKind_OpenAlways)
  2423. {
  2424. creationDisposition = OPEN_ALWAYS;
  2425. }
  2426. else
  2427. {
  2428. creationDisposition = OPEN_EXISTING;
  2429. }
  2430. DWORD attributes = 0;
  2431. if ((createdFileAttrs & (BfpFileAttribute_Directory | BfpFileAttribute_SymLink | BfpFileAttribute_Device)) != 0)
  2432. {
  2433. if (outResult != NULL)
  2434. *outResult = BfpFileResult_InvalidParameter;
  2435. return NULL;
  2436. }
  2437. attributes = FileAttributes_WinToBFP(createdFileAttrs);
  2438. if ((createFlags & BfpFileCreateFlag_WriteThrough) != 0)
  2439. desiredAccess |= FILE_FLAG_WRITE_THROUGH;
  2440. if ((createFlags & BfpFileCreateFlag_DeleteOnClose) != 0)
  2441. desiredAccess |= FILE_FLAG_DELETE_ON_CLOSE;
  2442. if ((createFlags & BfpFileCreateFlag_NoBuffering) != 0)
  2443. desiredAccess |= FILE_FLAG_NO_BUFFERING;
  2444. HANDLE handle = ::CreateFileW(wPath.c_str(), desiredAccess, shareMode, NULL, creationDisposition, attributes, NULL);
  2445. if (handle == INVALID_HANDLE_VALUE)
  2446. {
  2447. if (outResult != NULL)
  2448. {
  2449. int lastError = GetLastError();
  2450. switch (lastError)
  2451. {
  2452. case ERROR_SHARING_VIOLATION:
  2453. *outResult = BfpFileResult_ShareError;
  2454. break;
  2455. case ERROR_FILE_NOT_FOUND:
  2456. *outResult = BfpFileResult_NotFound;
  2457. break;
  2458. default:
  2459. *outResult = BfpFileResult_UnknownError;
  2460. break;
  2461. }
  2462. }
  2463. return NULL;
  2464. }
  2465. OUTRESULT(BfpFileResult_Ok);
  2466. BfpFile* bfpFile = new BfpFile();
  2467. bfpFile->mHandle = handle;
  2468. return bfpFile;
  2469. }
  2470. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_GetStd(BfpFileStdKind kind, BfpFileResult* outResult)
  2471. {
  2472. HANDLE h = INVALID_HANDLE_VALUE;
  2473. switch (kind)
  2474. {
  2475. case BfpFileStdKind_StdOut:
  2476. h = ::GetStdHandle(STD_OUTPUT_HANDLE);
  2477. break;
  2478. case BfpFileStdKind_StdError:
  2479. h = ::GetStdHandle(STD_ERROR_HANDLE);
  2480. break;
  2481. case BfpFileStdKind_StdIn:
  2482. h = ::GetStdHandle(STD_INPUT_HANDLE);
  2483. break;
  2484. }
  2485. if ((h == INVALID_HANDLE_VALUE) || (h == 0))
  2486. {
  2487. OUTRESULT(BfpFileResult_NotFound);
  2488. return NULL;
  2489. }
  2490. BfpFile* bfpFile = new BfpFile();
  2491. bfpFile->mHandle = h;
  2492. bfpFile->mIsStd = true;
  2493. return bfpFile;
  2494. }
  2495. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_GetSystemHandle(BfpFile* file)
  2496. {
  2497. return (intptr)file->mHandle;
  2498. }
  2499. BFP_EXPORT void BFP_CALLTYPE BfpFile_Release(BfpFile* file)
  2500. {
  2501. if ((file->mHandle != INVALID_HANDLE_VALUE) && (!file->mIsStd))
  2502. ::CloseHandle(file->mHandle);
  2503. delete file;
  2504. }
  2505. BFP_EXPORT void BFP_CALLTYPE BfpFile_Close(BfpFile* file, BfpFileResult* outResult)
  2506. {
  2507. if (file->mHandle != INVALID_HANDLE_VALUE)
  2508. {
  2509. ::CloseHandle(file->mHandle);
  2510. file->mHandle = INVALID_HANDLE_VALUE;
  2511. OUTRESULT(BfpFileResult_Ok);
  2512. }
  2513. else
  2514. OUTRESULT(BfpFileResult_UnknownError);
  2515. }
  2516. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Write(BfpFile* file, const void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  2517. {
  2518. DWORD bytesWritten = 0;
  2519. if (::WriteFile(file->mHandle, buffer, (uint32)size, &bytesWritten, NULL))
  2520. {
  2521. if (outResult != NULL)
  2522. {
  2523. if (bytesWritten != size)
  2524. *outResult = BfpFileResult_PartialData;
  2525. else
  2526. *outResult = BfpFileResult_Ok;
  2527. }
  2528. return bytesWritten;
  2529. }
  2530. if (outResult != NULL)
  2531. {
  2532. switch (GetLastError())
  2533. {
  2534. default:
  2535. *outResult = BfpFileResult_UnknownError;
  2536. break;
  2537. }
  2538. }
  2539. return bytesWritten;
  2540. }
  2541. struct OverlappedReadResult : OVERLAPPED
  2542. {
  2543. BfpFile* mFile;
  2544. intptr mBytesRead;
  2545. DWORD mErrorCode;
  2546. };
  2547. static void WINAPI OverlappedReadComplete(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
  2548. {
  2549. OverlappedReadResult* readResult = (OverlappedReadResult*)lpOverlapped;
  2550. readResult->mErrorCode = dwErrorCode;
  2551. readResult->mBytesRead = dwNumberOfBytesTransfered;
  2552. readResult->mFile->mAsyncData->SetEvent();
  2553. }
  2554. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Read(BfpFile* file, void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  2555. {
  2556. if (timeoutMS != -1)
  2557. {
  2558. if (file->mAsyncData == NULL)
  2559. {
  2560. OUTRESULT(BfpFileResult_InvalidParameter);
  2561. return 0;
  2562. }
  2563. while (true)
  2564. {
  2565. OverlappedReadResult overlapped;
  2566. memset(&overlapped, 0, sizeof(OverlappedReadResult));
  2567. overlapped.mFile = file;
  2568. //TODO: this doesn't set file stream location. It only works for streams like pipes, sockets, etc
  2569. if (::ReadFileEx(file->mHandle, buffer, (uint32)size, &overlapped, OverlappedReadComplete))
  2570. {
  2571. if (!file->mAsyncData->WaitAndResetEvent(timeoutMS))
  2572. {
  2573. ::CancelIoEx(file->mHandle, &overlapped);
  2574. // There's a chance we completed before we were cancelled -- check on that
  2575. if (!file->mAsyncData->WaitAndResetEvent(0))
  2576. {
  2577. OUTRESULT(BfpFileResult_Timeout);
  2578. return 0;
  2579. }
  2580. }
  2581. if (overlapped.mErrorCode == 0)
  2582. {
  2583. }
  2584. else if (overlapped.mErrorCode == ERROR_OPERATION_ABORTED)
  2585. {
  2586. OUTRESULT(BfpFileResult_Timeout);
  2587. return 0;
  2588. }
  2589. }
  2590. else
  2591. {
  2592. int lastError = ::GetLastError();
  2593. if (lastError == ERROR_PIPE_LISTENING)
  2594. {
  2595. overlapped.hEvent = file->mAsyncData->mEvent;
  2596. if (!::ConnectNamedPipe(file->mHandle, &overlapped))
  2597. {
  2598. int lastError = ::GetLastError();
  2599. if (lastError == ERROR_IO_PENDING)
  2600. {
  2601. if (!file->mAsyncData->WaitAndResetEvent(timeoutMS))
  2602. {
  2603. ::CancelIoEx(file->mHandle, &overlapped);
  2604. // Clear event set by CancelIoEx
  2605. file->mAsyncData->WaitAndResetEvent(0);
  2606. OUTRESULT(BfpFileResult_Timeout);
  2607. return 0;
  2608. }
  2609. }
  2610. }
  2611. // Now we have a connection, so retry the read...
  2612. continue;
  2613. }
  2614. else
  2615. {
  2616. OUTRESULT(BfpFileResult_UnknownError);
  2617. return 0;
  2618. }
  2619. }
  2620. OUTRESULT(BfpFileResult_Ok);
  2621. return overlapped.mBytesRead;
  2622. }
  2623. }
  2624. DWORD bytesRead = 0;
  2625. if (::ReadFile(file->mHandle, buffer, (uint32)size, &bytesRead, NULL))
  2626. {
  2627. if (bytesRead != size)
  2628. OUTRESULT(BfpFileResult_PartialData);
  2629. else
  2630. OUTRESULT(BfpFileResult_Ok);
  2631. return bytesRead;
  2632. }
  2633. int lastError = ::GetLastError();
  2634. switch (lastError)
  2635. {
  2636. case ERROR_BROKEN_PIPE: // Just an EOF
  2637. OUTRESULT(BfpFileResult_Ok);
  2638. break;
  2639. default:
  2640. OUTRESULT(BfpFileResult_UnknownError);
  2641. break;
  2642. }
  2643. return bytesRead;
  2644. }
  2645. BFP_EXPORT void BFP_CALLTYPE BfpFile_Flush(BfpFile* file)
  2646. {
  2647. ::FlushFileBuffers(file->mHandle);
  2648. }
  2649. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_GetFileSize(BfpFile* file)
  2650. {
  2651. LARGE_INTEGER largeInteger;
  2652. largeInteger.QuadPart = 0;
  2653. ::GetFileSizeEx(file->mHandle, &largeInteger);
  2654. return largeInteger.QuadPart;
  2655. }
  2656. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_Seek(BfpFile* file, int64 offset, BfpFileSeekKind seekKind)
  2657. {
  2658. DWORD moveMethod;
  2659. if (seekKind == BfpFileSeekKind_Absolute)
  2660. moveMethod = FILE_BEGIN;
  2661. else if (seekKind == BfpFileSeekKind_Relative)
  2662. moveMethod = FILE_CURRENT;
  2663. else
  2664. moveMethod = FILE_END;
  2665. LARGE_INTEGER liOffset;
  2666. liOffset.QuadPart = offset;
  2667. LARGE_INTEGER newPos;
  2668. newPos.QuadPart = 0;
  2669. ::SetFilePointerEx(file->mHandle, liOffset, &newPos, moveMethod);
  2670. return newPos.QuadPart;
  2671. }
  2672. BFP_EXPORT void BFP_CALLTYPE BfpFile_Truncate(BfpFile* file, BfpFileResult* outResult)
  2673. {
  2674. if (!SetEndOfFile(file->mHandle))
  2675. {
  2676. OUTRESULT(BfpFileResult_UnknownError);
  2677. return;
  2678. }
  2679. OUTRESULT(BfpFileResult_Ok);
  2680. }
  2681. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFile_GetTime_LastWrite(const char* path)
  2682. {
  2683. UTF16String wPath = UTF8Decode(path);
  2684. BfpTimeStamp lastWriteTime = 0;
  2685. GetFileInfo(path, &lastWriteTime, NULL);
  2686. return lastWriteTime;
  2687. }
  2688. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFile_GetAttributes(const char* path, BfpFileResult* outResult)
  2689. {
  2690. uint32 fileAttributes;
  2691. GetFileInfo(path, NULL, &fileAttributes);
  2692. return FileAttributes_WinToBFP(fileAttributes);
  2693. }
  2694. BFP_EXPORT void BFP_CALLTYPE BfpFile_SetAttributes(const char* path, BfpFileAttributes attribs, BfpFileResult* outResult)
  2695. {
  2696. if (!::SetFileAttributesW(UTF8Decode(path).c_str(), FileAttributes_BFPToWin(attribs)))
  2697. {
  2698. OUTRESULT(BfpFileResult_UnknownError);
  2699. return;
  2700. }
  2701. OUTRESULT(BfpFileResult_Ok);
  2702. }
  2703. BFP_EXPORT void BFP_CALLTYPE BfpFile_Copy(const char* oldName, const char* newName, BfpFileCopyKind copyKind, BfpFileResult* outResult)
  2704. {
  2705. if (copyKind == BfpFileCopyKind_IfNewer)
  2706. {
  2707. BfpTimeStamp fromTime = 0;
  2708. GetFileInfo(oldName, &fromTime, NULL);
  2709. BfpTimeStamp toTime = 0;
  2710. GetFileInfo(newName, &toTime, NULL);
  2711. if ((toTime != 0) && (toTime >= fromTime))
  2712. {
  2713. OUTRESULT(BfpFileResult_Ok);
  2714. return;
  2715. }
  2716. }
  2717. UTF16String wOldPath = UTF8Decode(oldName);
  2718. UTF16String wNewPath = UTF8Decode(newName);
  2719. if (!::CopyFileW(wOldPath.c_str(), wNewPath.c_str(), copyKind == BfpFileCopyKind_IfNotExists))
  2720. {
  2721. switch (::GetLastError())
  2722. {
  2723. case ERROR_ALREADY_EXISTS:
  2724. OUTRESULT(BfpFileResult_AlreadyExists);
  2725. break;
  2726. case ERROR_PATH_NOT_FOUND:
  2727. OUTRESULT(BfpFileResult_NotFound);
  2728. break;
  2729. default:
  2730. OUTRESULT(BfpFileResult_UnknownError);
  2731. break;
  2732. }
  2733. }
  2734. else
  2735. {
  2736. OUTRESULT(BfpFileResult_Ok);
  2737. }
  2738. }
  2739. BFP_EXPORT void BFP_CALLTYPE BfpFile_Rename(const char* oldName, const char* newName, BfpFileResult* outResult)
  2740. {
  2741. UTF16String wOldPath = UTF8Decode(oldName);
  2742. UTF16String wNewPath = UTF8Decode(newName);
  2743. if (!::MoveFileW(wOldPath.c_str(), wNewPath.c_str()))
  2744. {
  2745. switch (::GetLastError())
  2746. {
  2747. case ERROR_ALREADY_EXISTS:
  2748. OUTRESULT(BfpFileResult_AlreadyExists);
  2749. break;
  2750. case ERROR_PATH_NOT_FOUND:
  2751. OUTRESULT(BfpFileResult_NotFound);
  2752. break;
  2753. default:
  2754. OUTRESULT(BfpFileResult_UnknownError);
  2755. break;
  2756. }
  2757. }
  2758. else
  2759. {
  2760. OUTRESULT(BfpFileResult_Ok);
  2761. }
  2762. }
  2763. BFP_EXPORT void BFP_CALLTYPE BfpFile_Delete(const char* path, BfpFileResult* outResult)
  2764. {
  2765. if (!::DeleteFileW(UTF8Decode(path).c_str()))
  2766. {
  2767. int lastError = GetLastError();
  2768. switch (lastError)
  2769. {
  2770. case ERROR_FILE_NOT_FOUND:
  2771. case ERROR_PATH_NOT_FOUND:
  2772. OUTRESULT(BfpFileResult_NotFound);
  2773. break;
  2774. default:
  2775. OUTRESULT(BfpFileResult_UnknownError);
  2776. break;
  2777. }
  2778. }
  2779. else
  2780. OUTRESULT(BfpFileResult_Ok);
  2781. }
  2782. BFP_EXPORT bool BFP_CALLTYPE BfpFile_Exists(const char* path)
  2783. {
  2784. WIN32_FIND_DATAW findData;
  2785. HANDLE handleVal = FindFirstFileW(UTF8Decode(path).c_str(), &findData);
  2786. if (handleVal == INVALID_HANDLE_VALUE)
  2787. return false;
  2788. FindClose(handleVal);
  2789. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
  2790. }
  2791. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempPath(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  2792. {
  2793. WCHAR wStr[4096];
  2794. ::GetTempPathW(4096, wStr);
  2795. String str = UTF8Encode(wStr);
  2796. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  2797. }
  2798. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempFileName(char* outName, int* inOutNameSize, BfpFileResult* outResult)
  2799. {
  2800. WCHAR wPath[4096];
  2801. wPath[0] = 0;
  2802. ::GetTempPathW(4096, wPath);
  2803. WCHAR wFileName[4096];
  2804. wFileName[0] = 0;
  2805. GetTempFileNameW(wPath, L"tmp", 0, wFileName);
  2806. String str = UTF8Encode(wFileName);
  2807. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  2808. }
  2809. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetFullPath(const char* inPath, char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  2810. {
  2811. WCHAR wPath[4096];
  2812. wPath[0] = 0;
  2813. GetFullPathNameW(UTF8Decode(inPath).c_str(), 4096, wPath, NULL);
  2814. String str = UTF8Encode(wPath);
  2815. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  2816. }
  2817. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetActualPath(const char* inPathC, char* outPathC, int* inOutPathSize, BfpFileResult* outResult)
  2818. {
  2819. String inPath = inPathC;
  2820. String outPath;
  2821. // Check for '/../' backtracking - handle those first
  2822. {
  2823. int i = 0;
  2824. int32 lastComponentStart = -1;
  2825. String subName;
  2826. while (i < inPath.mLength)
  2827. {
  2828. // skip until path separator
  2829. while ((i < inPath.mLength) && (inPath[i] != DIR_SEP_CHAR) && (inPath[i] != DIR_SEP_CHAR_ALT))
  2830. ++i;
  2831. if (lastComponentStart != -1)
  2832. {
  2833. if ((i - lastComponentStart == 2) && (inPath[lastComponentStart] == '.') && (inPath[lastComponentStart + 1] == '.'))
  2834. {
  2835. // Backtrack
  2836. while ((lastComponentStart > 0) &&
  2837. ((inPath[lastComponentStart - 1] == DIR_SEP_CHAR) || (inPath[lastComponentStart - 1] == DIR_SEP_CHAR_ALT)))
  2838. lastComponentStart--;
  2839. while ((lastComponentStart > 0) && (inPath[lastComponentStart - 1] != DIR_SEP_CHAR) && (inPath[lastComponentStart - 1] != DIR_SEP_CHAR_ALT))
  2840. lastComponentStart--;
  2841. inPath.Remove(lastComponentStart, i - lastComponentStart + 1);
  2842. i = lastComponentStart;
  2843. continue;
  2844. }
  2845. else if ((i - lastComponentStart == 1) && (inPath[lastComponentStart] == '.'))
  2846. {
  2847. inPath.Remove(lastComponentStart, i - lastComponentStart + 1);
  2848. i = lastComponentStart;
  2849. continue;
  2850. }
  2851. }
  2852. ++i;
  2853. // Ignore multiple slashes in a row
  2854. while ((i < inPath.mLength) && ((inPath[i] == DIR_SEP_CHAR) || (inPath[i] == DIR_SEP_CHAR_ALT)))
  2855. ++i;
  2856. lastComponentStart = i;
  2857. }
  2858. }
  2859. int32 i = 0;
  2860. // for network paths (\\server\share\RestOfPath), getting the display
  2861. // name mangles it into unusable form (e.g. "\\server\share" turns
  2862. // into "share on server (server)"). So detect this case and just skip
  2863. // up to two path components
  2864. int length = (int)inPath.length();
  2865. if (length >= 2 && inPath[0] == DIR_SEP_CHAR && inPath[1] == DIR_SEP_CHAR)
  2866. {
  2867. int skippedCount = 0;
  2868. i = 2; // start after '\\'
  2869. while (i < length && skippedCount < 2)
  2870. {
  2871. if (inPath[i] == DIR_SEP_CHAR)
  2872. ++skippedCount;
  2873. ++i;
  2874. }
  2875. outPath.Append(inPath.c_str(), i);
  2876. }
  2877. // for drive names, just add it uppercased
  2878. else if (length >= 2 && inPath[1] == ':')
  2879. {
  2880. outPath.Append(toupper(inPath[0]));
  2881. outPath.Append(':');
  2882. if ((length >= 3) &&
  2883. ((inPath[2] == DIR_SEP_CHAR) || (inPath[2] == DIR_SEP_CHAR_ALT)))
  2884. {
  2885. outPath.Append(DIR_SEP_CHAR);
  2886. i = 3; // start after drive, colon and separator
  2887. }
  2888. else
  2889. {
  2890. i = 2; // start after drive and colon
  2891. }
  2892. }
  2893. if ((i == 0) && (length >= 1) &&
  2894. ((inPath[0] == DIR_SEP_CHAR) || (inPath[1] == DIR_SEP_CHAR_ALT)))
  2895. {
  2896. i++; // start after initial slash
  2897. outPath.Append(DIR_SEP_CHAR);
  2898. }
  2899. int32 lastComponentStart = i;
  2900. bool addSeparator = false;
  2901. String subName;
  2902. while (i < length)
  2903. {
  2904. // skip until path separator
  2905. while ((i < length) && (inPath[i] != DIR_SEP_CHAR) && (inPath[i] != DIR_SEP_CHAR_ALT))
  2906. ++i;
  2907. if (addSeparator)
  2908. outPath.Append(DIR_SEP_CHAR);
  2909. SHFILEINFOW info = { 0 };
  2910. subName.Clear();
  2911. subName = inPath.Substring(0, i);
  2912. for (int j = 0; j < (int)subName.length(); j++)
  2913. if (subName[j] == DIR_SEP_CHAR_ALT)
  2914. subName[j] = DIR_SEP_CHAR;
  2915. info.szDisplayName[0] = 0;
  2916. int32 size = (int32)sizeof(SHFILEINFOW);
  2917. WIN32_FIND_DATAW findData;
  2918. HANDLE handleVal = FindFirstFileW(UTF8Decode(subName).c_str(), &findData);
  2919. if (handleVal != INVALID_HANDLE_VALUE)
  2920. {
  2921. outPath.Append(UTF8Encode(findData.cFileName));
  2922. FindClose(handleVal);
  2923. }
  2924. else
  2925. {
  2926. // most likely file does not exist.
  2927. // So just append original path name component.
  2928. outPath.Append(inPath.Substring(lastComponentStart, i - lastComponentStart));
  2929. }
  2930. ++i;
  2931. // Ignore multiple slashes in a row
  2932. while ((i < length) && ((inPath[i] == DIR_SEP_CHAR) || (inPath[i] == DIR_SEP_CHAR_ALT)))
  2933. ++i;
  2934. lastComponentStart = i;
  2935. addSeparator = true;
  2936. }
  2937. TryStringOut(outPath, outPathC, inOutPathSize, (BfpResult*)outResult);
  2938. }
  2939. // BfpFindFileData
  2940. struct BfpFindFileData
  2941. {
  2942. BfpFindFileFlags mFlags;
  2943. WIN32_FIND_DATA mFindData;
  2944. Beefy::String mWildcard;
  2945. HANDLE mHandle;
  2946. };
  2947. #define HANDLE_TO_BFPFINDFILEDATA(handle) ((BfpFindFileData*)(handle))
  2948. #define BFPFINDFILEDATA_TO_HANDLE(findData) ((HANDLE)(findData))
  2949. static bool BfpFindFileData_CheckFilter(BfpFindFileData* findData)
  2950. {
  2951. bool isDir = (findData->mFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  2952. if (isDir)
  2953. {
  2954. if ((findData->mFlags & BfpFindFileFlag_Directories) == 0)
  2955. return false;
  2956. if ((wcscmp(findData->mFindData.cFileName, L".") == 0) || (wcscmp(findData->mFindData.cFileName, L"..") == 0))
  2957. return false;
  2958. }
  2959. else
  2960. {
  2961. if ((findData->mFlags & BfpFindFileFlag_Files) == 0)
  2962. return false;
  2963. }
  2964. Beefy::String fileName = UTF8Encode(findData->mFindData.cFileName);
  2965. if (!wc_match(findData->mWildcard.c_str(), fileName.c_str()))
  2966. return false;
  2967. return true;
  2968. }
  2969. BFP_EXPORT BfpFindFileData* BFP_CALLTYPE BfpFindFileData_FindFirstFile(const char* path, BfpFindFileFlags flags, BfpFileResult* outResult)
  2970. {
  2971. Beefy::String findStr = path;
  2972. Beefy::String wildcard;
  2973. int lastSlashPos = std::max((int)findStr.LastIndexOf('/'), (int)findStr.LastIndexOf('\\'));
  2974. if (lastSlashPos != -1)
  2975. {
  2976. wildcard = findStr.Substring(lastSlashPos + 1);
  2977. findStr = findStr.Substring(0, lastSlashPos + 1);
  2978. findStr.Append("*");
  2979. }
  2980. if (wildcard == "*.*")
  2981. wildcard = "*";
  2982. BfpFindFileData* findData = new BfpFindFileData();
  2983. findData->mFlags = flags;
  2984. findData->mWildcard = wildcard;
  2985. FINDEX_SEARCH_OPS searchOps;
  2986. if ((flags & BfpFindFileFlag_Files) == 0)
  2987. searchOps = FindExSearchLimitToDirectories;
  2988. else
  2989. searchOps = FindExSearchNameMatch;
  2990. UTF16String wPath = UTF8Decode(findStr);
  2991. findData->mHandle = ::FindFirstFileExW(wPath.c_str(), FindExInfoBasic, &findData->mFindData, searchOps, NULL, 0);
  2992. if (findData->mHandle == INVALID_HANDLE_VALUE)
  2993. {
  2994. if (outResult != NULL)
  2995. {
  2996. switch (GetLastError())
  2997. {
  2998. default:
  2999. *outResult = BfpFileResult_UnknownError;
  3000. break;
  3001. }
  3002. }
  3003. delete findData;
  3004. return NULL;
  3005. }
  3006. if (!BfpFindFileData_CheckFilter(findData))
  3007. {
  3008. if (!BfpFindFileData_FindNextFile(findData))
  3009. {
  3010. ::FindClose(findData->mHandle);
  3011. if (outResult != NULL)
  3012. *outResult = BfpFileResult_NoResults;
  3013. delete findData;
  3014. return NULL;
  3015. }
  3016. }
  3017. OUTRESULT(BfpFileResult_Ok);
  3018. return findData;
  3019. }
  3020. BFP_EXPORT bool BFP_CALLTYPE BfpFindFileData_FindNextFile(BfpFindFileData* findData)
  3021. {
  3022. while (true)
  3023. {
  3024. if (!::FindNextFileW(findData->mHandle, &findData->mFindData))
  3025. return false;
  3026. if (BfpFindFileData_CheckFilter(findData))
  3027. return true;
  3028. }
  3029. }
  3030. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_GetFileName(BfpFindFileData* findData, char* outName, int* inOutNameSize, BfpFileResult* outResult)
  3031. {
  3032. String name = UTF8Encode(findData->mFindData.cFileName);
  3033. TryStringOut(name, outName, inOutNameSize, (BfpResult*)outResult);
  3034. }
  3035. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_LastWrite(BfpFindFileData* findData)
  3036. {
  3037. return *(BfpTimeStamp*)&findData->mFindData.ftLastWriteTime;
  3038. }
  3039. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Created(BfpFindFileData* findData)
  3040. {
  3041. return *(BfpTimeStamp*)&findData->mFindData.ftCreationTime;
  3042. }
  3043. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Access(BfpFindFileData* findData)
  3044. {
  3045. return *(BfpTimeStamp*)&findData->mFindData.ftLastAccessTime;
  3046. }
  3047. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFindFileData_GetFileAttributes(BfpFindFileData* findData)
  3048. {
  3049. return FileAttributes_WinToBFP(findData->mFindData.dwFileAttributes);
  3050. }
  3051. BFP_EXPORT int64 BFP_CALLTYPE BfpFindFileData_GetFileSize(BfpFindFileData* findData)
  3052. {
  3053. return ((int64)findData->mFindData.nFileSizeHigh << 32) | (int64)findData->mFindData.nFileSizeLow;
  3054. }
  3055. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_Release(BfpFindFileData* findData)
  3056. {
  3057. ::FindClose(findData->mHandle);
  3058. delete findData;
  3059. }
  3060. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetCurrent(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  3061. {
  3062. wchar_t* wCwdStr = _wgetcwd(NULL, 0);
  3063. String str = UTF8Encode(wCwdStr);
  3064. free(wCwdStr);
  3065. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  3066. }
  3067. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_SetCurrent(const char* path, BfpFileResult* outResult)
  3068. {
  3069. UTF16String wPath = UTF8Decode(path);
  3070. if (_wchdir(wPath.c_str()) == -1)
  3071. OUTRESULT(BfpFileResult_UnknownError);
  3072. else
  3073. OUTRESULT(BfpFileResult_Ok);
  3074. }
  3075. BFP_EXPORT int BFP_CALLTYPE BfpStack_CaptureBackTrace(int framesToSkip, intptr* outFrames, int wantFrameCount)
  3076. {
  3077. return (int)RtlCaptureStackBackTrace(framesToSkip + 1, wantFrameCount, (void**)outFrames, NULL);
  3078. }
  3079. BFP_EXPORT void BFP_CALLTYPE BfpOutput_DebugString(const char* str)
  3080. {
  3081. OutputDebugStringA(str);
  3082. }