Platform.cpp 88 KB

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