Platform.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364
  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. BFP_EXPORT void BFP_CALLTYPE BfpSystem_Init(int version, BfpSystemInitFlags flags)
  763. {
  764. ::_set_error_mode(_OUT_TO_STDERR);
  765. #ifdef _DEBUG
  766. ::_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
  767. #endif
  768. ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  769. ::SetErrorMode(SEM_FAILCRITICALERRORS);
  770. if (version != BFP_VERSION)
  771. {
  772. BfpSystem_FatalError(StrFormat("Bfp build version '%d' does not match requested version '%d'", BFP_VERSION, version).c_str(), "BFP FATAL ERROR");
  773. }
  774. if ((flags & BfpSystemInitFlag_InstallCrashCatcher) != 0)
  775. {
  776. // Set up a handler for pure virtual function calls
  777. _set_purecall_handler(HandlePureVirtualFunctionCall);
  778. // Set up a handler for invalid parameters such as printf(NULL);
  779. _set_invalid_parameter_handler(HandleInvalidParameter);
  780. // Set up a handler for abort(). This is done in two steps.
  781. // First we ask the CRT to call an abort handler. This is the
  782. // default, but explicitly setting it seems like a good idea.
  783. _set_abort_behavior(_CALL_REPORTFAULT, _CALL_REPORTFAULT);
  784. // Then we install our abort handler.
  785. signal(SIGABRT, &AbortHandler);
  786. gCrashCatcher.Init();
  787. if ((flags & BfpSystemInitFlag_SilentCrash) != 0)
  788. gCrashCatcher.SetCrashReportKind(BfpCrashReportKind_None);
  789. }
  790. }
  791. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCommandLine(int argc, char** argv)
  792. {
  793. // This isn't required on Windows, but it is on Linux
  794. }
  795. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashReportKind(BfpCrashReportKind crashReportKind)
  796. {
  797. gCrashCatcher.SetCrashReportKind(crashReportKind);
  798. }
  799. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfoFunc(BfpCrashInfoFunc crashInfoFunc)
  800. {
  801. gCrashCatcher.AddCrashInfoFunc(crashInfoFunc);
  802. }
  803. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfo(const char* str)
  804. {
  805. gCrashCatcher.AddInfo(str);
  806. }
  807. BFP_EXPORT void BFP_CALLTYPE BfpSystem_Shutdown()
  808. {
  809. while (gManagerTail != NULL)
  810. {
  811. auto next = gManagerTail->mNext;
  812. delete gManagerTail;
  813. gManagerTail = next;
  814. }
  815. }
  816. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_TickCount()
  817. {
  818. return BFTickCount();
  819. }
  820. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpSystem_GetTimeStamp()
  821. {
  822. BfpTimeStamp timeStamp = 0;
  823. GetSystemTimeAsFileTime((FILETIME*)&timeStamp);
  824. return timeStamp;
  825. }
  826. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_EndianSwap16(uint16 val)
  827. {
  828. return _byteswap_ushort(val);
  829. }
  830. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_EndianSwap32(uint32 val)
  831. {
  832. return _byteswap_ulong(val);
  833. }
  834. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_EndianSwap64(uint64 val)
  835. {
  836. return _byteswap_uint64(val);
  837. }
  838. BFP_EXPORT uint8 BFP_CALLTYPE BfpSystem_InterlockedExchange8(uint8* ptr, uint8 val) // Returns the initial value in 'ptr'
  839. {
  840. return ::InterlockedExchange8((volatile char*)ptr, val);
  841. }
  842. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedExchange16(uint16* ptr, uint16 val) // Returns the initial value in 'ptr'
  843. {
  844. return ::InterlockedExchange16((volatile short*)ptr, val);
  845. }
  846. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchange32(uint32* ptr, uint32 val) // Returns the initial value in 'ptr'
  847. {
  848. return ::InterlockedExchange((volatile uint32*)ptr, val);
  849. }
  850. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchange64(uint64* ptr, uint64 val)
  851. {
  852. return ::InterlockedExchange((volatile uint64*)ptr, val);
  853. }
  854. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd8(uint8* ptr, uint8 val) // Returns the initial value in 'ptr'
  855. {
  856. return ::InterlockedExchangeAdd8((volatile char*)ptr, val);
  857. }
  858. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd16(uint16* ptr, uint16 val) // Returns the initial value in 'ptr'
  859. {
  860. return ::_InterlockedExchangeAdd16((volatile short*)ptr, val);
  861. }
  862. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd32(uint32* ptr, uint32 val) // Returns the initial value in 'ptr'
  863. {
  864. return ::InterlockedExchangeAdd((volatile uint32*)ptr, val);
  865. }
  866. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd64(uint64* ptr, uint64 val)
  867. {
  868. return ::InterlockedExchangeAdd((volatile uint64*)ptr, val);
  869. }
  870. BFP_EXPORT uint8 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange8(uint8* ptr, uint8 oldVal, uint8 newVal)
  871. {
  872. return ::_InterlockedCompareExchange8((volatile char*)ptr, newVal, oldVal);
  873. }
  874. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange16(uint16* ptr, uint16 oldVal, uint16 newVal)
  875. {
  876. return ::_InterlockedCompareExchange16((volatile short*)ptr, newVal, oldVal);
  877. }
  878. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange32(uint32* ptr, uint32 oldVal, uint32 newVal)
  879. {
  880. return ::InterlockedCompareExchange((volatile uint32*)ptr, newVal, oldVal);
  881. }
  882. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange64(uint64* ptr, uint64 oldVal, uint64 newVal)
  883. {
  884. return ::InterlockedCompareExchange64((volatile int64*)ptr, newVal, oldVal);
  885. }
  886. BFP_EXPORT void BFP_CALLTYPE BfpSystem_FatalError(const char* error, const char* title)
  887. {
  888. if (title != NULL)
  889. gCrashCatcher.Crash(String(title) + "\n" + String(error));
  890. else
  891. gCrashCatcher.Crash(error);
  892. }
  893. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetCommandLine(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  894. {
  895. WCHAR* ptr = ::GetCommandLineW();
  896. UTF16String wString(ptr);
  897. String env = UTF8Encode(wString);
  898. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  899. }
  900. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetExecutablePath(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  901. {
  902. WCHAR path[MAX_PATH];
  903. GetModuleFileNameW(NULL, path, MAX_PATH);
  904. String env = UTF8Encode(path);
  905. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  906. }
  907. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetEnvironmentStrings(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  908. {
  909. WCHAR* ptr = ::GetEnvironmentStringsW();
  910. WCHAR* endPtr = ptr;
  911. while (true)
  912. {
  913. if ((endPtr[0] == 0) && (endPtr[1] == 0))
  914. break;
  915. endPtr++;
  916. }
  917. UTF16String wString(ptr, (int)(endPtr - ptr + 2));
  918. String env = UTF8Encode(wString);
  919. ::FreeEnvironmentStringsW(ptr);
  920. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  921. }
  922. BFP_EXPORT int BFP_CALLTYPE BfpSystem_GetNumLogicalCPUs(BfpSystemResult* outResult)
  923. {
  924. SYSTEM_INFO sysInfo;
  925. GetSystemInfo(&sysInfo);
  926. OUTRESULT(BfpSystemResult_Ok);
  927. return sysInfo.dwNumberOfProcessors;
  928. }
  929. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTick()
  930. {
  931. return __rdtsc();
  932. }
  933. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTickFreq()
  934. {
  935. LARGE_INTEGER freq = { 0 };
  936. QueryPerformanceFrequency(&freq);
  937. return freq.QuadPart;
  938. }
  939. BFP_EXPORT void BFP_CALLTYPE BfpSystem_CreateGUID(BfpGUID* outGuid)
  940. {
  941. memset(outGuid, 0, sizeof(BfpGUID));
  942. UuidCreate((UUID*)outGuid);
  943. }
  944. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetComputerName(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  945. {
  946. char computerName[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
  947. DWORD computerNameSize = MAX_COMPUTERNAME_LENGTH;
  948. GetComputerNameA(computerName, &computerNameSize);
  949. TryStringOut(computerName, outStr, inOutStrSize, (BfpResult*)outResult);
  950. }
  951. /// BfpFileWatcher
  952. BFP_EXPORT BfpFileWatcher* BFP_CALLTYPE BfpFileWatcher_WatchDirectory(const char* path, BfpDirectoryChangeFunc callback, BfpFileWatcherFlags flags, void* userData, BfpFileResult* outResult)
  953. {
  954. HANDLE directoryHandle = CreateFileW(
  955. UTF8Decode(path).c_str(), // Directory name
  956. FILE_LIST_DIRECTORY, // access (read-write) mode
  957. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  958. NULL, // security descriptor
  959. OPEN_EXISTING,
  960. FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // file attributes
  961. NULL // file with attributes to copy
  962. );
  963. if (!IsHandleValid(directoryHandle))
  964. {
  965. OUTRESULT(BfpFileResult_UnknownError);
  966. return NULL;
  967. }
  968. BfpFileWatcher* fileWatcher = new BfpFileWatcher();
  969. fileWatcher->mKind = BfpOverlappedKind_FileWatcher;
  970. fileWatcher->mPath = path;
  971. fileWatcher->mDirectoryChangeFunc = callback;
  972. fileWatcher->mHandle = directoryHandle;
  973. fileWatcher->mFlags = flags;
  974. fileWatcher->mUserData = userData;
  975. IOCPManager::Get()->Add(fileWatcher);
  976. fileWatcher->Monitor();
  977. return fileWatcher;
  978. }
  979. BFP_EXPORT void BFP_CALLTYPE BfpFileWatcher_Release(BfpFileWatcher* fileWatcher)
  980. {
  981. IOCPManager::Get()->Remove(fileWatcher);
  982. //::CloseHandle(fileWatcher->mFileHandle);
  983. //fileWatcher->mFileHandle = NULL;
  984. //delete fileWatcher;
  985. }
  986. /// BfpProcess
  987. BFP_EXPORT intptr BFP_CALLTYPE BfpProcess_GetCurrentId()
  988. {
  989. return ::GetCurrentProcessId();
  990. }
  991. struct BfpProcess
  992. {
  993. int mProcessId;
  994. SYSTEM_PROCESS_INFORMATION* mInfo;
  995. String mImageName;
  996. };
  997. BFP_EXPORT bool BFP_CALLTYPE BfpProcess_IsRemoteMachine(const char* machineName)
  998. {
  999. return false;
  1000. }
  1001. BFP_EXPORT BfpProcess* BFP_CALLTYPE BfpProcess_GetById(const char* machineName, int processId, BfpProcessResult* outResult)
  1002. {
  1003. BfpProcess* process = new BfpProcess();
  1004. process->mProcessId = processId;
  1005. process->mInfo = NULL;
  1006. return process;
  1007. }
  1008. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Enumerate(const char* machineName, BfpProcess** outProcesses, int* inOutProcessesSize, BfpProcessResult* outResult)
  1009. {
  1010. ImportNTDll();
  1011. if (gNtQuerySystemInformation == NULL)
  1012. {
  1013. *inOutProcessesSize = 0;
  1014. return;
  1015. }
  1016. uint allocSize = 1024;
  1017. uint8* data = NULL;
  1018. while (true)
  1019. {
  1020. data = new uint8[allocSize];
  1021. ULONG wantSize = 0;
  1022. NTSTATUS status = gNtQuerySystemInformation(SystemProcessInformation, data, allocSize, &wantSize);
  1023. if (status != STATUS_INFO_LENGTH_MISMATCH)
  1024. {
  1025. auto processInfo = (SYSTEM_PROCESS_INFORMATION*)data;
  1026. auto curProcessInfo = processInfo;
  1027. int count = 0;
  1028. while (true)
  1029. {
  1030. if (curProcessInfo == NULL)
  1031. break;
  1032. count++;
  1033. if (curProcessInfo->NextEntryOffset == 0)
  1034. break;
  1035. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1036. }
  1037. if (count > *inOutProcessesSize)
  1038. {
  1039. *inOutProcessesSize = count;
  1040. OUTRESULT(BfpProcessResult_InsufficientBuffer);
  1041. delete data;
  1042. return;
  1043. }
  1044. curProcessInfo = processInfo;
  1045. count = 0;
  1046. while (true)
  1047. {
  1048. if (curProcessInfo == NULL)
  1049. break;
  1050. if (curProcessInfo->ProcessId != 0)
  1051. {
  1052. BfpProcess* process = new BfpProcess();
  1053. int dataSize = sizeof(SYSTEM_PROCESS_INFORMATION) + sizeof(SYSTEM_THREAD) * (curProcessInfo->NumberOfThreads - 1);
  1054. process->mProcessId = (int)(intptr)curProcessInfo->ProcessId;
  1055. process->mInfo = (SYSTEM_PROCESS_INFORMATION*)malloc(dataSize);
  1056. memcpy(process->mInfo, curProcessInfo, dataSize);
  1057. UTF16String utf16;
  1058. utf16.Set(curProcessInfo->ImageName.Buffer, curProcessInfo->ImageName.Length/2);
  1059. process->mImageName = UTF8Encode(utf16);
  1060. outProcesses[count++] = process;
  1061. }
  1062. if (curProcessInfo->NextEntryOffset == 0)
  1063. break;
  1064. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1065. }
  1066. *inOutProcessesSize = count;
  1067. OUTRESULT(BfpProcessResult_Ok);
  1068. delete data;
  1069. return;
  1070. }
  1071. allocSize = wantSize + 4096;
  1072. delete data;
  1073. }
  1074. }
  1075. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Release(BfpProcess* process)
  1076. {
  1077. if (process->mInfo != NULL)
  1078. free(process->mInfo);
  1079. delete process;
  1080. }
  1081. //struct EnumWndData
  1082. //{
  1083. // HWND mBestHandle;
  1084. // uint32 mProcessId;
  1085. //};
  1086. struct MainWindowCache
  1087. {
  1088. Dictionary<uint32, HWND> mMap;
  1089. uint32 mLastUpdate;
  1090. MainWindowCache()
  1091. {
  1092. mLastUpdate = 0;
  1093. }
  1094. };
  1095. static MainWindowCache gMainWindowCache;
  1096. static BOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM param)
  1097. {
  1098. //EnumWndData* enumWndData = (EnumWndData*)param;
  1099. DWORD processId = 0;
  1100. ::GetWindowThreadProcessId(hWnd, &processId);
  1101. if (gMainWindowCache.mMap.ContainsKey(processId))
  1102. {
  1103. //if (processId == 6720)
  1104. //OutputDebugStrF("Bailed\n");
  1105. return TRUE;
  1106. }
  1107. if ((::IsWindowVisible(hWnd)) && (::GetWindow(hWnd, GW_OWNER) == NULL))
  1108. {
  1109. //if (processId == 6720)
  1110. //OutputDebugStrF("Set\n");
  1111. gMainWindowCache.mMap[processId] = hWnd;
  1112. }
  1113. return TRUE;
  1114. }
  1115. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetMainWindowTitle(BfpProcess* process, char* outTitle, int* inOutTitleSize, BfpProcessResult* outResult)
  1116. {
  1117. HWND mainWindow = NULL;
  1118. //
  1119. {
  1120. AutoCrit autoCrit(gBfpCritSect);
  1121. if ((gMainWindowCache.mLastUpdate == 0) || (BFTickCount() - gMainWindowCache.mLastUpdate > 100))
  1122. {
  1123. gMainWindowCache.mMap.Clear();
  1124. ::EnumWindows(EnumWndProc, 0);
  1125. gMainWindowCache.mLastUpdate = BFTickCount();
  1126. }
  1127. gMainWindowCache.mMap.TryGetValue(process->mProcessId, &mainWindow);
  1128. }
  1129. /*EnumWndData enumWndData;
  1130. enumWndData.mBestHandle = NULL;
  1131. enumWndData.mProcessId = process->mProcessId;*/
  1132. String title;
  1133. if (mainWindow != NULL)
  1134. {
  1135. int wantSize = 128;
  1136. while (true)
  1137. {
  1138. WCHAR* str = new WCHAR[wantSize];
  1139. int size = ::GetWindowTextW(mainWindow, str, wantSize) + 1;
  1140. if (size <= 0)
  1141. {
  1142. delete str;
  1143. break;
  1144. }
  1145. if (size <= wantSize)
  1146. {
  1147. title = UTF8Encode(str);
  1148. delete str;
  1149. break;
  1150. }
  1151. delete str;
  1152. wantSize = size;
  1153. }
  1154. }
  1155. TryStringOut(title, outTitle, inOutTitleSize, (BfpResult*)outResult);
  1156. }
  1157. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetProcessName(BfpProcess* process, char* outName, int* inOutNameSize, BfpProcessResult* outResult)
  1158. {
  1159. if (process->mImageName.IsEmpty())
  1160. {
  1161. HANDLE hProc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process->mProcessId);
  1162. if (hProc == INVALID_HANDLE_VALUE)
  1163. {
  1164. OUTRESULT(BfpProcessResult_UnknownError);
  1165. return;
  1166. }
  1167. WCHAR wName[MAX_PATH];
  1168. ::GetModuleFileNameExW(hProc, NULL, wName, MAX_PATH);
  1169. ::CloseHandle(hProc);
  1170. String name = UTF8Encode(wName);
  1171. process->mImageName = name;
  1172. }
  1173. TryStringOut(process->mImageName, outName, inOutNameSize, (BfpResult*)outResult);
  1174. }
  1175. BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetProcessId(BfpProcess* process)
  1176. {
  1177. return process->mProcessId;
  1178. }
  1179. BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetRunningTime(BfpProcess* process)
  1180. {
  1181. if (process->mInfo == NULL)
  1182. return -1;
  1183. return (int)(process->mInfo->CreateTime.QuadPart / 10);
  1184. }
  1185. /// BfpSpawn
  1186. struct BfpSpawn
  1187. {
  1188. public:
  1189. String mArgsParamFilePath;
  1190. HANDLE mHProcess;
  1191. DWORD mProcessId;
  1192. HANDLE mStandardInputWritePipeHandle;
  1193. HANDLE mStandardOutputReadPipeHandle;
  1194. HANDLE mStandardErrorReadPipeHandle;
  1195. bool mIsDone;
  1196. public:
  1197. BfpSpawn()
  1198. {
  1199. mHProcess = 0;
  1200. mProcessId = 0;
  1201. mStandardInputWritePipeHandle = 0;
  1202. mStandardOutputReadPipeHandle = 0;
  1203. mStandardErrorReadPipeHandle = 0;
  1204. mIsDone = false;
  1205. }
  1206. ~BfpSpawn()
  1207. {
  1208. if (IsHandleValid(mHProcess))
  1209. ::CloseHandle(mHProcess);
  1210. if (IsHandleValid(mStandardInputWritePipeHandle))
  1211. ::CloseHandle(mStandardInputWritePipeHandle);
  1212. if (IsHandleValid(mStandardOutputReadPipeHandle))
  1213. ::CloseHandle(mStandardOutputReadPipeHandle);
  1214. if (IsHandleValid(mStandardErrorReadPipeHandle))
  1215. ::CloseHandle(mStandardErrorReadPipeHandle);
  1216. }
  1217. static bool CreatePipeWithSecurityAttributes(HANDLE& hReadPipe, HANDLE& hWritePipe, SECURITY_ATTRIBUTES* lpPipeAttributes, int32 nSize)
  1218. {
  1219. hReadPipe = 0;
  1220. hWritePipe = 0;
  1221. bool ret = ::CreatePipe(&hReadPipe, &hWritePipe, lpPipeAttributes, nSize);
  1222. if (!ret || (hReadPipe == INVALID_HANDLE_VALUE) || (hWritePipe == INVALID_HANDLE_VALUE))
  1223. return false;
  1224. return true;
  1225. }
  1226. // Using synchronous Anonymous pipes for process input/output redirection means we would end up
  1227. // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since
  1228. // it will take advantage of the NT IO completion port infrastructure. But we can't really use
  1229. // Overlapped I/O for process input/output as it would break Console apps (managed Console class
  1230. // methods such as WriteLine as well as native CRT functions like printf) which are making an
  1231. // assumption that the console standard handles (obtained via GetStdHandle()) are opened
  1232. // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchrnously!
  1233. bool CreatePipe(HANDLE& parentHandle, HANDLE& childHandle, bool parentInputs)
  1234. {
  1235. SECURITY_ATTRIBUTES securityAttributesParent = { 0 };
  1236. securityAttributesParent.bInheritHandle = 1;
  1237. HANDLE hTmp = INVALID_HANDLE_VALUE;
  1238. if (parentInputs)
  1239. CreatePipeWithSecurityAttributes(childHandle, hTmp, &securityAttributesParent, 0);
  1240. else
  1241. CreatePipeWithSecurityAttributes(hTmp, childHandle, &securityAttributesParent, 0);
  1242. HANDLE dupHandle = 0;
  1243. // Duplicate the parent handle to be non-inheritable so that the child process
  1244. // doesn't have access. This is done for correctness sake, exact reason is unclear.
  1245. // One potential theory is that child process can do something brain dead like
  1246. // closing the parent end of the pipe and there by getting into a blocking situation
  1247. // as parent will not be draining the pipe at the other end anymore.
  1248. if (!::DuplicateHandle(GetCurrentProcess(), hTmp,
  1249. GetCurrentProcess(), &dupHandle,
  1250. 0, false, DUPLICATE_SAME_ACCESS))
  1251. {
  1252. return false;
  1253. }
  1254. parentHandle = dupHandle;
  1255. if (hTmp != INVALID_HANDLE_VALUE)
  1256. ::CloseHandle(hTmp);
  1257. return true;
  1258. }
  1259. bool StartWithCreateProcess(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1260. {
  1261. String fileName = targetPath;
  1262. String commandLine;
  1263. if ((flags & BfpSpawnFlag_ArgsIncludesTarget) == 0)
  1264. {
  1265. if ((!fileName.StartsWith("\"")) && (!fileName.EndsWith("\"")))
  1266. {
  1267. bool needsQuoting = false;
  1268. for (int i = 0; i < (int)fileName.length(); i++)
  1269. {
  1270. char c = fileName[i];
  1271. if (c == ' ')
  1272. needsQuoting = true;
  1273. }
  1274. if (needsQuoting)
  1275. {
  1276. commandLine.Append('\"');
  1277. commandLine.Append(fileName);
  1278. commandLine.Append('\"');
  1279. }
  1280. else
  1281. {
  1282. commandLine.Append(fileName);
  1283. }
  1284. }
  1285. else
  1286. {
  1287. commandLine.Append(fileName);
  1288. }
  1289. }
  1290. if ((args != NULL) && (args[0] != '0'))
  1291. {
  1292. if (!commandLine.IsEmpty())
  1293. commandLine.Append(' ');
  1294. commandLine.Append(args);
  1295. }
  1296. STARTUPINFOW startupInfo = { 0 };
  1297. PROCESS_INFORMATION processInfo = { 0 };
  1298. bool retVal;
  1299. int32 errorCode = 0;
  1300. //
  1301. {
  1302. // set up the streams
  1303. if ((flags & (BfpSpawnFlag_RedirectStdInput | BfpSpawnFlag_RedirectStdOutput | BfpSpawnFlag_RedirectStdError)) != 0)
  1304. {
  1305. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  1306. CreatePipe(mStandardInputWritePipeHandle, startupInfo.hStdInput, true);
  1307. else if (::GetConsoleWindow() != NULL)
  1308. startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  1309. else
  1310. startupInfo.hStdInput = INVALID_HANDLE_VALUE;
  1311. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  1312. CreatePipe(mStandardOutputReadPipeHandle, startupInfo.hStdOutput, false);
  1313. else
  1314. startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  1315. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  1316. CreatePipe(mStandardErrorReadPipeHandle, startupInfo.hStdError, false);
  1317. else
  1318. startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  1319. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  1320. }
  1321. // set up the creation flags paramater
  1322. int32 creationFlags = 0;
  1323. if ((flags & BfpSpawnFlag_NoWindow) != 0)
  1324. creationFlags |= CREATE_NO_WINDOW;
  1325. // set up the environment block parameter
  1326. WCHAR* targetStrPtr = NULL;
  1327. UTF16String targetStrW;
  1328. if ((flags & BfpSpawnFlag_ArgsIncludesTarget) != 0)
  1329. {
  1330. // If we already included the target in the args then the actual target may be different, so we need to explicitly pass that
  1331. targetStrW = UTF8Decode(targetPath);
  1332. targetStrPtr = (WCHAR*)targetStrW.c_str();
  1333. }
  1334. WCHAR* dirStrPtr = NULL;
  1335. UTF16String dirStrW;
  1336. if ((workingDir != NULL) && (workingDir[0] != 0))
  1337. {
  1338. dirStrW = UTF8Decode(workingDir);
  1339. dirStrPtr = (WCHAR*)dirStrW.c_str();
  1340. }
  1341. UTF16String envW;
  1342. WCHAR* envPtrW = NULL;
  1343. if ((env != NULL) && (env[0] != 0))
  1344. {
  1345. const char* envPtr = env;
  1346. while (true)
  1347. {
  1348. if ((envPtr[0] == 0) && (envPtr[1] == 0))
  1349. break;
  1350. envPtr++;
  1351. }
  1352. int envSize = (int)(envPtr - env) + 2;
  1353. String str8(env, envSize);
  1354. envW = UTF8Decode(str8);
  1355. envPtrW = (WCHAR*)envW.c_str();
  1356. startupInfo.dwFlags |= CREATE_UNICODE_ENVIRONMENT;
  1357. }
  1358. retVal = ::CreateProcessW(
  1359. targetStrPtr,
  1360. (WCHAR*)UTF8Decode(commandLine).c_str(), // pointer to the command line string
  1361. NULL, // pointer to process security attributes, we don't need to inherit the handle
  1362. NULL, // pointer to thread security attributes
  1363. true, // handle inheritance flag
  1364. creationFlags, // creation flags
  1365. envPtrW, // pointer to new environment block
  1366. dirStrPtr, // pointer to current directory name
  1367. &startupInfo, // pointer to STARTUPINFO
  1368. &processInfo // pointer to PROCESS_INFORMATION
  1369. );
  1370. if (!retVal)
  1371. errorCode = ::GetLastError();
  1372. if (processInfo.hThread != INVALID_HANDLE_VALUE)
  1373. ::CloseHandle(processInfo.hThread);
  1374. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  1375. ::CloseHandle(startupInfo.hStdInput);
  1376. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  1377. ::CloseHandle(startupInfo.hStdOutput);
  1378. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  1379. ::CloseHandle(startupInfo.hStdError);
  1380. if (!retVal)
  1381. {
  1382. if (IsHandleValid(mStandardInputWritePipeHandle))
  1383. {
  1384. ::CloseHandle(mStandardInputWritePipeHandle);
  1385. mStandardInputWritePipeHandle = 0;
  1386. }
  1387. if (IsHandleValid(mStandardOutputReadPipeHandle))
  1388. {
  1389. ::CloseHandle(mStandardOutputReadPipeHandle);
  1390. mStandardOutputReadPipeHandle = 0;
  1391. }
  1392. if (IsHandleValid(mStandardErrorReadPipeHandle))
  1393. {
  1394. ::CloseHandle(mStandardErrorReadPipeHandle);
  1395. mStandardErrorReadPipeHandle = 0;
  1396. }
  1397. OUTRESULT(BfpSpawnResult_UnknownError);
  1398. if (errorCode == ERROR_BAD_EXE_FORMAT || errorCode == ERROR_EXE_MACHINE_TYPE_MISMATCH)
  1399. {
  1400. return false;
  1401. }
  1402. return false;
  1403. }
  1404. }
  1405. bool ret = false;
  1406. if (IsHandleValid(processInfo.hProcess))
  1407. {
  1408. mHProcess = processInfo.hProcess;
  1409. mProcessId = processInfo.dwProcessId;
  1410. ret = true;
  1411. }
  1412. if (!ret)
  1413. {
  1414. OUTRESULT(BfpSpawnResult_UnknownError);
  1415. return false;
  1416. }
  1417. return true;
  1418. }
  1419. bool StartWithShellExecute(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1420. {
  1421. SHELLEXECUTEINFOW shellExecuteInfo = { 0 };
  1422. shellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
  1423. shellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  1424. if ((flags & BfpSpawnFlag_ErrorDialog) != 0)
  1425. {
  1426. //shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle;
  1427. }
  1428. else
  1429. {
  1430. shellExecuteInfo.fMask |= SEE_MASK_FLAG_NO_UI;
  1431. }
  1432. if ((flags & BfpSpawnFlag_NoWindow) != 0)
  1433. shellExecuteInfo.nShow = SW_HIDE;
  1434. else
  1435. shellExecuteInfo.nShow = SW_SHOWNORMAL;
  1436. UTF16String fileW;
  1437. UTF16String verbW;
  1438. UTF16String argsW;
  1439. UTF16String dirW;
  1440. String target = targetPath;
  1441. int barPos = (int)target.IndexOf('|');
  1442. if (barPos != -1)
  1443. {
  1444. fileW = UTF8Decode(target.Substring(0, barPos));
  1445. shellExecuteInfo.lpFile = fileW.c_str();
  1446. verbW = UTF8Decode(target.Substring(barPos + 1));
  1447. shellExecuteInfo.lpVerb = verbW.c_str();
  1448. }
  1449. else
  1450. {
  1451. fileW = UTF8Decode(target);
  1452. shellExecuteInfo.lpFile = fileW.c_str();
  1453. }
  1454. if ((args != NULL) && (args[0] != 0))
  1455. {
  1456. argsW = UTF8Decode(args);
  1457. shellExecuteInfo.lpParameters = argsW.c_str();
  1458. }
  1459. if ((workingDir != NULL) && (workingDir[0] != 0))
  1460. {
  1461. dirW = UTF8Decode(workingDir);
  1462. shellExecuteInfo.lpDirectory = dirW.c_str();
  1463. }
  1464. shellExecuteInfo.fMask |= SEE_MASK_FLAG_DDEWAIT;
  1465. BOOL success = ::ShellExecuteExW(&shellExecuteInfo);
  1466. if (!success)
  1467. {
  1468. int lastError = ::GetLastError();
  1469. OUTRESULT(BfpSpawnResult_UnknownError);
  1470. return false;
  1471. }
  1472. mHProcess = shellExecuteInfo.hProcess;
  1473. return true;
  1474. }
  1475. };
  1476. BFP_EXPORT BfpSpawn* BFP_CALLTYPE BfpSpawn_Create(const char* targetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  1477. {
  1478. String newArgs;
  1479. String tempFileName;
  1480. if ((flags & BfpSpawnFlag_UseArgsFile) != 0)
  1481. {
  1482. char tempPathStr[MAX_PATH];
  1483. ::GetTempPathA(MAX_PATH, tempPathStr);
  1484. char tempFileNameStr[MAX_PATH];
  1485. ::GetTempFileNameA(tempPathStr, "BFP", 0, tempFileNameStr);
  1486. tempFileName = tempFileNameStr;
  1487. BfpFileResult fileResult;
  1488. BfpFile* file = BfpFile_Create(tempFileNameStr, BfpFileCreateKind_CreateAlways, BfpFileCreateFlag_Write, BfpFileAttribute_Normal, &fileResult);
  1489. if (file == NULL)
  1490. {
  1491. OUTRESULT(BfpSpawnResult_TempFileError);
  1492. return NULL;
  1493. }
  1494. if ((flags & BfpSpawnFlag_UseArgsFile_Native) != 0)
  1495. {
  1496. UTF16String wStr = UTF8Decode(args);
  1497. if ((flags & BfpSpawnFlag_UseArgsFile_BOM) != 0)
  1498. {
  1499. uint8 bom[2] = { 0xFF, 0xFE };
  1500. BfpFile_Write(file, bom, 2, -1, NULL);
  1501. }
  1502. BfpFile_Write(file, wStr.c_str(), wStr.length() * 2, -1, NULL);
  1503. }
  1504. else
  1505. BfpFile_Write(file, args, strlen(args), -1, NULL);
  1506. BfpFile_Release(file);
  1507. newArgs.Append("@");
  1508. newArgs.Append(tempFileName);
  1509. if (newArgs.Contains(' '))
  1510. {
  1511. newArgs.Insert(0, '\"');
  1512. newArgs.Append('\"');
  1513. }
  1514. args = newArgs.c_str();
  1515. }
  1516. BfpSpawn* spawn = new BfpSpawn();
  1517. bool success = false;
  1518. if ((flags & BfpSpawnFlag_UseShellExecute) != 0)
  1519. success = spawn->StartWithShellExecute(targetPath, args, workingDir, env, flags, outResult);
  1520. else
  1521. success = spawn->StartWithCreateProcess(targetPath, args, workingDir, env, flags, outResult);
  1522. if (!success)
  1523. {
  1524. delete spawn;
  1525. return NULL;
  1526. }
  1527. spawn->mArgsParamFilePath = tempFileName;
  1528. return spawn;
  1529. }
  1530. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_Release(BfpSpawn* spawn)
  1531. {
  1532. if ((!spawn->mArgsParamFilePath.IsEmpty()) && (spawn->mIsDone))
  1533. BfpFile_Delete(spawn->mArgsParamFilePath.c_str(), NULL);
  1534. delete spawn;
  1535. }
  1536. // static BOOL CALLBACK TerminateAppEnum(HWND hwnd, LPARAM lParam)
  1537. // {
  1538. // DWORD dwID;
  1539. // GetWindowThreadProcessId(hwnd, &dwID);
  1540. //
  1541. // if (dwID == (DWORD)lParam)
  1542. // {
  1543. // PostMessage(hwnd, WM_CLOSE, 0, 0);
  1544. // }
  1545. //
  1546. // return TRUE;
  1547. // }
  1548. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_Kill(BfpSpawn* spawn, int exitCode, BfpKillFlags killFlags, BfpSpawnResult* outResult)
  1549. {
  1550. //::EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM)spawn->mProcessId);
  1551. if ((killFlags & BfpKillFlag_KillChildren) != 0)
  1552. {
  1553. ImportNTDll();
  1554. HashSet<int> killSet;
  1555. killSet.Add(spawn->mProcessId);
  1556. HashSet<int> killedSet;
  1557. killedSet.Add(spawn->mProcessId);
  1558. // New child processes can launch between the NtQuerySystemInformation call and the actual process termination,
  1559. // so we need to run multiple loops until we stop finding child processes
  1560. while (true)
  1561. {
  1562. uint allocSize = 8192;
  1563. uint8* data;
  1564. while (true)
  1565. {
  1566. data = new uint8[allocSize];
  1567. ULONG wantSize = 0;
  1568. NTSTATUS status = gNtQuerySystemInformation(SystemProcessInformation, data, allocSize, &wantSize);
  1569. if (status != STATUS_INFO_LENGTH_MISMATCH)
  1570. {
  1571. bool foundNew;
  1572. do
  1573. {
  1574. foundNew = false;
  1575. auto processInfo = (SYSTEM_PROCESS_INFORMATION*)data;
  1576. auto curProcessInfo = processInfo;
  1577. while (true)
  1578. {
  1579. if (curProcessInfo == NULL)
  1580. break;
  1581. if (killSet.Contains((int)(intptr)curProcessInfo->InheritedFromProcessId))
  1582. {
  1583. if (killSet.Add((int)(intptr)curProcessInfo->ProcessId))
  1584. foundNew = true;
  1585. }
  1586. if (curProcessInfo->NextEntryOffset == 0)
  1587. break;
  1588. curProcessInfo = (SYSTEM_PROCESS_INFORMATION*)((intptr)curProcessInfo + curProcessInfo->NextEntryOffset);
  1589. }
  1590. } while (foundNew);
  1591. delete data;
  1592. break;
  1593. }
  1594. allocSize = wantSize + 4096;
  1595. delete data;
  1596. }
  1597. if (killedSet.size() == killSet.size())
  1598. break;
  1599. for (auto pid : killSet)
  1600. {
  1601. if (!killedSet.Add(pid))
  1602. continue;
  1603. HANDLE procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
  1604. if (procHandle != NULL)
  1605. {
  1606. ::TerminateProcess(procHandle, exitCode);
  1607. // DWORD threadId = 0;
  1608. // ::CreateRemoteThread(procHandle, NULL, 0, (LPTHREAD_START_ROUTINE)ExitProcess, (void*)(intptr)exitCode, 0, &threadId);
  1609. // if (pid != spawn->mProcessId)
  1610. // ::CloseHandle(procHandle);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. if (!::TerminateProcess(spawn->mHProcess, (UINT)exitCode))
  1616. {
  1617. int lastError = ::GetLastError();
  1618. OUTRESULT(BfpSpawnResult_UnknownError);
  1619. return;
  1620. }
  1621. // BOOL hadConsole = ::FreeConsole();
  1622. // ::AttachConsole(spawn->mProcessId);
  1623. // ::SetConsoleCtrlHandler(NULL, true);
  1624. // ::GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
  1625. // //::Sleep(2000);
  1626. // ::FreeConsole();
  1627. // ::SetConsoleCtrlHandler(NULL, false);
  1628. // if (!::TerminateProcess(spawn->mHProcess, (UINT)exitCode))
  1629. // {
  1630. // int lastError = ::GetLastError();
  1631. // OUTRESULT(BfpSpawnResult_UnknownError);
  1632. // return;
  1633. // }
  1634. OUTRESULT(BfpSpawnResult_Ok);
  1635. }
  1636. BFP_EXPORT bool BFP_CALLTYPE BfpSpawn_WaitFor(BfpSpawn* spawn, int waitMS, int* outExitCode, BfpSpawnResult* outResult)
  1637. {
  1638. if (::WaitForSingleObject(spawn->mHProcess, waitMS) != WAIT_OBJECT_0)
  1639. {
  1640. OUTRESULT(BfpSpawnResult_UnknownError);
  1641. return false;
  1642. }
  1643. spawn->mIsDone = true;
  1644. ::GetExitCodeProcess(spawn->mHProcess, (DWORD*)outExitCode);
  1645. OUTRESULT(BfpSpawnResult_Ok);
  1646. return true;
  1647. }
  1648. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_GetStdHandles(BfpSpawn* spawn, BfpFile** outStdIn, BfpFile** outStdOut, BfpFile** outStdErr)
  1649. {
  1650. if (outStdIn != NULL)
  1651. {
  1652. *outStdIn = new BfpFile(spawn->mStandardInputWritePipeHandle);
  1653. spawn->mStandardInputWritePipeHandle = 0;
  1654. }
  1655. if (outStdOut != NULL)
  1656. {
  1657. *outStdOut = new BfpFile(spawn->mStandardOutputReadPipeHandle);
  1658. spawn->mStandardOutputReadPipeHandle = 0;
  1659. }
  1660. if (outStdErr != NULL)
  1661. {
  1662. *outStdErr = new BfpFile(spawn->mStandardErrorReadPipeHandle);
  1663. spawn->mStandardErrorReadPipeHandle = 0;
  1664. }
  1665. }
  1666. /// BfpThread
  1667. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_Create(BfpThreadStartProc startProc, void* threadParam, intptr stackSize, BfpThreadCreateFlags flags, BfpThreadId* outThreadId)
  1668. {
  1669. DWORD creationFlags = 0;
  1670. if ((flags & BfpThreadCreateFlag_Suspended) != 0)
  1671. creationFlags |= CREATE_SUSPENDED;
  1672. if (((flags & BfpThreadCreateFlag_StackSizeReserve) != 0) && (stackSize != 0))
  1673. creationFlags |= STACK_SIZE_PARAM_IS_A_RESERVATION;
  1674. DWORD threadId;
  1675. // We have an explicit LPTHREAD_START_ROUTINE cast because BfpThreadStartProc returns 'void'. This doesn't break the calling convention, it just means
  1676. // the return register value is garbage
  1677. HANDLE handle = ::CreateThread(NULL, (SIZE_T)stackSize, (LPTHREAD_START_ROUTINE)startProc, threadParam, creationFlags, &threadId);
  1678. if (outThreadId != NULL)
  1679. *outThreadId = threadId;
  1680. return (BfpThread*)handle;
  1681. }
  1682. BFP_EXPORT void BFP_CALLTYPE BfpThread_Release(BfpThread* thread)
  1683. {
  1684. ::CloseHandle((HANDLE)thread);
  1685. }
  1686. static void SetThreadName(DWORD threadId, const char* name)
  1687. {
  1688. const DWORD MS_VC_EXCEPTION = 0x406D1388;
  1689. typedef struct tagTHREADNAME_INFO
  1690. {
  1691. DWORD dwType; // Must be 0x1000.
  1692. LPCSTR szName; // Pointer to name (in user addr space).
  1693. DWORD dwThreadID; // Thread ID (-1=caller thread).
  1694. DWORD dwFlags; // Reserved for future use, must be zero.
  1695. } THREADNAME_INFO;
  1696. THREADNAME_INFO info;
  1697. info.dwType = 0x1000;
  1698. info.szName = name;
  1699. info.dwThreadID = threadId;
  1700. info.dwFlags = 0;
  1701. __try
  1702. {
  1703. RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
  1704. }
  1705. __except (EXCEPTION_EXECUTE_HANDLER)
  1706. {
  1707. }
  1708. }
  1709. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetName(BfpThread* thread, const char* name, BfpThreadResult* outResult)
  1710. {
  1711. ImportKernel();
  1712. HANDLE hThread = (HANDLE)thread;
  1713. if (hThread == NULL)
  1714. hThread = ::GetCurrentThread();
  1715. if (gSetThreadDescription != NULL)
  1716. {
  1717. gSetThreadDescription(hThread, UTF8Decode(name).c_str());
  1718. OUTRESULT(BfpThreadResult_Ok);
  1719. return;
  1720. }
  1721. SetThreadName(::GetThreadId(hThread), name);
  1722. OUTRESULT(BfpThreadResult_UnknownError);
  1723. }
  1724. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetName(BfpThread* thread, char* outName, int* inOutNameSize, BfpThreadResult* outResult)
  1725. {
  1726. ImportKernel();
  1727. PWSTR wStr = NULL;
  1728. if (gGetThreadDescription != NULL)
  1729. {
  1730. gGetThreadDescription((HANDLE)thread, &wStr);
  1731. if (wStr == NULL)
  1732. {
  1733. OUTRESULT(BfpThreadResult_UnknownError);
  1734. return;
  1735. }
  1736. String str = UTF8Encode(wStr);
  1737. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  1738. LocalFree(wStr);
  1739. return;
  1740. }
  1741. OUTRESULT(BfpThreadResult_UnknownError);
  1742. }
  1743. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_GetCurrent()
  1744. {
  1745. return (BfpThread*)::OpenThread(THREAD_ALL_ACCESS, TRUE, ::GetCurrentThreadId());
  1746. }
  1747. BFP_EXPORT BfpThreadId BFP_CALLTYPE BfpThread_GetCurrentId()
  1748. {
  1749. return (BfpThreadId)::GetCurrentThreadId();
  1750. }
  1751. BFP_EXPORT bool BFP_CALLTYPE BfpThread_WaitFor(BfpThread* thread, int waitMS)
  1752. {
  1753. return ::WaitForSingleObject((HANDLE)thread, waitMS) == WAIT_OBJECT_0;
  1754. }
  1755. BFP_EXPORT BfpThreadPriority BFP_CALLTYPE BfpThread_GetPriority(BfpThread* thread, BfpThreadResult* outResult)
  1756. {
  1757. return (BfpThreadPriority)::GetThreadPriority((HANDLE)thread);
  1758. }
  1759. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetPriority(BfpThread* thread, BfpThreadPriority threadPriority, BfpThreadResult* outResult)
  1760. {
  1761. // Coincidentally, our priority values map to (THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST)
  1762. if (::SetThreadPriority((HANDLE)thread, (int)threadPriority))
  1763. OUTRESULT(BfpThreadResult_Ok);
  1764. else
  1765. OUTRESULT(BfpThreadResult_UnknownError);
  1766. }
  1767. BFP_EXPORT void BFP_CALLTYPE BfpThread_Suspend(BfpThread* thread, BfpThreadResult* outResult)
  1768. {
  1769. DWORD suspendCount = ::SuspendThread((HANDLE)thread);
  1770. if (suspendCount == (DWORD)-1)
  1771. {
  1772. int error = GetLastError();
  1773. BF_DBG_FATAL("Failed BfpThread_Suspend");
  1774. OUTRESULT(BfpThreadResult_UnknownError);
  1775. return;
  1776. }
  1777. OUTRESULT(BfpThreadResult_Ok);
  1778. }
  1779. BFP_EXPORT void BFP_CALLTYPE BfpThread_Resume(BfpThread* thread, BfpThreadResult* outResult)
  1780. {
  1781. DWORD suspendCount = ::ResumeThread((HANDLE)thread);
  1782. if (suspendCount == (DWORD)-1)
  1783. {
  1784. int error = GetLastError();
  1785. BF_DBG_FATAL("Failed BfpThread_Resume");
  1786. OUTRESULT(BfpThreadResult_UnknownError);
  1787. return;
  1788. }
  1789. OUTRESULT(BfpThreadResult_Ok);
  1790. }
  1791. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetIntRegisters(BfpThread* thread, intptr* outStackPtr, intptr* outIntRegs, int* inOutIntRegCount, BfpThreadResult* outResult)
  1792. {
  1793. CONTEXT ctx;
  1794. memset(&ctx, 0, sizeof(CONTEXT));
  1795. ctx.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
  1796. BOOL success = ::GetThreadContext((HANDLE)thread, &ctx);
  1797. if (!success)
  1798. {
  1799. int error = GetLastError();
  1800. BF_DBG_FATAL("Failed BfpThread_GetIntRegisters");
  1801. OUTRESULT(BfpThreadResult_UnknownError);
  1802. return;
  1803. }
  1804. DWORD lastError = GetLastError();
  1805. BF_ASSERT(success);
  1806. #ifdef BF32
  1807. *outStackPtr = (intptr)ctx.Esp;
  1808. if (*inOutIntRegCount < 7)
  1809. {
  1810. OUTRESULT(BfpThreadResult_InsufficientBuffer);
  1811. return;
  1812. }
  1813. #else
  1814. *outStackPtr = (intptr)ctx.Rsp;
  1815. if (*inOutIntRegCount < 15)
  1816. {
  1817. OUTRESULT(BfpThreadResult_InsufficientBuffer);
  1818. return;
  1819. }
  1820. #endif
  1821. OUTRESULT(BfpThreadResult_Ok);
  1822. if (outIntRegs == NULL)
  1823. return;
  1824. intptr* curPtr = outIntRegs;
  1825. #ifdef BF32
  1826. *(curPtr++) = (intptr)ctx.Eax;
  1827. *(curPtr++) = (intptr)ctx.Ebx;
  1828. *(curPtr++) = (intptr)ctx.Ecx;
  1829. *(curPtr++) = (intptr)ctx.Edx;
  1830. *(curPtr++) = (intptr)ctx.Esi;
  1831. *(curPtr++) = (intptr)ctx.Edi;
  1832. *(curPtr++) = (intptr)ctx.Ebp;
  1833. #else
  1834. *(curPtr++) = (intptr)ctx.SegFs; // Testing
  1835. *(curPtr++) = (intptr)ctx.Rax;
  1836. *(curPtr++) = (intptr)ctx.Rbx;
  1837. *(curPtr++) = (intptr)ctx.Rcx;
  1838. *(curPtr++) = (intptr)ctx.Rdx;
  1839. *(curPtr++) = (intptr)ctx.Rsi;
  1840. *(curPtr++) = (intptr)ctx.Rdi;
  1841. *(curPtr++) = (intptr)ctx.Rbp;
  1842. *(curPtr++) = (intptr)ctx.R8;
  1843. *(curPtr++) = (intptr)ctx.R9;
  1844. *(curPtr++) = (intptr)ctx.R10;
  1845. *(curPtr++) = (intptr)ctx.R11;
  1846. *(curPtr++) = (intptr)ctx.R12;
  1847. *(curPtr++) = (intptr)ctx.R13;
  1848. *(curPtr++) = (intptr)ctx.R14;
  1849. *(curPtr++) = (intptr)ctx.R15;
  1850. #endif
  1851. *inOutIntRegCount = (int)(curPtr - outIntRegs);
  1852. }
  1853. struct BfpThreadStackInfo
  1854. {
  1855. intptr mStackBase;
  1856. intptr mStackLimit;
  1857. };
  1858. static __declspec(thread) BfpThreadStackInfo gThreadStackInfo;
  1859. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetStackInfo(BfpThread* thread, intptr* outStackBase, int* outStackLimit, BfpThreadResult* outResult)
  1860. {
  1861. if (gThreadStackInfo.mStackBase == 0)
  1862. {
  1863. auto teb = (NT_TIB*)NtCurrentTeb();
  1864. MEMORY_BASIC_INFORMATION stackInfo = { 0 };
  1865. // We subtract one page for our request. VirtualQuery rounds UP to the next page.
  1866. // Unfortunately, the stack grows down. If we're on the first page (last page in the
  1867. // VirtualAlloc), we'll be moved to the next page, which is off the stack! Note this
  1868. // doesn't work right for IA64 due to bigger pages.
  1869. void* currentAddr = (void*)((intptr_t)&stackInfo - 4096);
  1870. // Query for the current stack allocation information.
  1871. VirtualQuery(currentAddr, &stackInfo, sizeof(MEMORY_BASIC_INFORMATION));
  1872. gThreadStackInfo.mStackBase = (uintptr_t)teb->StackBase;
  1873. gThreadStackInfo.mStackLimit = (uintptr_t)stackInfo.AllocationBase;
  1874. }
  1875. *outStackBase = (intptr)gThreadStackInfo.mStackBase;
  1876. *outStackLimit = (int)(gThreadStackInfo.mStackBase - gThreadStackInfo.mStackLimit);
  1877. OUTRESULT(BfpThreadResult_Ok);
  1878. return;
  1879. }
  1880. struct BfpCritSect
  1881. {
  1882. CRITICAL_SECTION mCritSect;
  1883. };
  1884. BFP_EXPORT void BFP_CALLTYPE BfpThread_Sleep(int sleepMS)
  1885. {
  1886. ::Sleep(sleepMS);
  1887. }
  1888. BFP_EXPORT bool BFP_CALLTYPE BfpThread_Yield()
  1889. {
  1890. return ::SwitchToThread();
  1891. }
  1892. ///
  1893. BFP_EXPORT BfpCritSect* BFP_CALLTYPE BfpCritSect_Create()
  1894. {
  1895. BfpCritSect* critSect = new BfpCritSect();
  1896. ::InitializeCriticalSection(&critSect->mCritSect);
  1897. return critSect;
  1898. }
  1899. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Release(BfpCritSect* critSect)
  1900. {
  1901. ::DeleteCriticalSection(&critSect->mCritSect);
  1902. delete critSect;
  1903. }
  1904. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Enter(BfpCritSect* critSect)
  1905. {
  1906. ::EnterCriticalSection(&critSect->mCritSect);
  1907. }
  1908. BFP_EXPORT bool BFP_CALLTYPE BfpCritSect_TryEnter(BfpCritSect* critSect, int waitMS)
  1909. {
  1910. if (waitMS == 0)
  1911. {
  1912. return ::TryEnterCriticalSection(&critSect->mCritSect);
  1913. }
  1914. else if (waitMS == -1)
  1915. {
  1916. BfpCritSect_Enter(critSect);
  1917. return true;
  1918. }
  1919. // This is a poor implementation. We should use a mutex if this is required
  1920. uint32 start = BFTickCount();
  1921. while ((int)(BFTickCount() - start) < waitMS)
  1922. {
  1923. if (::TryEnterCriticalSection(&critSect->mCritSect))
  1924. return true;
  1925. BfpThread_Yield();
  1926. }
  1927. return false;
  1928. }
  1929. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Leave(BfpCritSect* critSect)
  1930. {
  1931. ::LeaveCriticalSection(&critSect->mCritSect);
  1932. }
  1933. #define DWORD_TO_BFPTLS(val) ((BfpTLS*)(intptr)(val))
  1934. #define BFPTLS_TO_DWORD(val) ((DWORD)(intptr)(val))
  1935. struct BfpTLS;
  1936. BFP_EXPORT BfpTLS* BFP_CALLTYPE BfpTLS_Create()
  1937. {
  1938. return DWORD_TO_BFPTLS(::TlsAlloc());
  1939. }
  1940. BFP_EXPORT void BFP_CALLTYPE BfpTLS_Release(BfpTLS* tls)
  1941. {
  1942. ::TlsFree(BFPTLS_TO_DWORD(tls));
  1943. }
  1944. BFP_EXPORT void BFP_CALLTYPE BfpTLS_SetValue(BfpTLS* tls, void* value)
  1945. {
  1946. ::TlsSetValue(BFPTLS_TO_DWORD(tls), value);
  1947. }
  1948. BFP_EXPORT void* BFP_CALLTYPE BfpTLS_GetValue(BfpTLS* tls)
  1949. {
  1950. return ::TlsGetValue(BFPTLS_TO_DWORD(tls));
  1951. }
  1952. BFP_EXPORT BfpEvent* BFP_CALLTYPE BfpEvent_Create(BfpEventFlags flags)
  1953. {
  1954. BfpEvent* event = new BfpEvent();
  1955. ::InitializeCriticalSection(&event->mCritSect);
  1956. ::InitializeConditionVariable(&event->mCondVariable);
  1957. event->mSet = (flags & (BfpEventFlag_InitiallySet_Auto | BfpEventFlag_InitiallySet_Manual)) != 0;
  1958. event->mManualReset = (flags & BfpEventFlag_InitiallySet_Manual) != 0;
  1959. return event;
  1960. }
  1961. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Release(BfpEvent* event)
  1962. {
  1963. ::DeleteCriticalSection(&event->mCritSect);
  1964. delete event;
  1965. }
  1966. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Set(BfpEvent* event, bool requireManualReset)
  1967. {
  1968. ::EnterCriticalSection(&event->mCritSect);
  1969. event->mSet = true;
  1970. if (requireManualReset)
  1971. event->mManualReset = true;
  1972. if (event->mManualReset)
  1973. ::WakeAllConditionVariable(&event->mCondVariable);
  1974. else
  1975. ::WakeConditionVariable(&event->mCondVariable);
  1976. ::LeaveCriticalSection(&event->mCritSect);
  1977. }
  1978. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Reset(BfpEvent* event, BfpEventResult* outResult)
  1979. {
  1980. event->mSet = false;
  1981. event->mManualReset = false;
  1982. }
  1983. BFP_EXPORT bool BFP_CALLTYPE BfpEvent_WaitFor(BfpEvent* event, int waitMS)
  1984. {
  1985. ::EnterCriticalSection(&event->mCritSect);
  1986. while (!event->mSet)
  1987. {
  1988. if (!SleepConditionVariableCS(&event->mCondVariable, &event->mCritSect, waitMS))
  1989. {
  1990. if (GetLastError() == ERROR_TIMEOUT)
  1991. {
  1992. // Timeout
  1993. LeaveCriticalSection(&event->mCritSect);
  1994. return false;
  1995. }
  1996. }
  1997. }
  1998. if (!event->mManualReset)
  1999. event->mSet = false;
  2000. ::LeaveCriticalSection(&event->mCritSect);
  2001. return true;
  2002. }
  2003. struct BfpDynLib;
  2004. BFP_EXPORT BfpDynLib* BFP_CALLTYPE BfpDynLib_Load(const char* fileName)
  2005. {
  2006. UTF16String wPath = UTF8Decode(fileName);
  2007. return (BfpDynLib*)::LoadLibraryW(wPath.c_str());
  2008. }
  2009. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_Release(BfpDynLib* lib)
  2010. {
  2011. ::FreeLibrary((HMODULE)lib);
  2012. }
  2013. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_GetFilePath(BfpDynLib* lib, char* outPath, int* inOutPathSize, BfpLibResult* outResult)
  2014. {
  2015. Beefy::String path;
  2016. WCHAR cPath[4096];
  2017. ::GetModuleFileNameW((HMODULE)lib, cPath, 4096);
  2018. path = UTF8Encode(cPath);
  2019. TryStringOut(path, outPath, inOutPathSize, (BfpResult*)outResult);
  2020. }
  2021. BFP_EXPORT void* BFP_CALLTYPE BfpDynLib_GetProcAddress(BfpDynLib* lib, const char* name)
  2022. {
  2023. return ::GetProcAddress((HMODULE)lib, name);
  2024. }
  2025. struct BfpFindFileData;
  2026. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Create(const char* path, BfpFileResult* outResult)
  2027. {
  2028. UTF16String wPath = UTF8Decode(path);
  2029. if (!::CreateDirectoryW(wPath.c_str(), NULL))
  2030. {
  2031. switch (::GetLastError())
  2032. {
  2033. case ERROR_ALREADY_EXISTS:
  2034. OUTRESULT(BfpFileResult_AlreadyExists);
  2035. break;
  2036. case ERROR_PATH_NOT_FOUND:
  2037. OUTRESULT(BfpFileResult_NotFound);
  2038. break;
  2039. default:
  2040. OUTRESULT(BfpFileResult_UnknownError);
  2041. break;
  2042. }
  2043. }
  2044. else
  2045. {
  2046. OUTRESULT(BfpFileResult_Ok);
  2047. }
  2048. }
  2049. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Rename(const char* oldName, const char* newName, BfpFileResult* outResult)
  2050. {
  2051. UTF16String wOldPath = UTF8Decode(oldName);
  2052. UTF16String wNewPath = UTF8Decode(newName);
  2053. if (!::MoveFileW(wOldPath.c_str(), wNewPath.c_str()))
  2054. {
  2055. int err = ::GetLastError();
  2056. switch (err)
  2057. {
  2058. case ERROR_ALREADY_EXISTS:
  2059. OUTRESULT(BfpFileResult_AlreadyExists);
  2060. break;
  2061. case ERROR_FILE_NOT_FOUND:
  2062. case ERROR_PATH_NOT_FOUND:
  2063. OUTRESULT(BfpFileResult_NotFound);
  2064. break;
  2065. default:
  2066. OUTRESULT(BfpFileResult_UnknownError);
  2067. break;
  2068. }
  2069. }
  2070. else
  2071. {
  2072. OUTRESULT(BfpFileResult_Ok);
  2073. }
  2074. }
  2075. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Delete(const char* path, BfpFileResult* outResult)
  2076. {
  2077. UTF16String wPath = UTF8Decode(path);
  2078. if (!::RemoveDirectoryW(wPath.c_str()))
  2079. {
  2080. switch (GetLastError())
  2081. {
  2082. case ERROR_FILE_NOT_FOUND:
  2083. OUTRESULT(BfpFileResult_NotFound);
  2084. break;
  2085. case ERROR_DIR_NOT_EMPTY:
  2086. OUTRESULT(BfpFileResult_NotEmpty);
  2087. break;
  2088. default:
  2089. OUTRESULT(BfpFileResult_UnknownError);
  2090. break;
  2091. }
  2092. }
  2093. else
  2094. {
  2095. OUTRESULT(BfpFileResult_Ok);
  2096. }
  2097. }
  2098. BFP_EXPORT bool BFP_CALLTYPE BfpDirectory_Exists(const char* path)
  2099. {
  2100. WIN32_FIND_DATAW findData;
  2101. UTF16String wpath = UTF8Decode(path);
  2102. if (wpath.length() > 0)
  2103. {
  2104. uint16& endC = wpath[wpath.length() - 1];
  2105. if ((endC == '\\') || (endC == '/'))
  2106. {
  2107. wpath.pop_back();
  2108. }
  2109. }
  2110. HANDLE handleVal = FindFirstFileW(wpath.c_str(), &findData);
  2111. if (handleVal == INVALID_HANDLE_VALUE)
  2112. return false;
  2113. FindClose(handleVal);
  2114. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  2115. }
  2116. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetSysDirectory(BfpSysDirectoryKind sysDirKind, char* outPath, int* inOutPathLen, BfpFileResult* outResult)
  2117. {
  2118. String path;
  2119. auto _GetKnownFolder = [&](REFKNOWNFOLDERID rfid)
  2120. {
  2121. PWSTR pStrPtr;
  2122. int result = SHGetKnownFolderPath(rfid, KF_FLAG_CREATE, NULL, &pStrPtr);
  2123. if (result != 0)
  2124. {
  2125. OUTRESULT(BfpFileResult_UnknownError);
  2126. return;
  2127. }
  2128. path = UTF8Encode(pStrPtr);
  2129. CoTaskMemFree(pStrPtr);
  2130. TryStringOut(path, outPath, inOutPathLen, (BfpResult*)outResult);
  2131. };
  2132. switch (sysDirKind)
  2133. {
  2134. case BfpSysDirectoryKind_Default:
  2135. _GetKnownFolder(FOLDERID_Desktop);
  2136. break;
  2137. case BfpSysDirectoryKind_Home:
  2138. _GetKnownFolder(FOLDERID_Profile);
  2139. break;
  2140. case BfpSysDirectoryKind_System:
  2141. _GetKnownFolder(FOLDERID_System);
  2142. break;
  2143. case BfpSysDirectoryKind_Desktop:
  2144. _GetKnownFolder(FOLDERID_Desktop);
  2145. return;
  2146. case BfpSysDirectoryKind_Desktop_Common:
  2147. _GetKnownFolder(FOLDERID_PublicDesktop);
  2148. return;
  2149. case BfpSysDirectoryKind_AppData_Local:
  2150. _GetKnownFolder(FOLDERID_LocalAppData);
  2151. return;
  2152. case BfpSysDirectoryKind_AppData_LocalLow:
  2153. _GetKnownFolder(FOLDERID_LocalAppDataLow);
  2154. return;
  2155. case BfpSysDirectoryKind_AppData_Roaming:
  2156. _GetKnownFolder(FOLDERID_RoamingAppData);
  2157. return;
  2158. case BfpSysDirectoryKind_Programs:
  2159. _GetKnownFolder(FOLDERID_Programs);
  2160. return;
  2161. case BfpSysDirectoryKind_Programs_Common:
  2162. _GetKnownFolder(FOLDERID_CommonPrograms);
  2163. return;
  2164. }
  2165. TryStringOut(path, outPath, inOutPathLen, (BfpResult*)outResult);
  2166. }
  2167. //////////////////////////////////////////////////////////////////////////
  2168. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_Create(const char* path, BfpFileCreateKind createKind, BfpFileCreateFlags createFlags, BfpFileAttributes createdFileAttrs, BfpFileResult* outResult)
  2169. {
  2170. UTF16String wPath = UTF8Decode(path);
  2171. //OVERLAPPED
  2172. if ((createFlags & BfpFileCreateFlag_Pipe) != 0)
  2173. {
  2174. String pipeName = StrFormat("\\\\%s\\pipe\\%s", ".", path);
  2175. wPath = UTF8Decode(pipeName);
  2176. if ((createKind == BfpFileCreateKind_CreateIfNotExists) ||
  2177. (createKind == BfpFileCreateKind_CreateAlways))
  2178. {
  2179. bool isOverlapped = false;
  2180. DWORD openMode = 0;
  2181. DWORD desiredAccess = 0;
  2182. if ((createFlags & BfpFileCreateFlag_Read) != 0)
  2183. openMode |= PIPE_ACCESS_INBOUND;
  2184. if ((createFlags & BfpFileCreateFlag_Write) != 0)
  2185. openMode |= PIPE_ACCESS_OUTBOUND;
  2186. if (createKind == BfpFileCreateKind_CreateIfNotExists)
  2187. openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
  2188. int pipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
  2189. if ((createFlags & BfpFileCreateFlag_AllowTimeouts) != 0)
  2190. {
  2191. openMode |= FILE_FLAG_OVERLAPPED;
  2192. isOverlapped = true;
  2193. }
  2194. else if ((createFlags & BfpFileCreateFlag_NonBlocking) != 0)
  2195. pipeMode |= PIPE_NOWAIT;
  2196. HANDLE handle = ::CreateNamedPipeW(wPath.c_str(), openMode, pipeMode, PIPE_UNLIMITED_INSTANCES, 8192, 8192, 0, NULL);
  2197. if (handle == INVALID_HANDLE_VALUE)
  2198. {
  2199. if (outResult != NULL)
  2200. {
  2201. int lastError = GetLastError();
  2202. switch (lastError)
  2203. {
  2204. default:
  2205. *outResult = BfpFileResult_UnknownError;
  2206. break;
  2207. }
  2208. }
  2209. return NULL;
  2210. }
  2211. OUTRESULT(BfpFileResult_Ok);
  2212. BfpFile* bfpFile = new BfpFile();
  2213. bfpFile->mHandle = handle;
  2214. bfpFile->mIsPipe = true;
  2215. if (isOverlapped)
  2216. {
  2217. bfpFile->mAsyncData = new BfpAsyncData();
  2218. }
  2219. return bfpFile;
  2220. }
  2221. }
  2222. DWORD desiredAccess = 0;
  2223. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  2224. desiredAccess |= FILE_APPEND_DATA;
  2225. else
  2226. {
  2227. if ((createFlags & BfpFileCreateFlag_Read) != 0)
  2228. desiredAccess |= GENERIC_READ;
  2229. if ((createFlags & BfpFileCreateFlag_Write) != 0)
  2230. desiredAccess |= GENERIC_WRITE;
  2231. }
  2232. DWORD shareMode = 0;
  2233. if ((createFlags & BfpFileCreateFlag_ShareRead) != 0)
  2234. shareMode |= FILE_SHARE_READ;
  2235. if ((createFlags & BfpFileCreateFlag_ShareWrite) != 0)
  2236. shareMode |= FILE_SHARE_WRITE;
  2237. if ((createFlags & BfpFileCreateFlag_ShareDelete) != 0)
  2238. shareMode |= FILE_SHARE_DELETE;
  2239. DWORD creationDisposition = 0;
  2240. if (createKind == BfpFileCreateKind_CreateAlways)
  2241. {
  2242. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  2243. creationDisposition = OPEN_ALWAYS;
  2244. else
  2245. creationDisposition = CREATE_ALWAYS;
  2246. }
  2247. else if (createKind == BfpFileCreateKind_CreateIfNotExists)
  2248. {
  2249. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  2250. creationDisposition = CREATE_NEW;
  2251. else
  2252. creationDisposition = TRUNCATE_EXISTING;
  2253. }
  2254. else
  2255. {
  2256. creationDisposition = OPEN_EXISTING;
  2257. }
  2258. DWORD attributes = 0;
  2259. if ((createdFileAttrs & (BfpFileAttribute_Directory | BfpFileAttribute_SymLink | BfpFileAttribute_Device)) != 0)
  2260. {
  2261. if (outResult != NULL)
  2262. *outResult = BfpFileResult_InvalidParameter;
  2263. return NULL;
  2264. }
  2265. attributes = FileAttributes_WinToBFP(createdFileAttrs);
  2266. if ((createFlags & BfpFileCreateFlag_WriteThrough) != 0)
  2267. desiredAccess |= FILE_FLAG_WRITE_THROUGH;
  2268. if ((createFlags & BfpFileCreateFlag_DeleteOnClose) != 0)
  2269. desiredAccess |= FILE_FLAG_DELETE_ON_CLOSE;
  2270. if ((createFlags & BfpFileCreateFlag_NoBuffering) != 0)
  2271. desiredAccess |= FILE_FLAG_NO_BUFFERING;
  2272. HANDLE handle = ::CreateFileW(wPath.c_str(), desiredAccess, shareMode, NULL, creationDisposition, attributes, NULL);
  2273. if (handle == INVALID_HANDLE_VALUE)
  2274. {
  2275. if (outResult != NULL)
  2276. {
  2277. int lastError = GetLastError();
  2278. switch (lastError)
  2279. {
  2280. case ERROR_SHARING_VIOLATION:
  2281. *outResult = BfpFileResult_ShareError;
  2282. break;
  2283. case ERROR_FILE_NOT_FOUND:
  2284. *outResult = BfpFileResult_NotFound;
  2285. break;
  2286. default:
  2287. *outResult = BfpFileResult_UnknownError;
  2288. break;
  2289. }
  2290. }
  2291. return NULL;
  2292. }
  2293. OUTRESULT(BfpFileResult_Ok);
  2294. BfpFile* bfpFile = new BfpFile();
  2295. bfpFile->mHandle = handle;
  2296. return bfpFile;
  2297. }
  2298. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_GetStd(BfpFileStdKind kind, BfpFileResult* outResult)
  2299. {
  2300. HANDLE h = INVALID_HANDLE_VALUE;
  2301. switch (kind)
  2302. {
  2303. case BfpFileStdKind_StdOut:
  2304. h = ::GetStdHandle(STD_OUTPUT_HANDLE);
  2305. break;
  2306. case BfpFileStdKind_StdError:
  2307. h = ::GetStdHandle(STD_ERROR_HANDLE);
  2308. break;
  2309. case BfpFileStdKind_StdIn:
  2310. h = ::GetStdHandle(STD_INPUT_HANDLE);
  2311. break;
  2312. }
  2313. if ((h == INVALID_HANDLE_VALUE) || (h == 0))
  2314. {
  2315. OUTRESULT(BfpFileResult_NotFound);
  2316. return NULL;
  2317. }
  2318. BfpFile* bfpFile = new BfpFile();
  2319. bfpFile->mHandle = h;
  2320. bfpFile->mIsStd = true;
  2321. return bfpFile;
  2322. }
  2323. BFP_EXPORT void BFP_CALLTYPE BfpFile_Release(BfpFile* file)
  2324. {
  2325. if ((file->mHandle != INVALID_HANDLE_VALUE) && (!file->mIsStd))
  2326. ::CloseHandle(file->mHandle);
  2327. delete file;
  2328. }
  2329. BFP_EXPORT void BFP_CALLTYPE BfpFile_Close(BfpFile* file, BfpFileResult* outResult)
  2330. {
  2331. if (file->mHandle != INVALID_HANDLE_VALUE)
  2332. {
  2333. ::CloseHandle(file->mHandle);
  2334. file->mHandle = INVALID_HANDLE_VALUE;
  2335. OUTRESULT(BfpFileResult_Ok);
  2336. }
  2337. else
  2338. OUTRESULT(BfpFileResult_UnknownError);
  2339. }
  2340. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Write(BfpFile* file, const void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  2341. {
  2342. DWORD bytesWritten = 0;
  2343. if (::WriteFile(file->mHandle, buffer, (uint32)size, &bytesWritten, NULL))
  2344. {
  2345. if (outResult != NULL)
  2346. {
  2347. if (bytesWritten != size)
  2348. *outResult = BfpFileResult_PartialData;
  2349. else
  2350. *outResult = BfpFileResult_Ok;
  2351. }
  2352. return bytesWritten;
  2353. }
  2354. if (outResult != NULL)
  2355. {
  2356. switch (GetLastError())
  2357. {
  2358. default:
  2359. *outResult = BfpFileResult_UnknownError;
  2360. break;
  2361. }
  2362. }
  2363. return bytesWritten;
  2364. }
  2365. struct OverlappedReadResult : OVERLAPPED
  2366. {
  2367. BfpFile* mFile;
  2368. intptr mBytesRead;
  2369. DWORD mErrorCode;
  2370. };
  2371. static void WINAPI OverlappedReadComplete(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
  2372. {
  2373. OverlappedReadResult* readResult = (OverlappedReadResult*)lpOverlapped;
  2374. readResult->mErrorCode = dwErrorCode;
  2375. readResult->mBytesRead = dwNumberOfBytesTransfered;
  2376. readResult->mFile->mAsyncData->SetEvent();
  2377. }
  2378. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Read(BfpFile* file, void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  2379. {
  2380. if (timeoutMS != -1)
  2381. {
  2382. while (true)
  2383. {
  2384. OverlappedReadResult overlapped;
  2385. memset(&overlapped, 0, sizeof(OverlappedReadResult));
  2386. overlapped.mFile = file;
  2387. //TODO: this doesn't set file stream location. It only works for streams like pipes, sockets, etc
  2388. if (::ReadFileEx(file->mHandle, buffer, (uint32)size, &overlapped, OverlappedReadComplete))
  2389. {
  2390. if (!file->mAsyncData->WaitAndResetEvent(timeoutMS))
  2391. {
  2392. ::CancelIoEx(file->mHandle, &overlapped);
  2393. // There's a chance we completed before we were cancelled -- check on that
  2394. if (!file->mAsyncData->WaitAndResetEvent(0))
  2395. {
  2396. OUTRESULT(BfpFileResult_Timeout);
  2397. return 0;
  2398. }
  2399. }
  2400. if (overlapped.mErrorCode == 0)
  2401. {
  2402. }
  2403. else if (overlapped.mErrorCode == ERROR_OPERATION_ABORTED)
  2404. {
  2405. OUTRESULT(BfpFileResult_Timeout);
  2406. return 0;
  2407. }
  2408. }
  2409. else
  2410. {
  2411. int lastError = ::GetLastError();
  2412. if (lastError == ERROR_PIPE_LISTENING)
  2413. {
  2414. overlapped.hEvent = file->mAsyncData->mEvent;
  2415. if (!::ConnectNamedPipe(file->mHandle, &overlapped))
  2416. {
  2417. int lastError = ::GetLastError();
  2418. if (lastError == ERROR_IO_PENDING)
  2419. {
  2420. if (!file->mAsyncData->WaitAndResetEvent(timeoutMS))
  2421. {
  2422. ::CancelIoEx(file->mHandle, &overlapped);
  2423. // Clear event set by CancelIoEx
  2424. file->mAsyncData->WaitAndResetEvent(0);
  2425. OUTRESULT(BfpFileResult_Timeout);
  2426. return 0;
  2427. }
  2428. }
  2429. }
  2430. // Now we have a connection, so retry the read...
  2431. continue;
  2432. }
  2433. else
  2434. {
  2435. OUTRESULT(BfpFileResult_UnknownError);
  2436. return 0;
  2437. }
  2438. }
  2439. OUTRESULT(BfpFileResult_Ok);
  2440. return overlapped.mBytesRead;
  2441. }
  2442. }
  2443. DWORD bytesRead = 0;
  2444. if (::ReadFile(file->mHandle, buffer, (uint32)size, &bytesRead, NULL))
  2445. {
  2446. if (bytesRead != size)
  2447. OUTRESULT(BfpFileResult_PartialData);
  2448. else
  2449. OUTRESULT(BfpFileResult_Ok);
  2450. return bytesRead;
  2451. }
  2452. int lastError = ::GetLastError();
  2453. switch (lastError)
  2454. {
  2455. case ERROR_BROKEN_PIPE: // Just an EOF
  2456. break;
  2457. default:
  2458. OUTRESULT(BfpFileResult_UnknownError);
  2459. break;
  2460. }
  2461. return bytesRead;
  2462. }
  2463. BFP_EXPORT void BFP_CALLTYPE BfpFile_Flush(BfpFile* file)
  2464. {
  2465. ::FlushFileBuffers(file->mHandle);
  2466. }
  2467. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_GetFileSize(BfpFile* file)
  2468. {
  2469. LARGE_INTEGER largeInteger;
  2470. largeInteger.QuadPart = 0;
  2471. ::GetFileSizeEx(file->mHandle, &largeInteger);
  2472. return largeInteger.QuadPart;
  2473. }
  2474. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_Seek(BfpFile* file, int64 offset, BfpFileSeekKind seekKind)
  2475. {
  2476. DWORD moveMethod;
  2477. if (seekKind == BfpFileSeekKind_Absolute)
  2478. moveMethod = FILE_BEGIN;
  2479. else if (seekKind == BfpFileSeekKind_Relative)
  2480. moveMethod = FILE_CURRENT;
  2481. else
  2482. moveMethod = FILE_END;
  2483. LARGE_INTEGER liOffset;
  2484. liOffset.QuadPart = offset;
  2485. LARGE_INTEGER newPos;
  2486. newPos.QuadPart = 0;
  2487. ::SetFilePointerEx(file->mHandle, liOffset, &newPos, moveMethod);
  2488. return newPos.QuadPart;
  2489. }
  2490. BFP_EXPORT void BFP_CALLTYPE BfpFile_Truncate(BfpFile* file)
  2491. {
  2492. SetEndOfFile(file->mHandle);
  2493. }
  2494. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFile_GetTime_LastWrite(const char* path)
  2495. {
  2496. UTF16String wPath = UTF8Decode(path);
  2497. BfpTimeStamp lastWriteTime = 0;
  2498. GetFileInfo(path, &lastWriteTime, NULL);
  2499. return lastWriteTime;
  2500. }
  2501. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFile_GetAttributes(const char* path, BfpFileResult* outResult)
  2502. {
  2503. uint32 fileAttributes;
  2504. GetFileInfo(path, NULL, &fileAttributes);
  2505. return FileAttributes_WinToBFP(fileAttributes);
  2506. }
  2507. BFP_EXPORT void BFP_CALLTYPE BfpFile_SetAttributes(const char* path, BfpFileAttributes attribs, BfpFileResult* outResult)
  2508. {
  2509. if (!::SetFileAttributesW(UTF8Decode(path).c_str(), FileAttributes_BFPToWin(attribs)))
  2510. {
  2511. OUTRESULT(BfpFileResult_UnknownError);
  2512. return;
  2513. }
  2514. OUTRESULT(BfpFileResult_Ok);
  2515. }
  2516. BFP_EXPORT void BFP_CALLTYPE BfpFile_Copy(const char* oldName, const char* newName, BfpFileCopyKind copyKind, BfpFileResult* outResult)
  2517. {
  2518. if (copyKind == BfpFileCopyKind_IfNewer)
  2519. {
  2520. BfpTimeStamp fromTime = 0;
  2521. GetFileInfo(oldName, &fromTime, NULL);
  2522. BfpTimeStamp toTime = 0;
  2523. GetFileInfo(newName, &toTime, NULL);
  2524. if ((toTime != 0) && (toTime >= fromTime))
  2525. {
  2526. OUTRESULT(BfpFileResult_Ok);
  2527. return;
  2528. }
  2529. }
  2530. UTF16String wOldPath = UTF8Decode(oldName);
  2531. UTF16String wNewPath = UTF8Decode(newName);
  2532. if (!::CopyFileW(wOldPath.c_str(), wNewPath.c_str(), copyKind == BfpFileCopyKind_IfNotExists))
  2533. {
  2534. switch (::GetLastError())
  2535. {
  2536. case ERROR_ALREADY_EXISTS:
  2537. OUTRESULT(BfpFileResult_AlreadyExists);
  2538. break;
  2539. case ERROR_PATH_NOT_FOUND:
  2540. OUTRESULT(BfpFileResult_NotFound);
  2541. break;
  2542. default:
  2543. OUTRESULT(BfpFileResult_UnknownError);
  2544. break;
  2545. }
  2546. }
  2547. else
  2548. {
  2549. OUTRESULT(BfpFileResult_Ok);
  2550. }
  2551. }
  2552. BFP_EXPORT void BFP_CALLTYPE BfpFile_Rename(const char* oldName, const char* newName, BfpFileResult* outResult)
  2553. {
  2554. UTF16String wOldPath = UTF8Decode(oldName);
  2555. UTF16String wNewPath = UTF8Decode(newName);
  2556. if (!::MoveFileW(wOldPath.c_str(), wNewPath.c_str()))
  2557. {
  2558. switch (::GetLastError())
  2559. {
  2560. case ERROR_ALREADY_EXISTS:
  2561. OUTRESULT(BfpFileResult_AlreadyExists);
  2562. break;
  2563. case ERROR_PATH_NOT_FOUND:
  2564. OUTRESULT(BfpFileResult_NotFound);
  2565. break;
  2566. default:
  2567. OUTRESULT(BfpFileResult_UnknownError);
  2568. break;
  2569. }
  2570. }
  2571. else
  2572. {
  2573. OUTRESULT(BfpFileResult_Ok);
  2574. }
  2575. }
  2576. BFP_EXPORT void BFP_CALLTYPE BfpFile_Delete(const char* path, BfpFileResult* outResult)
  2577. {
  2578. if (!::DeleteFileW(UTF8Decode(path).c_str()))
  2579. {
  2580. int lastError = GetLastError();
  2581. switch (lastError)
  2582. {
  2583. case ERROR_FILE_NOT_FOUND:
  2584. case ERROR_PATH_NOT_FOUND:
  2585. OUTRESULT(BfpFileResult_NotFound);
  2586. break;
  2587. default:
  2588. OUTRESULT(BfpFileResult_UnknownError);
  2589. break;
  2590. }
  2591. }
  2592. else
  2593. OUTRESULT(BfpFileResult_Ok);
  2594. }
  2595. BFP_EXPORT bool BFP_CALLTYPE BfpFile_Exists(const char* path)
  2596. {
  2597. WIN32_FIND_DATAW findData;
  2598. HANDLE handleVal = FindFirstFileW(UTF8Decode(path).c_str(), &findData);
  2599. if (handleVal == INVALID_HANDLE_VALUE)
  2600. return false;
  2601. FindClose(handleVal);
  2602. return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
  2603. }
  2604. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempPath(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  2605. {
  2606. WCHAR wStr[4096];
  2607. ::GetTempPathW(4096, wStr);
  2608. String str = UTF8Encode(wStr);
  2609. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  2610. }
  2611. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempFileName(char* outName, int* inOutNameSize, BfpFileResult* outResult)
  2612. {
  2613. WCHAR wPath[4096];
  2614. wPath[0] = 0;
  2615. ::GetTempPathW(4096, wPath);
  2616. WCHAR wFileName[4096];
  2617. wFileName[0] = 0;
  2618. GetTempFileNameW(wPath, L"tmp", 0, wFileName);
  2619. String str = UTF8Encode(wFileName);
  2620. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  2621. }
  2622. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetFullPath(const char* inPath, char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  2623. {
  2624. WCHAR wPath[4096];
  2625. wPath[0] = 0;
  2626. GetFullPathNameW(UTF8Decode(inPath).c_str(), 4096, wPath, NULL);
  2627. String str = UTF8Encode(wPath);
  2628. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  2629. }
  2630. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetActualPath(const char* inPathC, char* outPathC, int* inOutPathSize, BfpFileResult* outResult)
  2631. {
  2632. String inPath = inPathC;
  2633. String outPath;
  2634. // This is quite involved, but the meat is SHGetFileInfo
  2635. //const wchar8_t kSeparator = L'\\';
  2636. // copy input string because we'll be temporary modifying it in place
  2637. //size_t length = wcslen(path);
  2638. //wchar8_t buffer[MAX_PATH];
  2639. //memcpy( buffer, path, (length+1) * sizeof(path[0]) );
  2640. int32 i = 0;
  2641. //UTF16String result;
  2642. // for network paths (\\server\share\RestOfPath), getting the display
  2643. // name mangles it into unusable form (e.g. "\\server\share" turns
  2644. // into "share on server (server)"). So detect this case and just skip
  2645. // up to two path components
  2646. int length = (int)inPath.length();
  2647. if (length >= 2 && inPath[0] == DIR_SEP_CHAR && inPath[1] == DIR_SEP_CHAR)
  2648. {
  2649. int skippedCount = 0;
  2650. i = 2; // start after '\\'
  2651. while (i < length && skippedCount < 2)
  2652. {
  2653. if (inPath[i] == DIR_SEP_CHAR)
  2654. ++skippedCount;
  2655. ++i;
  2656. }
  2657. outPath.Append(inPath.c_str(), i);
  2658. }
  2659. // for drive names, just add it uppercased
  2660. else if (length >= 2 && inPath[1] == ':')
  2661. {
  2662. outPath.Append(toupper(inPath[0]));
  2663. outPath.Append(':');
  2664. if ((length >= 3) &&
  2665. ((inPath[2] == DIR_SEP_CHAR) || (inPath[2] == DIR_SEP_CHAR_ALT)))
  2666. {
  2667. outPath.Append(DIR_SEP_CHAR);
  2668. i = 3; // start after drive, colon and separator
  2669. }
  2670. else
  2671. {
  2672. i = 2; // start after drive and colon
  2673. }
  2674. }
  2675. if ((i == 0) && (length >= 1) &&
  2676. ((inPath[0] == DIR_SEP_CHAR) || (inPath[1] == DIR_SEP_CHAR_ALT)))
  2677. {
  2678. i++; // start after initial slash
  2679. outPath.Append(DIR_SEP_CHAR);
  2680. }
  2681. int32 lastComponentStart = i;
  2682. bool addSeparator = false;
  2683. String subName;
  2684. while (i < length)
  2685. {
  2686. // skip until path separator
  2687. while ((i < length) && (inPath[i] != DIR_SEP_CHAR) && (inPath[i] != DIR_SEP_CHAR_ALT))
  2688. ++i;
  2689. if (addSeparator)
  2690. outPath.Append(DIR_SEP_CHAR);
  2691. SHFILEINFOW info = { 0 };
  2692. subName.Clear();
  2693. subName = inPath.Substring(0, i);
  2694. for (int j = 0; j < (int)subName.length(); j++)
  2695. if (subName[j] == DIR_SEP_CHAR_ALT)
  2696. subName[j] = DIR_SEP_CHAR;
  2697. info.szDisplayName[0] = 0;
  2698. int32 size = (int32)sizeof(SHFILEINFOW);
  2699. if (SHGetFileInfoW(UTF8Decode(subName).c_str(), 0, &info, (int32)sizeof(SHFILEINFOW), SHGFI_DISPLAYNAME))
  2700. {
  2701. outPath.Append(UTF8Encode(info.szDisplayName));
  2702. }
  2703. else
  2704. {
  2705. // most likely file does not exist.
  2706. // So just append original path name component.
  2707. outPath.Append(inPath.Substring(lastComponentStart, i - lastComponentStart));
  2708. }
  2709. ++i;
  2710. // Ignore multiple slashes in a row
  2711. while ((i < length) && ((inPath[i] == DIR_SEP_CHAR) || (inPath[i] == DIR_SEP_CHAR_ALT)))
  2712. ++i;
  2713. lastComponentStart = i;
  2714. addSeparator = true;
  2715. }
  2716. TryStringOut(outPath, outPathC, inOutPathSize, (BfpResult*)outResult);
  2717. }
  2718. // BfpFindFileData
  2719. struct BfpFindFileData
  2720. {
  2721. BfpFindFileFlags mFlags;
  2722. WIN32_FIND_DATA mFindData;
  2723. HANDLE mHandle;
  2724. };
  2725. #define HANDLE_TO_BFPFINDFILEDATA(handle) ((BfpFindFileData*)(handle))
  2726. #define BFPFINDFILEDATA_TO_HANDLE(findData) ((HANDLE)(findData))
  2727. static bool BfpFindFileData_CheckFilter(BfpFindFileData* findData)
  2728. {
  2729. bool isDir = (findData->mFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  2730. if (isDir)
  2731. {
  2732. if ((findData->mFlags & BfpFindFileFlag_Directories) != 0)
  2733. {
  2734. if ((wcscmp(findData->mFindData.cFileName, L".") == 0) || (wcscmp(findData->mFindData.cFileName, L"..") == 0))
  2735. {
  2736. return false;
  2737. }
  2738. return true;
  2739. }
  2740. }
  2741. else
  2742. {
  2743. if ((findData->mFlags & BfpFindFileFlag_Files) != 0)
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. BFP_EXPORT BfpFindFileData* BFP_CALLTYPE BfpFindFileData_FindFirstFile(const char* path, BfpFindFileFlags flags, BfpFileResult* outResult)
  2749. {
  2750. UTF16String wPath = UTF8Decode(path);
  2751. BfpFindFileData* findData = new BfpFindFileData();
  2752. findData->mFlags = flags;
  2753. FINDEX_SEARCH_OPS searchOps;
  2754. if ((flags & BfpFindFileFlag_Files) == 0)
  2755. searchOps = FindExSearchLimitToDirectories;
  2756. else
  2757. searchOps = FindExSearchNameMatch;
  2758. findData->mHandle = ::FindFirstFileExW(wPath.c_str(), FindExInfoBasic, &findData->mFindData, searchOps, NULL, 0);
  2759. if (findData->mHandle == INVALID_HANDLE_VALUE)
  2760. {
  2761. if (outResult != NULL)
  2762. {
  2763. switch (GetLastError())
  2764. {
  2765. default:
  2766. *outResult = BfpFileResult_UnknownError;
  2767. break;
  2768. }
  2769. }
  2770. delete findData;
  2771. return NULL;
  2772. }
  2773. if (!BfpFindFileData_CheckFilter(findData))
  2774. {
  2775. if (!BfpFindFileData_FindNextFile(findData))
  2776. {
  2777. ::FindClose(findData->mHandle);
  2778. if (outResult != NULL)
  2779. *outResult = BfpFileResult_NoResults;
  2780. delete findData;
  2781. return NULL;
  2782. }
  2783. }
  2784. OUTRESULT(BfpFileResult_Ok);
  2785. return findData;
  2786. }
  2787. BFP_EXPORT bool BFP_CALLTYPE BfpFindFileData_FindNextFile(BfpFindFileData* findData)
  2788. {
  2789. while (true)
  2790. {
  2791. if (!::FindNextFileW(findData->mHandle, &findData->mFindData))
  2792. return false;
  2793. if (BfpFindFileData_CheckFilter(findData))
  2794. return true;
  2795. }
  2796. }
  2797. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_GetFileName(BfpFindFileData* findData, char* outName, int* inOutNameSize, BfpFileResult* outResult)
  2798. {
  2799. String name = UTF8Encode(findData->mFindData.cFileName);
  2800. TryStringOut(name, outName, inOutNameSize, (BfpResult*)outResult);
  2801. }
  2802. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_LastWrite(BfpFindFileData* findData)
  2803. {
  2804. return *(BfpTimeStamp*)&findData->mFindData.ftLastWriteTime;
  2805. }
  2806. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Created(BfpFindFileData* findData)
  2807. {
  2808. return *(BfpTimeStamp*)&findData->mFindData.ftCreationTime;
  2809. }
  2810. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Access(BfpFindFileData* findData)
  2811. {
  2812. return *(BfpTimeStamp*)&findData->mFindData.ftLastAccessTime;
  2813. }
  2814. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFindFileData_GetFileAttributes(BfpFindFileData* findData)
  2815. {
  2816. return FileAttributes_WinToBFP(findData->mFindData.dwFileAttributes);
  2817. }
  2818. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_Release(BfpFindFileData* findData)
  2819. {
  2820. ::FindClose(findData->mHandle);
  2821. delete findData;
  2822. }
  2823. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetCurrent(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  2824. {
  2825. wchar_t* wCwdStr = _wgetcwd(NULL, 0);
  2826. String str = UTF8Encode(wCwdStr);
  2827. free(wCwdStr);
  2828. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  2829. }
  2830. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_SetCurrent(const char* path, BfpFileResult* outResult)
  2831. {
  2832. UTF16String wPath = UTF8Decode(path);
  2833. if (_wchdir(wPath.c_str()) == -1)
  2834. OUTRESULT(BfpFileResult_UnknownError);
  2835. else
  2836. OUTRESULT(BfpFileResult_Ok);
  2837. }
  2838. BFP_EXPORT int BFP_CALLTYPE BfpStack_CaptureBackTrace(int framesToSkip, intptr* outFrames, int wantFrameCount)
  2839. {
  2840. return (int)RtlCaptureStackBackTrace(framesToSkip + 1, wantFrameCount, (void**)outFrames, NULL);
  2841. }
  2842. BFP_EXPORT void BFP_CALLTYPE BfpOutput_DebugString(const char* str)
  2843. {
  2844. OutputDebugStringA(str);
  2845. }