Platform.cpp 86 KB

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