Platform.cpp 97 KB

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