LinuxCommon.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. #include "Common.h"
  2. #include "BFPlatform.h"
  3. #include <sys/stat.h>
  4. #include <sys/sysinfo.h>
  5. #include <sys/wait.h>
  6. #include <dlfcn.h>
  7. #include <wchar.h>
  8. #include <fcntl.h>
  9. #include <time.h>
  10. #include <link.h>
  11. #include <dlfcn.h>
  12. #include <dirent.h>
  13. #include <syslog.h>
  14. #include <unistd.h>
  15. #include <execinfo.h>
  16. #include <signal.h>
  17. #include <spawn.h>
  18. #include "../PlatformInterface.h"
  19. #include "../PlatformHelper.h"
  20. #include "../util/CritSect.h"
  21. #include "../util/Dictionary.h"
  22. #include "../util/Hash.h"
  23. #include "backtrace.h"
  24. #include "backtrace-supported.h"
  25. #include "../third_party/stb/stb_sprintf.h"
  26. #include <cxxabi.h>
  27. #include <random>
  28. USING_NS_BF;
  29. struct BfpPipeInfo
  30. {
  31. String mPipePath;
  32. int mWriteHandle;
  33. };
  34. struct BfpFile
  35. {
  36. BfpPipeInfo* mPipeInfo;
  37. int mHandle;
  38. bool mNonBlocking;
  39. bool mAllowTimeout;
  40. bool mIsStd;
  41. BfpFile()
  42. {
  43. mPipeInfo = NULL;
  44. mHandle = -1;
  45. mNonBlocking = false;
  46. mAllowTimeout = false;
  47. mIsStd = false;
  48. }
  49. BfpFile(int handle)
  50. {
  51. mPipeInfo = NULL;
  52. mHandle = handle;
  53. mNonBlocking = false;
  54. mAllowTimeout = false;
  55. mIsStd = false;
  56. }
  57. ~BfpFile()
  58. {
  59. delete mPipeInfo;
  60. }
  61. };
  62. BfpTimeStamp BfpToTimeStamp(const timespec& ts)
  63. {
  64. return (int64)(ts.tv_sec * 10000000) + (int64)(ts.tv_nsec / 100) + 116444736000000000;
  65. }
  66. int gBFPlatformLastError = 0;
  67. uint32 Beefy::BFTickCount()
  68. {
  69. struct timespec now;
  70. if (clock_gettime(CLOCK_MONOTONIC, &now))
  71. return 0;
  72. return (uint32)((uint64)now.tv_sec * 1000.0 + (uint64)now.tv_nsec / 1000000);
  73. }
  74. int64 Beefy::EndianSwap(int64 val)
  75. {
  76. return __builtin_bswap64(val);
  77. }
  78. /*int* GetStdHandle(int32 handleId)
  79. {
  80. if (handleId == STD_INPUT_HANDLE)
  81. return (int*)STDIN_FILENO;
  82. if (handleId == STD_OUTPUT_HANDLE)
  83. return (int*)STDOUT_FILENO;
  84. return (int*)STDERR_FILENO;
  85. }*/
  86. /*int32 GetFileType(HANDLE fileHandle)
  87. {
  88. if (isatty(file->mHandleHandle))
  89. return FILE_TYPE_CHAR;
  90. return FILE_TYPE_DISK;
  91. }*/
  92. /*bool WriteFile(HANDLE hFile, void* lpBuffer, uint32 nNumberOfBytesToWrite, uint32* lpNumberOfBytesWritten, OVERLAPPED* lpOverlapped)
  93. {
  94. #ifdef BF_PLATFORM_IOS
  95. int logType = -1;
  96. if (hFile == (int*)STDOUT_FILENO)
  97. logType = LOG_WARNING;
  98. else if (hFile == (int*)STDERR_FILENO)
  99. logType = LOG_ERR;
  100. if (logType != -1)
  101. {
  102. static std::string strOut;
  103. strOut.resize(nNumberOfBytesToWrite);
  104. memcpy(&strOut[0], lpBuffer, nNumberOfBytesToWrite);
  105. if ((strOut[0] != '\r') && (strOut[0] != '\n'))
  106. syslog(LOG_WARNING, "%s", strOut.c_str());
  107. }
  108. #endif
  109. int writeCount = (int)::write((int)(intptr)hFile, lpBuffer, nNumberOfBytesToWrite);
  110. if (writeCount == -1)
  111. {
  112. //TODO: set gBFPlatformLastError
  113. lpNumberOfBytesWritten = 0;
  114. return false;
  115. }
  116. *lpNumberOfBytesWritten = (uint32)writeCount;
  117. return true;
  118. }*/
  119. int64 Beefy::GetFileTimeWrite(const StringImpl& path)
  120. {
  121. struct stat statbuf = {0};
  122. int result = stat(path.c_str(), &statbuf);
  123. if (result == -1)
  124. return 0;
  125. //int64 fileTime = 0;
  126. //BFSystemTimeToFileTime(statbuf.st_mtime, 0, &fileTime);
  127. return statbuf.st_mtime;
  128. }
  129. /*DWORD GetTimeZoneInformation(TIME_ZONE_INFORMATION* lpTimeZoneInformation)
  130. {
  131. std::wstring tzName0 = Beefy::UTF8Decode(tzname[0]);
  132. std::wstring tzName1 = Beefy::UTF8Decode(tzname[1]);
  133. bool isDST = false;
  134. time_t timeNow;
  135. time(&timeNow);
  136. tm tmNow = *gmtime(&timeNow);
  137. isDST = tmNow.tm_isdst;
  138. struct tm checkTM;
  139. memset(&checkTM, 0, sizeof(tm));
  140. checkTM.tm_mday = 1;
  141. checkTM.tm_year = tmNow.tm_year;
  142. time_t checkTime = mktime(&checkTM);
  143. time_t lastOffset = 0;
  144. time_t minOffset = 0;
  145. time_t maxOffset = 0;
  146. for (int pass = 0; pass < 2; pass++)
  147. {
  148. int searchDir = 60*60*24;
  149. int thresholdCount = 0;
  150. while (true)
  151. {
  152. checkTime += searchDir;
  153. tm checkTM = *gmtime(&checkTime);
  154. if (checkTM.tm_year != tmNow.tm_year)
  155. break; // No DST
  156. mktime(&checkTM);
  157. time_t offset = checkTM.tm_gmtoff;
  158. if (lastOffset != offset)
  159. {
  160. if (thresholdCount == 0)
  161. {
  162. minOffset = offset;
  163. maxOffset = offset;
  164. }
  165. else if (thresholdCount == 3)
  166. {
  167. SYSTEMTIME* sysTimeP = (offset == minOffset) ?
  168. &lpTimeZoneInformation->StandardDate :
  169. &lpTimeZoneInformation->DaylightDate;
  170. if (offset == minOffset)
  171. tzName0 = Beefy::UTF8Decode(checkTM.tm_zone);
  172. else
  173. tzName1 = Beefy::UTF8Decode(checkTM.tm_zone);
  174. sysTimeP->wDay = 0;
  175. sysTimeP->wDayOfWeek = 0;
  176. sysTimeP->wYear = checkTM.tm_year + 1900;
  177. sysTimeP->wMonth = checkTM.tm_mon;
  178. sysTimeP->wDay = checkTM.tm_mday + 1;
  179. sysTimeP->wHour = checkTM.tm_hour;
  180. sysTimeP->wMinute = checkTM.tm_min;
  181. sysTimeP->wSecond = checkTM.tm_sec;
  182. sysTimeP->wMilliseconds = 0;
  183. break;
  184. }
  185. else
  186. {
  187. if (thresholdCount == 1)
  188. searchDir /= -24;
  189. else
  190. searchDir /= -60;
  191. minOffset = std::min(minOffset, offset);
  192. maxOffset = std::max(maxOffset, offset);
  193. }
  194. thresholdCount++;
  195. lastOffset = offset;
  196. }
  197. }
  198. }
  199. wcsncpy(lpTimeZoneInformation->StandardName, tzName0.c_str(), 32);
  200. wcsncpy(lpTimeZoneInformation->DaylightName, tzName1.c_str(), 32);
  201. lpTimeZoneInformation->DaylightBias = (int32)maxOffset;
  202. lpTimeZoneInformation->StandardBias = (int32)minOffset;
  203. if (minOffset == maxOffset)
  204. return 0;
  205. return isDST ? 2 : 1;
  206. }*/
  207. bool Beefy::FileExists(const StringImpl& path, String* outActualName)
  208. {
  209. struct stat statbuf = {0};
  210. int result = stat(path.c_str(), &statbuf);
  211. if (result != 0)
  212. return false;
  213. return !S_ISDIR(statbuf.st_mode);
  214. }
  215. bool Beefy::DirectoryExists(const StringImpl& path, String* outActualName)
  216. {
  217. struct stat statbuf = {0};
  218. int result = stat(path.c_str(), &statbuf);
  219. if (result != 0)
  220. return false;
  221. return S_ISDIR(statbuf.st_mode);
  222. }
  223. uint64 Beefy::BFGetTickCountMicro()
  224. {
  225. struct timespec now;
  226. if (clock_gettime(CLOCK_MONOTONIC, &now))
  227. return 0;
  228. return ((uint64)now.tv_sec * 1000000.0 + (uint64)now.tv_nsec / 1000);
  229. }
  230. uint64 Beefy::BFGetTickCountMicroFast()
  231. {
  232. return BFGetTickCountMicro();
  233. }
  234. /*
  235. int64 abs(int64 val)
  236. {
  237. return llabs(val);
  238. }
  239. */
  240. void mkdir(const char* path)
  241. {
  242. mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  243. }
  244. typedef void(*CrashInfoFunc)();
  245. static CritSect gSysCritSect;
  246. static String gCrashInfo;
  247. static Array<CrashInfoFunc> gCrashInfoFuncs;
  248. struct bt_ctx {
  249. struct backtrace_state *state;
  250. int error;
  251. };
  252. static void error_callback(void *data, const char *msg, int errnum)
  253. {
  254. struct bt_ctx *ctx = (bt_ctx*)data;
  255. fprintf(stderr, "ERROR: %s (%d)", msg, errnum);
  256. ctx->error = 1;
  257. }
  258. static void syminfo_callback (void *data, uintptr_t pc, const char *symname, uintptr_t symval, uintptr_t symsize)
  259. {
  260. char str[4096];
  261. if (symname)
  262. stbsp_snprintf(str, 4096, "%@ %s\n", pc, symname);
  263. else
  264. stbsp_snprintf(str, 4096, "%@\n", pc);
  265. fputs(str, stderr);
  266. }
  267. static int full_callback(void *data, uintptr_t pc, const char* filename, int lineno, const char* function)
  268. {
  269. struct bt_ctx *ctx = (bt_ctx*)data;
  270. if (function)
  271. {
  272. int status = -1;
  273. char* demangledName = abi::__cxa_demangle(function, NULL, NULL, &status );
  274. const char* showName = (demangledName != NULL) ? demangledName : function;
  275. char str[4096];
  276. stbsp_snprintf(str, 4096, "%@ %s %s:%d\n", pc, showName, filename?filename:"??", lineno);
  277. fputs(str, stderr);
  278. if (demangledName != NULL)
  279. free(demangledName);
  280. }
  281. else
  282. backtrace_syminfo (ctx->state, pc, syminfo_callback, error_callback, data);
  283. return 0;
  284. }
  285. static int simple_callback(void *data, uintptr_t pc)
  286. {
  287. struct bt_ctx *ctx = (bt_ctx*)data;
  288. backtrace_pcinfo(ctx->state, pc, full_callback, error_callback, data);
  289. return 0;
  290. }
  291. static inline void bt(struct backtrace_state *state)
  292. {
  293. struct bt_ctx ctx = {state, 0};
  294. //backtrace_print(state, 0, stdout);
  295. backtrace_simple(state, 2, simple_callback, error_callback, &ctx);
  296. }
  297. static String gCmdLine;
  298. static String gExePath;
  299. static void Crashed()
  300. {
  301. //
  302. {
  303. AutoCrit autoCrit(gSysCritSect);
  304. String debugDump;
  305. debugDump += "**** FATAL APPLICATION ERROR ****\n";
  306. for (auto func : gCrashInfoFuncs)
  307. func();
  308. if (!gCrashInfo.IsEmpty())
  309. {
  310. debugDump += gCrashInfo;
  311. debugDump += "\n";
  312. }
  313. fprintf(stderr, "%s", debugDump.c_str());
  314. }
  315. struct backtrace_state *state = backtrace_create_state(gExePath.c_str(), BACKTRACE_SUPPORTS_THREADS, error_callback, NULL);
  316. bt(state);
  317. /*void* array[10];
  318. size_t size;
  319. char** strings;
  320. size_t i;
  321. size = backtrace(array, 10);
  322. strings = backtrace_symbols(array, size);
  323. for (i = 0; i < size; i++)
  324. fprintf(stderr, "%s\n", strings[i]);
  325. free(strings);*/
  326. exit(1);
  327. }
  328. static void SigHandler(int sig)
  329. {
  330. //printf("SigHandler paused...\n");
  331. const char* sigName = NULL;
  332. switch (sig)
  333. {
  334. case SIGFPE:
  335. sigName = "SIGFPE";
  336. break;
  337. case SIGSEGV:
  338. sigName = "SIGSEGV";
  339. break;
  340. case SIGABRT:
  341. sigName = "SIGABRT";
  342. break;
  343. case SIGILL:
  344. sigName = "SIGILL";
  345. break;
  346. }
  347. if (sigName != NULL)
  348. gCrashInfo += StrFormat("Signal: %s\n", sigName);
  349. else
  350. gCrashInfo += StrFormat("Signal: %d\n", sig);
  351. Crashed();
  352. }
  353. BFP_EXPORT void BFP_CALLTYPE BfpSystem_Init(int version, BfpSystemInitFlags flags)
  354. {
  355. if (version != BFP_VERSION)
  356. {
  357. BfpSystem_FatalError(StrFormat("Bfp build version '%d' does not match requested version '%d'", BFP_VERSION, version).c_str(), "BFP FATAL ERROR");
  358. }
  359. signal(SIGSEGV, SigHandler);
  360. signal(SIGFPE, SigHandler);
  361. signal(SIGABRT, SigHandler);
  362. }
  363. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCommandLine(int argc, char** argv)
  364. {
  365. char* relPath = argv[0];
  366. char* cwd = getcwd(NULL, 0);
  367. gExePath = GetAbsPath(relPath, cwd);
  368. free(cwd);
  369. for (int i = 0; i < argc; i++)
  370. {
  371. if (i != 0)
  372. gCmdLine.Append(' ');
  373. String arg = argv[i];
  374. if ((arg.Contains(' ')) || (arg.Contains('\"')))
  375. {
  376. arg.Replace("\"", "\\\"");
  377. gCmdLine.Append("\"");
  378. gCmdLine.Append(arg);
  379. gCmdLine.Append("\"");
  380. }
  381. else
  382. gCmdLine.Append(arg);
  383. }
  384. }
  385. BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashReportKind(BfpCrashReportKind crashReportKind)
  386. {
  387. }
  388. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfoFunc(BfpCrashInfoFunc crashInfoFunc)
  389. {
  390. AutoCrit autoCrit(gSysCritSect);
  391. gCrashInfoFuncs.Add(crashInfoFunc);
  392. }
  393. BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfo(const char* str) // Can do at any time, or during CrashInfoFunc callbacks
  394. {
  395. AutoCrit autoCrit(gSysCritSect);
  396. gCrashInfo.Append(str);
  397. }
  398. void BfpSystem_Shutdown()
  399. {
  400. }
  401. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_TickCount()
  402. {
  403. return Beefy::BFTickCount();
  404. }
  405. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpSystem_GetTimeStamp()
  406. {
  407. struct timeval tv;
  408. BfpTimeStamp result = 11644473600LL;
  409. gettimeofday(&tv, NULL);
  410. result += tv.tv_sec;
  411. result *= 10000000LL;
  412. result += tv.tv_usec * 10;
  413. return result;
  414. }
  415. BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_EndianSwap16(uint16 val)
  416. {
  417. return __builtin_bswap16(val);
  418. }
  419. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_EndianSwap32(uint32 val)
  420. {
  421. return __builtin_bswap32(val);
  422. }
  423. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_EndianSwap64(uint64 val)
  424. {
  425. return __builtin_bswap64(val);
  426. }
  427. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchange32(uint32* ptr, uint32 val)
  428. {
  429. // __sync_lock_test_and_set only has Acquire semantics, so we need a __sync_synchronize to enforce a full barrier
  430. uint32 prevVal = __sync_lock_test_and_set(ptr, val);
  431. __sync_synchronize();
  432. return prevVal;
  433. }
  434. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchange64(uint64* ptr, uint64 val)
  435. {
  436. // __sync_lock_test_and_set only has Acquire semantics, so we need a __sync_synchronize to enforce a full barrier
  437. uint64 prevVal = __sync_lock_test_and_set(ptr, val);
  438. __sync_synchronize();
  439. return prevVal;
  440. }
  441. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd32(uint32* ptr, uint32 val)
  442. {
  443. return __sync_fetch_and_add(ptr, val);
  444. }
  445. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd64(uint64* ptr, uint64 val)
  446. {
  447. return __sync_fetch_and_add(ptr, val);
  448. }
  449. BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange32(uint32* ptr, uint32 oldVal, uint32 newVal)
  450. {
  451. return __sync_val_compare_and_swap(ptr, oldVal, newVal);
  452. }
  453. BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange64(uint64* ptr, uint64 oldVal, uint64 newVal)
  454. {
  455. return __sync_val_compare_and_swap(ptr, oldVal, newVal);
  456. }
  457. BFP_EXPORT void BFP_CALLTYPE BfpSystem_FatalError(const char* error, const char* title)
  458. {
  459. fprintf(stderr, "%s\n", error);
  460. fflush(stderr);
  461. Crashed();
  462. }
  463. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetCommandLine(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  464. {
  465. TryStringOut(gCmdLine, outStr, inOutStrSize, (BfpResult*)outResult);
  466. }
  467. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetExecutablePath(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  468. {
  469. TryStringOut(gExePath, outStr, inOutStrSize, (BfpResult*)outResult);
  470. }
  471. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetEnvironmentStrings(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  472. {
  473. String env;
  474. char** envPtr = environ;
  475. while (true)
  476. {
  477. char* envStr = *envPtr;
  478. env.Append(envStr, strlen(envStr) + 1);
  479. ++envPtr;
  480. }
  481. TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
  482. }
  483. BFP_EXPORT int BFP_CALLTYPE BfpSystem_GetNumLogicalCPUs(BfpSystemResult* outResult)
  484. {
  485. OUTRESULT(BfpSystemResult_Ok);
  486. return get_nprocs_conf();
  487. }
  488. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTick()
  489. {
  490. return 10000000;
  491. }
  492. BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTickFreq()
  493. {
  494. struct timespec now;
  495. clock_gettime(CLOCK_MONOTONIC, &now);
  496. return (now.tv_sec * 10000000LL) + now.tv_nsec / 100;
  497. }
  498. BFP_EXPORT void BFP_CALLTYPE BfpSystem_CreateGUID(BfpGUID* outGuid)
  499. {
  500. // uuid_t guid;
  501. // uuid_generate(guid);
  502. // BfpGUID bfpGuid;
  503. // memcpy(&bfpGuid, guid, 16);
  504. // return bfpGuid;
  505. uint8* ptr = (uint8*)outGuid;
  506. std::random_device rd;
  507. std::mt19937 gen(rd());
  508. std::uniform_int_distribution<uint8> dis(0, 255);
  509. for (int i = 0; i < 16; i++)
  510. ptr[i] = dis(gen);
  511. // variant must be 10xxxxxx
  512. ptr[8] &= 0xBF;
  513. ptr[8] |= 0x80;
  514. // version must be 0100xxxx
  515. ptr[6] &= 0x4F;
  516. ptr[6] |= 0x40;
  517. }
  518. BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetComputerName(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
  519. {
  520. char hostName[1024];
  521. gethostname(hostName, 1024);
  522. TryStringOut(hostName, outStr, inOutStrSize, (BfpResult*)outResult);
  523. }
  524. // BfpProcess
  525. BFP_EXPORT intptr BFP_CALLTYPE BfpProcess_GetCurrentId()
  526. {
  527. return getpid();
  528. }
  529. BFP_EXPORT bool BFP_CALLTYPE BfpProcess_IsRemoteMachine(const char* machineName)
  530. {
  531. return false;
  532. }
  533. BFP_EXPORT BfpProcess* BFP_CALLTYPE BfpProcess_GetById(const char* machineName, int processId, BfpProcessResult* outResult)
  534. {
  535. NOT_IMPL;
  536. return NULL;
  537. }
  538. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Enumerate(const char* machineName, BfpProcess** outProcesses, int* inOutProcessesSize, BfpProcessResult* outResult)
  539. {
  540. NOT_IMPL;
  541. }
  542. BFP_EXPORT void BFP_CALLTYPE BfpProcess_Release(BfpProcess* process)
  543. {
  544. NOT_IMPL;
  545. }
  546. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetMainWindowTitle(BfpProcess* process, char* outTitle, int* inOutTitleSize, BfpProcessResult* outResult)
  547. {
  548. NOT_IMPL;
  549. }
  550. BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetProcessName(BfpProcess* process, char* outName, int* inOutNameSize, BfpProcessResult* outResult)
  551. {
  552. NOT_IMPL;
  553. }
  554. BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetProcessId(BfpProcess* process)
  555. {
  556. NOT_IMPL;
  557. return 0;
  558. }
  559. // BfpSpawn
  560. struct BfpSpawn
  561. {
  562. int mPid;
  563. bool mExited;
  564. int mStatus;
  565. int mStdInFD;
  566. int mStdOutFD;
  567. int mStdErrFD;
  568. };
  569. BFP_EXPORT BfpSpawn* BFP_CALLTYPE BfpSpawn_Create(const char* inTargetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
  570. {
  571. Beefy::Array<Beefy::StringView> stringViews;
  572. //printf("Executing: %s %s %x\n", inTargetPath, args, flags);
  573. if ((workingDir != NULL) && (workingDir[0] != 0))
  574. {
  575. if (chdir(workingDir) != 0)
  576. {
  577. //printf("CHDIR failed %s\n", workingDir);
  578. OUTRESULT(BfpSpawnResult_UnknownError);
  579. return NULL;
  580. }
  581. }
  582. String newArgs;
  583. String tempFileName;
  584. if ((flags & BfpSpawnFlag_UseArgsFile) != 0)
  585. {
  586. char tempFileNameStr[256];
  587. int size = 256;
  588. BfpFileResult fileResult;
  589. BfpFile_GetTempFileName(tempFileNameStr, &size, &fileResult);
  590. if (fileResult == BfpFileResult_Ok)
  591. {
  592. tempFileName = tempFileNameStr;
  593. BfpFileResult fileResult;
  594. BfpFile* file = BfpFile_Create(tempFileNameStr, BfpFileCreateKind_CreateAlways, BfpFileCreateFlag_Write, BfpFileAttribute_Normal, &fileResult);
  595. if (file == NULL)
  596. {
  597. OUTRESULT(BfpSpawnResult_TempFileError);
  598. return NULL;
  599. }
  600. if ((flags & BfpSpawnFlag_UseArgsFile_Native) != 0)
  601. {
  602. UTF16String wStr = UTF8Decode(args);
  603. if ((flags & BfpSpawnFlag_UseArgsFile_BOM) != 0)
  604. {
  605. uint8 bom[2] = { 0xFF, 0xFE };
  606. BfpFile_Write(file, bom, 2, -1, NULL);
  607. }
  608. BfpFile_Write(file, wStr.c_str(), wStr.length() * 2, -1, NULL);
  609. }
  610. else
  611. BfpFile_Write(file, args, strlen(args), -1, NULL);
  612. BfpFile_Release(file);
  613. newArgs.Append("@");
  614. newArgs.Append(tempFileName);
  615. if (newArgs.Contains(' '))
  616. {
  617. newArgs.Insert(0, '\"');
  618. newArgs.Append('\"');
  619. }
  620. args = newArgs.c_str();
  621. }
  622. }
  623. int32 firstCharIdx = -1;
  624. bool inQuote = false;
  625. String targetPath = inTargetPath;
  626. String verb;
  627. if ((flags & BfpSpawnFlag_UseShellExecute) != 0)
  628. {
  629. String target = targetPath;
  630. int barPos = (int)target.IndexOf('|');
  631. if (barPos != -1)
  632. {
  633. verb = targetPath.Substring(barPos + 1);
  634. targetPath.RemoveToEnd(barPos);
  635. }
  636. }
  637. int32 i = 0;
  638. for ( ; true; i++)
  639. {
  640. char c = args[i];
  641. if (c == '\0')
  642. break;
  643. if ((c == ' ') && (!inQuote))
  644. {
  645. if (firstCharIdx != -1)
  646. {
  647. stringViews.Add(Beefy::StringView(args, firstCharIdx, i - firstCharIdx));
  648. firstCharIdx = -1;
  649. }
  650. }
  651. else
  652. {
  653. if (firstCharIdx == -1)
  654. firstCharIdx = i;
  655. if (c == '"')
  656. inQuote = !inQuote;
  657. else if ((inQuote) && (c == '\\'))
  658. {
  659. c = args[i + 1];
  660. if (c == '"')
  661. i++;
  662. }
  663. }
  664. }
  665. if (firstCharIdx != -1)
  666. stringViews.Add(Beefy::StringView(args, firstCharIdx, i - firstCharIdx));
  667. Beefy::Array<char*> argvArr;
  668. if ((flags & BfpSpawnFlag_ArgsIncludesTarget) == 0)
  669. argvArr.Add(strdup(targetPath.c_str()));
  670. for (int32 i = 0; i < (int32)stringViews.size(); i++)
  671. {
  672. Beefy::StringView stringView = stringViews[i];
  673. char* str = NULL;
  674. for (int32 pass = 0; pass < 2; pass++)
  675. {
  676. char* strPtr = str;
  677. int32 strPos = 0;
  678. for (int32 char8Idx = 0; char8Idx < stringView.mLength; char8Idx++)
  679. {
  680. char c = stringView.mPtr[char8Idx];
  681. if (c == '"')
  682. inQuote = !inQuote;
  683. else
  684. {
  685. if ((inQuote) && (c == '\\') && (char8Idx < stringView.mLength - 1))
  686. {
  687. char nextC = stringView.mPtr[char8Idx + 1];
  688. if (nextC == '"')
  689. {
  690. c = nextC;
  691. char8Idx++;
  692. }
  693. }
  694. if (strPtr != NULL)
  695. *(strPtr++) = c;
  696. strPos++;
  697. }
  698. }
  699. if (pass == 0)
  700. str = (char*)malloc(strPos + 1);
  701. else
  702. *(strPtr++) = 0;
  703. }
  704. argvArr.Add(str);
  705. }
  706. argvArr.Add(NULL);
  707. char** argv = NULL;
  708. //pid_t pid = 0;
  709. //int status = posix_spawn(&pid, targetPath, NULL, NULL, &argvArr[0], environ);
  710. Beefy::Array<char*> envArr;
  711. if (env != NULL)
  712. {
  713. char* envPtr = (char*)env;
  714. while (true)
  715. {
  716. if (*envPtr == 0)
  717. break;
  718. envArr.Add(envPtr);
  719. envPtr += strlen(envPtr) + 1;
  720. }
  721. }
  722. envArr.Add(NULL);
  723. int stdInFD[2];
  724. int stdOutFD[2];
  725. int stdErrFD[2];
  726. bool failed = false;
  727. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  728. if (pipe(stdInFD) != 0)
  729. failed = true;
  730. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  731. if (pipe(stdOutFD) != 0)
  732. failed = true;
  733. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  734. if (pipe(stdErrFD) != 0)
  735. failed = true;
  736. if (failed)
  737. {
  738. //printf("Pipe failed\n");
  739. OUTRESULT(BfpSpawnResult_UnknownError);
  740. return NULL;
  741. }
  742. BfpSpawn* spawn;
  743. pid_t pid = fork();
  744. if (pid == -1) // Error
  745. {
  746. OUTRESULT(BfpSpawnResult_UnknownError);
  747. return NULL;
  748. }
  749. else if (pid == 0) // Child
  750. {
  751. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  752. while ((dup2(stdInFD[0], STDIN_FILENO) == -1) && (errno == EINTR)) {}
  753. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  754. while ((dup2(stdOutFD[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
  755. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  756. while ((dup2(stdErrFD[1], STDERR_FILENO) == -1) && (errno == EINTR)) {}
  757. // If successful then this shouldn't return at all:
  758. int result;
  759. if (env != NULL)
  760. result = execve(targetPath.c_str(), (char* const*)&argvArr[0], (char* const*)&envArr[0]);
  761. else
  762. result = execv(targetPath.c_str(), (char* const*)&argvArr[0]);
  763. printf("Couldn't execute %s\n", targetPath.c_str());
  764. exit(-1);
  765. }
  766. else // Parent
  767. {
  768. spawn = new BfpSpawn();
  769. if ((flags & BfpSpawnFlag_RedirectStdInput) != 0)
  770. {
  771. spawn->mStdInFD = stdInFD[1];
  772. close(stdInFD[0]);
  773. }
  774. else
  775. spawn->mStdInFD = 0;
  776. if ((flags & BfpSpawnFlag_RedirectStdOutput) != 0)
  777. {
  778. spawn->mStdOutFD = stdOutFD[0];
  779. close(stdOutFD[1]);
  780. }
  781. else
  782. spawn->mStdOutFD = 0;
  783. if ((flags & BfpSpawnFlag_RedirectStdError) != 0)
  784. {
  785. spawn->mStdErrFD = stdErrFD[0];
  786. close(stdErrFD[1]);
  787. }
  788. else
  789. spawn->mStdErrFD = 0;
  790. }
  791. for (auto val : argvArr)
  792. free(val);
  793. //printf("Spawn pid:%d status:%d\n", pid, status);
  794. spawn->mPid = pid;
  795. spawn->mExited = false;
  796. spawn->mStatus = 0;
  797. return spawn;
  798. }
  799. void BfpSpawn_Release(BfpSpawn* spawn)
  800. {
  801. // We don't support 'detaching' currently- this can create zombie processes since we
  802. // don't have a reaper strategy
  803. BfpSpawn_WaitFor(spawn, -1, NULL, NULL);
  804. delete spawn;
  805. }
  806. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_GetStdHandles(BfpSpawn* spawn, BfpFile** outStdIn, BfpFile** outStdOut, BfpFile** outStdErr)
  807. {
  808. if (outStdIn != NULL)
  809. {
  810. *outStdIn = new BfpFile(spawn->mStdInFD);
  811. spawn->mStdInFD = 0;
  812. }
  813. if (outStdOut != NULL)
  814. {
  815. *outStdOut = new BfpFile(spawn->mStdOutFD);
  816. spawn->mStdOutFD = 0;
  817. }
  818. if (outStdErr != NULL)
  819. {
  820. *outStdErr = new BfpFile(spawn->mStdErrFD);
  821. spawn->mStdErrFD = 0;
  822. }
  823. }
  824. bool BfpSpawn_WaitFor(BfpSpawn* spawn, int waitMS, int* outExitCode, BfpSpawnResult* outResult)
  825. {
  826. OUTRESULT(BfpSpawnResult_Ok);
  827. if (!spawn->mExited)
  828. {
  829. int flags = 0;
  830. if (waitMS != -1)
  831. {
  832. flags = WNOHANG;
  833. }
  834. //TODO: Implement values other than 0 or -1 for waitMS?
  835. pid_t result = waitpid(spawn->mPid, &spawn->mStatus, flags);
  836. if (result != spawn->mPid)
  837. return false;
  838. spawn->mExited = true;
  839. }
  840. if (!WIFEXITED(spawn->mStatus) && !WIFSIGNALED(spawn->mStatus))
  841. return false;
  842. if (outExitCode != NULL)
  843. *outExitCode = WEXITSTATUS(spawn->mStatus);
  844. return true;
  845. }
  846. // BfpFileWatcher
  847. BFP_EXPORT BfpFileWatcher* BFP_CALLTYPE BfpFileWatcher_WatchDirectory(const char* path, BfpDirectoryChangeFunc callback, BfpFileWatcherFlags flags, void* userData, BfpFileResult* outResult)
  848. {
  849. NOT_IMPL;
  850. return NULL;
  851. }
  852. BFP_EXPORT void BFP_CALLTYPE BfpFileWatcher_Release(BfpFileWatcher* fileWatcher)
  853. {
  854. NOT_IMPL;
  855. }
  856. // BfpThread
  857. struct BfpThread
  858. {
  859. bool mPThreadReleased;
  860. BfpThreadStartProc mStartProc;
  861. void* mThreadParam;
  862. pthread_t mPThread;
  863. int mRefCount;
  864. int mPriority;
  865. BfpThread()
  866. {
  867. }
  868. void Release()
  869. {
  870. int refCount = __sync_fetch_and_sub(&mRefCount, 1) - 1;
  871. if (refCount == 0)
  872. delete this;
  873. }
  874. };
  875. struct BfpThreadInfo
  876. {
  877. intptr mStackBase;
  878. int mStackLimit;
  879. };
  880. static __thread BfpThread* gCurrentThread;
  881. static __thread BfpThreadInfo gCurrentThreadInfo;
  882. void* ThreadFunc(void* threadParam)
  883. {
  884. BfpThread* thread = (BfpThread*)threadParam;
  885. gCurrentThread = thread;
  886. thread->mStartProc(thread->mThreadParam);
  887. thread->Release();
  888. }
  889. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_Create(BfpThreadStartProc startProc, void* threadParam, intptr stackSize, BfpThreadCreateFlags flags, BfpThreadId* outThreadId)
  890. {
  891. BfpThread* thread = new BfpThread();
  892. thread->mPThreadReleased = false;
  893. thread->mStartProc = startProc;
  894. thread->mThreadParam = threadParam;
  895. thread->mRefCount = 2;
  896. thread->mPriority = 0;
  897. BF_ASSERT(sizeof(pthread_t) <= sizeof(void*));
  898. pthread_attr_t params;
  899. pthread_attr_init(&params);
  900. pthread_attr_setstacksize(&params, stackSize);
  901. //pthread_attr_setdetachstate(&params,PTHREAD_CREATE_DETACHED);
  902. pthread_create(&thread->mPThread, &params, ThreadFunc, (void*)thread);
  903. pthread_attr_destroy(&params);
  904. if (outThreadId != NULL)
  905. *outThreadId = (BfpThreadId)thread->mPThread;
  906. return thread;
  907. }
  908. #define FIXTHREAD() \
  909. pthread_t pt; \
  910. if (((intptr)thread & 1) != 0) \
  911. { \
  912. pt = (pthread_t)((intptr)thread & ~3); \
  913. thread = NULL; \
  914. } else \
  915. pt = thread->mPThread
  916. BFP_EXPORT void BFP_CALLTYPE BfpThread_Release(BfpThread* thread)
  917. {
  918. FIXTHREAD();
  919. if (thread == NULL)
  920. return;
  921. if (!thread->mPThreadReleased)
  922. {
  923. pthread_detach(thread->mPThread);
  924. thread->mPThreadReleased = true;
  925. }
  926. thread->Release();
  927. }
  928. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetName(BfpThread* thread, const char* name, BfpThreadResult* outResult)
  929. {
  930. OUTRESULT(BfpThreadResult_Ok);
  931. }
  932. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetName(BfpThread* thread, char* outName, int* inOutNameSize, BfpThreadResult* outResult)
  933. {
  934. String str = "";
  935. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  936. }
  937. BFP_EXPORT BfpThread* BFP_CALLTYPE BfpThread_GetCurrent()
  938. {
  939. if (gCurrentThread == NULL)
  940. {
  941. // Not a "true" BfpThread, this is either the main thread or a thread we didn't create
  942. return (BfpThread*)((intptr)pthread_self() | 1);
  943. }
  944. return gCurrentThread;
  945. }
  946. BFP_EXPORT BfpThreadId BFP_CALLTYPE BfpThread_GetCurrentId()
  947. {
  948. if (gCurrentThread == NULL)
  949. {
  950. return (BfpThreadId)((intptr)pthread_self());
  951. }
  952. return (BfpThreadId)gCurrentThread->mPThread;
  953. }
  954. BFP_EXPORT bool BFP_CALLTYPE BfpThread_WaitFor(BfpThread* thread, int waitMS)
  955. {
  956. FIXTHREAD();
  957. if (waitMS == -1)
  958. {
  959. pthread_join(pt, NULL);
  960. thread->mPThreadReleased = true;
  961. return true;
  962. }
  963. struct timespec waitTime;
  964. waitTime.tv_sec = waitMS / 1000;
  965. waitTime.tv_nsec = (waitMS % 1000) * 1000000;
  966. int result = pthread_timedjoin_np(pt, NULL, &waitTime);
  967. if (result == 0)
  968. {
  969. if (thread != NULL)
  970. thread->mPThreadReleased = true;
  971. return true;
  972. }
  973. return false;
  974. }
  975. BFP_EXPORT void BFP_CALLTYPE BfpSpawn_Kill(BfpSpawn* spawn, int exitCode, BfpKillFlags killFlags, BfpSpawnResult* outResult)
  976. {
  977. //TODO: Implement
  978. OUTRESULT(BfpSpawnResult_UnknownError);
  979. }
  980. BFP_EXPORT BfpThreadPriority BFP_CALLTYPE BfpThread_GetPriority(BfpThread* thread, BfpThreadResult* outResult)
  981. {
  982. FIXTHREAD();
  983. OUTRESULT(BfpThreadResult_Ok);
  984. if (thread == NULL)
  985. return (BfpThreadPriority)0;
  986. return (BfpThreadPriority)thread->mPriority;
  987. }
  988. BFP_EXPORT void BFP_CALLTYPE BfpThread_SetPriority(BfpThread* thread, BfpThreadPriority threadPriority, BfpThreadResult* outResult)
  989. {
  990. // In effect, we have two 'nice' settings: 0 (normal) or 10 (low)
  991. // High-priority settings just don't do anything
  992. //pid_t tid = syscall(SYS_gettid);
  993. //int ret = setpriority(PRIO_PROCESS, tid, -std::min(nPriority, 0) * 10);
  994. OUTRESULT(BfpThreadResult_Ok);
  995. }
  996. BFP_EXPORT void BFP_CALLTYPE BfpThread_Suspend(BfpThread* thread, BfpThreadResult* outResult)
  997. {
  998. NOT_IMPL;
  999. }
  1000. BFP_EXPORT void BFP_CALLTYPE BfpThread_Resume(BfpThread* thread, BfpThreadResult* outResult)
  1001. {
  1002. NOT_IMPL;
  1003. }
  1004. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetIntRegisters(BfpThread* thread, intptr* outStackPtr, intptr* outIntRegs, int* inOutIntRegCount, BfpThreadResult* outResult)
  1005. {
  1006. NOT_IMPL;
  1007. }
  1008. BFP_EXPORT void BFP_CALLTYPE BfpThread_GetStackInfo(BfpThread* thread, intptr* outStackBase, int* outStackLimit, BfpThreadResult* outResult)
  1009. {
  1010. if (gCurrentThreadInfo.mStackBase == 0)
  1011. {
  1012. void* stackBase = 0;
  1013. size_t stackLimit = 0;
  1014. pthread_attr_t attr;
  1015. pthread_getattr_np(pthread_self(), &attr);
  1016. pthread_attr_getstack(&attr, &stackBase, &stackLimit);
  1017. gCurrentThreadInfo.mStackBase = (intptr)stackBase + stackLimit;
  1018. gCurrentThreadInfo.mStackLimit = (int)stackLimit;
  1019. pthread_attr_destroy(&attr);
  1020. }
  1021. *outStackBase = gCurrentThreadInfo.mStackBase;
  1022. *outStackLimit = gCurrentThreadInfo.mStackLimit;
  1023. OUTRESULT(BfpThreadResult_Ok);
  1024. }
  1025. BFP_EXPORT void BFP_CALLTYPE BfpThread_Sleep(int sleepMS)
  1026. {
  1027. usleep(sleepMS * 1000);
  1028. }
  1029. BFP_EXPORT bool BFP_CALLTYPE BfpThread_Yield()
  1030. {
  1031. return sched_yield() == 0;
  1032. }
  1033. struct BfpCritSect
  1034. {
  1035. pthread_mutex_t mPMutex;
  1036. };
  1037. BFP_EXPORT BfpCritSect* BFP_CALLTYPE BfpCritSect_Create()
  1038. {
  1039. BfpCritSect* critSect = new BfpCritSect();
  1040. pthread_mutexattr_t attributes;
  1041. pthread_mutexattr_init(&attributes);
  1042. pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE);
  1043. pthread_mutex_init(&critSect->mPMutex, &attributes);
  1044. pthread_mutexattr_destroy(&attributes);
  1045. return critSect;
  1046. }
  1047. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Release(BfpCritSect* critSect)
  1048. {
  1049. pthread_mutex_destroy(&critSect->mPMutex);
  1050. }
  1051. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Enter(BfpCritSect* critSect)
  1052. {
  1053. pthread_mutex_lock(&critSect->mPMutex);
  1054. }
  1055. BFP_EXPORT bool BFP_CALLTYPE BfpCritSect_TryEnter(BfpCritSect* critSect, int waitMS)
  1056. {
  1057. if (waitMS == -1)
  1058. {
  1059. BfpCritSect_Enter(critSect);
  1060. return true;
  1061. }
  1062. else if (waitMS == 0)
  1063. {
  1064. return pthread_mutex_trylock(&critSect->mPMutex) == 0;
  1065. }
  1066. uint32 start = Beefy::BFTickCount();
  1067. while ((int)(Beefy::BFTickCount() - start) < waitMS)
  1068. {
  1069. if (pthread_mutex_trylock(&critSect->mPMutex) == 0)
  1070. {
  1071. return true;
  1072. }
  1073. }
  1074. return false;
  1075. }
  1076. BFP_EXPORT void BFP_CALLTYPE BfpCritSect_Leave(BfpCritSect* critSect)
  1077. {
  1078. pthread_mutex_unlock(&critSect->mPMutex);
  1079. }
  1080. BFP_EXPORT BfpTLS* BFP_CALLTYPE BfpTLS_Create()
  1081. {
  1082. pthread_key_t key = 0;
  1083. pthread_key_create(&key, NULL);
  1084. return (BfpTLS*)(intptr)key;
  1085. }
  1086. BFP_EXPORT void BFP_CALLTYPE BfpTLS_Release(BfpTLS* tls)
  1087. {
  1088. pthread_key_delete((pthread_key_t)(intptr)tls);
  1089. }
  1090. BFP_EXPORT void BFP_CALLTYPE BfpTLS_SetValue(BfpTLS* tls, void* value)
  1091. {
  1092. pthread_setspecific((pthread_key_t)(intptr)tls, value);
  1093. }
  1094. BFP_EXPORT void* BFP_CALLTYPE BfpTLS_GetValue(BfpTLS* tls)
  1095. {
  1096. return pthread_getspecific((pthread_key_t)(intptr)tls);
  1097. }
  1098. struct BfpEvent
  1099. {
  1100. pthread_mutex_t mMutex;
  1101. pthread_cond_t mCondVariable;
  1102. bool mSet;
  1103. bool mManualReset;
  1104. };
  1105. BFP_EXPORT BfpEvent* BFP_CALLTYPE BfpEvent_Create(BfpEventFlags flags)
  1106. {
  1107. BfpEvent* event = new BfpEvent();
  1108. pthread_mutex_init(&event->mMutex, NULL);
  1109. pthread_cond_init(&event->mCondVariable, NULL);
  1110. event->mSet = (flags & (BfpEventFlag_InitiallySet_Auto | BfpEventFlag_InitiallySet_Manual)) != 0;
  1111. event->mManualReset = (flags & BfpEventFlag_InitiallySet_Manual) != 0;
  1112. return event;
  1113. }
  1114. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Release(BfpEvent* event)
  1115. {
  1116. pthread_cond_destroy(&event->mCondVariable);
  1117. pthread_mutex_destroy(&event->mMutex);
  1118. }
  1119. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Set(BfpEvent* event, bool requireManualReset)
  1120. {
  1121. pthread_mutex_lock(&event->mMutex);
  1122. event->mSet = true;
  1123. if (requireManualReset)
  1124. event->mManualReset = true;
  1125. if (event->mManualReset)
  1126. pthread_cond_broadcast(&event->mCondVariable);
  1127. else
  1128. pthread_cond_signal(&event->mCondVariable);
  1129. pthread_mutex_unlock(&event->mMutex);
  1130. }
  1131. BFP_EXPORT void BFP_CALLTYPE BfpEvent_Reset(BfpEvent* event, BfpEventResult* outResult)
  1132. {
  1133. event->mSet = false;
  1134. event->mManualReset = false;
  1135. }
  1136. BFP_EXPORT bool BFP_CALLTYPE BfpEvent_WaitFor(BfpEvent* event, int waitMS)
  1137. {
  1138. int result = pthread_mutex_lock(&event->mMutex);
  1139. BF_ASSERT(result == 0);
  1140. while (!event->mSet)
  1141. {
  1142. if (waitMS == -1)
  1143. {
  1144. pthread_cond_wait(&event->mCondVariable, &event->mMutex);
  1145. }
  1146. else
  1147. {
  1148. timespec ts;
  1149. clock_gettime(CLOCK_REALTIME, &ts);
  1150. ts.tv_sec += waitMS / 1000;
  1151. ts.tv_nsec += (waitMS % 1000) * 1000000;
  1152. result = pthread_cond_timedwait(&event->mCondVariable, &event->mMutex, &ts);
  1153. if (waitMS == (uint32)-1)
  1154. BF_ASSERT(result == 0);
  1155. if (result != 0)
  1156. {
  1157. // Timeout
  1158. pthread_mutex_unlock(&event->mMutex);
  1159. return false;
  1160. }
  1161. }
  1162. }
  1163. if (!event->mManualReset)
  1164. event->mSet = false;
  1165. pthread_mutex_unlock(&event->mMutex);
  1166. return true;
  1167. }
  1168. BFP_EXPORT BfpDynLib* BFP_CALLTYPE BfpDynLib_Load(const char* fileName)
  1169. {
  1170. BfpDynLib* mod = NULL;
  1171. static const char* prefixes[] = {NULL, "lib"};
  1172. static const char* suffixes[] = {NULL, ".so", ".dylib"};
  1173. for (int prefixIdx = 0; prefixIdx < sizeof(prefixes)/sizeof(prefixes[0]); prefixIdx++)
  1174. {
  1175. for (int suffixIdx = 0; suffixIdx < sizeof(suffixes)/sizeof(suffixes[0]); suffixIdx++)
  1176. {
  1177. const char* prefix = prefixes[prefixIdx];
  1178. const char* suffix = suffixes[suffixIdx];
  1179. Beefy::String checkName = fileName;
  1180. if (prefix != NULL)
  1181. checkName = Beefy::String(prefix) + checkName;
  1182. if (suffix != NULL)
  1183. {
  1184. int dotPos = checkName.LastIndexOf('.');
  1185. if (dotPos != -1)
  1186. checkName.RemoveToEnd(dotPos);
  1187. checkName += suffix;
  1188. }
  1189. mod = (BfpDynLib*)dlopen(checkName.c_str(), RTLD_LAZY);
  1190. if (mod != NULL)
  1191. return mod;
  1192. }
  1193. }
  1194. /*mod = (BfpDynLib*)dlopen("/var/Beef/qt-build/Debug/bin/libIDEHelper.so", RTLD_LAZY);;
  1195. if (mod == NULL)
  1196. {
  1197. printf("Err: %s\n", dlerror());
  1198. fflush(stdout);
  1199. }*/
  1200. return NULL;
  1201. }
  1202. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_Release(BfpDynLib* lib)
  1203. {
  1204. dlclose((void*)lib);
  1205. }
  1206. BFP_EXPORT void BFP_CALLTYPE BfpDynLib_GetFilePath(BfpDynLib* lib, char* outPath, int* inOutPathSize, BfpLibResult* outResult)
  1207. {
  1208. Beefy::String path;
  1209. link_map* linkMap = NULL;
  1210. dlinfo((void*)lib, RTLD_DI_LINKMAP, &linkMap);
  1211. if (linkMap == NULL)
  1212. {
  1213. OUTRESULT(BfpLibResult_UnknownError);
  1214. return;
  1215. }
  1216. path = linkMap->l_name;
  1217. TryStringOut(path, outPath, inOutPathSize, (BfpResult*)outResult);
  1218. }
  1219. BFP_EXPORT void* BFP_CALLTYPE BfpDynLib_GetProcAddress(BfpDynLib* lib, const char* name)
  1220. {
  1221. return dlsym((void*)lib, name);
  1222. }
  1223. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Create(const char* path, BfpFileResult* outResult)
  1224. {
  1225. if (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
  1226. {
  1227. switch (errno)
  1228. {
  1229. case EEXIST:
  1230. OUTRESULT(BfpFileResult_AlreadyExists);
  1231. break;
  1232. case ENOENT:
  1233. OUTRESULT(BfpFileResult_NotFound);
  1234. break;
  1235. default:
  1236. OUTRESULT(BfpFileResult_UnknownError);
  1237. break;
  1238. }
  1239. }
  1240. else
  1241. OUTRESULT(BfpFileResult_Ok);
  1242. }
  1243. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Rename(const char* oldName, const char* newName, BfpFileResult* outResult)
  1244. {
  1245. NOT_IMPL;
  1246. }
  1247. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_Delete(const char* path, BfpFileResult* outResult)
  1248. {
  1249. if (rmdir(path) != 0)
  1250. {
  1251. switch (errno)
  1252. {
  1253. case ENOENT:
  1254. OUTRESULT(BfpFileResult_NotFound);
  1255. break;
  1256. default:
  1257. OUTRESULT(BfpFileResult_UnknownError);
  1258. break;
  1259. }
  1260. }
  1261. else
  1262. OUTRESULT(BfpFileResult_Ok);
  1263. }
  1264. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetCurrent(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  1265. {
  1266. char* str = getcwd(NULL, 0);
  1267. Beefy::String path = str;
  1268. free(str);
  1269. TryStringOut(path, outPath, inOutPathSize, (BfpResult*)outResult);
  1270. }
  1271. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_SetCurrent(const char* path, BfpFileResult* outResult)
  1272. {
  1273. if (chdir(path) != 0)
  1274. OUTRESULT(BfpFileResult_NotFound);
  1275. else
  1276. OUTRESULT(BfpFileResult_Ok);
  1277. }
  1278. BFP_EXPORT bool BFP_CALLTYPE BfpDirectory_Exists(const char* path)
  1279. {
  1280. struct stat statbuf = {0};
  1281. int result = stat(path, &statbuf);
  1282. if (result != 0)
  1283. return false;
  1284. return S_ISDIR(statbuf.st_mode);
  1285. }
  1286. BFP_EXPORT void BFP_CALLTYPE BfpDirectory_GetSysDirectory(BfpSysDirectoryKind sysDirKind, char* outPath, int* inOutPathLen, BfpFileResult* outResult)
  1287. {
  1288. String path = "~";
  1289. TryStringOut(path, outPath, inOutPathLen, (BfpResult*)outResult);
  1290. }
  1291. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_Create(const char* inName, BfpFileCreateKind createKind, BfpFileCreateFlags createFlags, BfpFileAttributes createdFileAttrs, BfpFileResult* outResult)
  1292. {
  1293. auto _DoCreate = [&](String& name)
  1294. {
  1295. int flags = 0;
  1296. int mode = 0;
  1297. int pipePairHandle = -1;
  1298. if ((createFlags & (BfpFileCreateFlag_Read | BfpFileCreateFlag_Write)) == (BfpFileCreateFlag_Read | BfpFileCreateFlag_Write))
  1299. flags |= O_RDWR;
  1300. else if ((createFlags & BfpFileCreateFlag_Read) != 0)
  1301. flags |= O_RDONLY;
  1302. else if ((createFlags & BfpFileCreateFlag_Write) != 0)
  1303. flags |= O_WRONLY;
  1304. if ((createFlags & BfpFileCreateFlag_Append) != 0)
  1305. flags |= O_APPEND;
  1306. if ((createFlags & BfpFileCreateFlag_Truncate) != 0)
  1307. flags |= O_TRUNC;
  1308. if ((createFlags & (BfpFileCreateFlag_NonBlocking | BfpFileCreateFlag_AllowTimeouts)) != 0)
  1309. flags |= O_NONBLOCK;
  1310. if ((createFlags & BfpFileCreateFlag_Pipe) != 0)
  1311. {
  1312. name = "/tmp/" + name;
  1313. if ((createKind == BfpFileCreateKind_CreateAlways) ||
  1314. (createKind == BfpFileCreateKind_CreateIfNotExists))
  1315. {
  1316. for (int pass = 0; pass < 2; pass++)
  1317. {
  1318. int result = mknod(name.c_str(), S_IFIFO | ALLPERMS, 0);
  1319. if (result == 0)
  1320. break;
  1321. int err = errno;
  1322. if (err == EEXIST)
  1323. {
  1324. err = remove(name.c_str());
  1325. if (err == 0)
  1326. continue;
  1327. OUTRESULT(BfpFileResult_AlreadyExists);
  1328. return -1;
  1329. }
  1330. OUTRESULT(BfpFileResult_UnknownError);
  1331. return -1;
  1332. }
  1333. }
  1334. }
  1335. else
  1336. {
  1337. if (createKind == BfpFileCreateKind_CreateAlways)
  1338. flags |= O_CREAT;
  1339. else if (createKind == BfpFileCreateKind_CreateIfNotExists)
  1340. flags |= O_CREAT | O_EXCL;
  1341. }
  1342. mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  1343. int result = open(name.c_str(), flags, mode);
  1344. //printf("BfpFile_Create %s %d %d %d\n", name.c_str(), result, flags, mode);
  1345. if (result <= 0)
  1346. {
  1347. switch (errno)
  1348. {
  1349. case EEXIST:
  1350. OUTRESULT(BfpFileResult_AlreadyExists);
  1351. break;
  1352. case ENOENT:
  1353. OUTRESULT(BfpFileResult_NotFound);
  1354. break;
  1355. case EACCES:
  1356. OUTRESULT(BfpFileResult_AccessError);
  1357. break;
  1358. default:
  1359. OUTRESULT(BfpFileResult_UnknownError);
  1360. break;
  1361. }
  1362. return -1;
  1363. }
  1364. return result;
  1365. };
  1366. BfpFile* bfpFile = NULL;
  1367. int result;
  1368. if ((createFlags & BfpFileCreateFlag_Pipe) != 0)
  1369. {
  1370. int readHandle;
  1371. int writeHandle;
  1372. String name = inName;
  1373. String altName = name + "__";
  1374. bool isCreating = false;
  1375. if ((createKind == BfpFileCreateKind_CreateAlways) ||
  1376. (createKind == BfpFileCreateKind_CreateIfNotExists))
  1377. {
  1378. readHandle = _DoCreate(name);
  1379. writeHandle = _DoCreate(altName);
  1380. isCreating = true;
  1381. }
  1382. else
  1383. {
  1384. readHandle = _DoCreate(altName);
  1385. writeHandle = _DoCreate(name);
  1386. }
  1387. if ((readHandle != -1) && (writeHandle != -1))
  1388. {
  1389. OUTRESULT(BfpFileResult_Ok);
  1390. BfpPipeInfo* pipeInfo = new BfpPipeInfo();
  1391. pipeInfo->mWriteHandle = writeHandle;
  1392. if (isCreating)
  1393. pipeInfo->mPipePath = name;
  1394. bfpFile = new BfpFile();
  1395. bfpFile->mHandle = readHandle;
  1396. bfpFile->mPipeInfo = pipeInfo;
  1397. }
  1398. else
  1399. {
  1400. if (readHandle != -1)
  1401. close(readHandle);
  1402. if (writeHandle != -1)
  1403. close(writeHandle);
  1404. return NULL;
  1405. }
  1406. }
  1407. else
  1408. {
  1409. String name = inName;
  1410. int handle = _DoCreate(name);
  1411. if (handle == -1)
  1412. return NULL;
  1413. OUTRESULT(BfpFileResult_Ok);
  1414. bfpFile = new BfpFile();
  1415. bfpFile->mHandle = handle;
  1416. }
  1417. OUTRESULT(BfpFileResult_Ok);
  1418. if ((createFlags & (BfpFileCreateFlag_NonBlocking | BfpFileCreateFlag_AllowTimeouts)) != 0)
  1419. bfpFile->mNonBlocking = true;
  1420. if ((createFlags & BfpFileCreateFlag_AllowTimeouts) != 0)
  1421. bfpFile->mAllowTimeout = true;
  1422. return bfpFile;
  1423. }
  1424. BFP_EXPORT BfpFile* BFP_CALLTYPE BfpFile_GetStd(BfpFileStdKind kind, BfpFileResult* outResult)
  1425. {
  1426. int h = -1;
  1427. switch (kind)
  1428. {
  1429. case BfpFileStdKind_StdOut:
  1430. h = STDOUT_FILENO;
  1431. break;
  1432. case BfpFileStdKind_StdError:
  1433. h = STDERR_FILENO;
  1434. break;
  1435. case BfpFileStdKind_StdIn:
  1436. h = STDIN_FILENO;
  1437. break;
  1438. }
  1439. if (h == -1)
  1440. {
  1441. OUTRESULT(BfpFileResult_NotFound);
  1442. return NULL;
  1443. }
  1444. BfpFile* bfpFile = new BfpFile();
  1445. bfpFile->mHandle = h;
  1446. bfpFile->mIsStd = true;
  1447. return bfpFile;
  1448. }
  1449. BFP_EXPORT void BFP_CALLTYPE BfpFile_Release(BfpFile* file)
  1450. {
  1451. if ((file->mHandle != -1) && (!file->mIsStd))
  1452. close(file->mHandle);
  1453. if (file->mPipeInfo != NULL)
  1454. {
  1455. if (file->mPipeInfo->mWriteHandle != -1)
  1456. close(file->mPipeInfo->mWriteHandle);
  1457. if (!file->mPipeInfo->mPipePath.IsEmpty())
  1458. {
  1459. int worked = remove(file->mPipeInfo->mPipePath.c_str());
  1460. remove((file->mPipeInfo->mPipePath + "__").c_str());
  1461. //printf("Removing %s %d\n", file->mPipeInfo->mPipePath.c_str(), worked);
  1462. }
  1463. }
  1464. delete file;
  1465. }
  1466. BFP_EXPORT void BFP_CALLTYPE BfpFile_Close(BfpFile* file, BfpFileResult* outResult)
  1467. {
  1468. if (file->mHandle != -1)
  1469. {
  1470. close(file->mHandle);
  1471. file->mHandle = -1;
  1472. if (file->mPipeInfo != NULL)
  1473. {
  1474. close(file->mPipeInfo->mWriteHandle);
  1475. file->mPipeInfo->mWriteHandle = -1;
  1476. }
  1477. OUTRESULT(BfpFileResult_Ok);
  1478. }
  1479. else
  1480. OUTRESULT(BfpFileResult_UnknownError);
  1481. }
  1482. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Write(BfpFile* file, const void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  1483. {
  1484. int writeHandle = file->mHandle;
  1485. if (file->mPipeInfo != NULL)
  1486. writeHandle = file->mPipeInfo->mWriteHandle;
  1487. intptr writeCount = ::write(writeHandle, buffer, size);
  1488. // if ((writeCount > 0) && (file->mIsPipe))
  1489. // {
  1490. // ::fsync(file->mHandle);
  1491. // }
  1492. if (writeCount < 0)
  1493. OUTRESULT(BfpFileResult_UnknownError);
  1494. else if (writeCount != size)
  1495. OUTRESULT(BfpFileResult_PartialData);
  1496. else
  1497. OUTRESULT(BfpFileResult_Ok);
  1498. return writeCount;
  1499. }
  1500. BFP_EXPORT intptr BFP_CALLTYPE BfpFile_Read(BfpFile* file, void* buffer, intptr size, int timeoutMS, BfpFileResult* outResult)
  1501. {
  1502. if (file->mNonBlocking)
  1503. {
  1504. if (!file->mAllowTimeout)
  1505. timeoutMS = -1;
  1506. timeval timeout;
  1507. timeout.tv_sec = 0;
  1508. timeout.tv_usec = timeoutMS * 1000;
  1509. fd_set readFDSet;
  1510. FD_ZERO(&readFDSet);
  1511. FD_SET(file->mHandle, &readFDSet);
  1512. fd_set errorFDSet;
  1513. FD_ZERO(&errorFDSet);
  1514. FD_SET(file->mHandle, &errorFDSet);
  1515. if (select(file->mHandle + 1, &readFDSet, NULL, &errorFDSet, (timeoutMS == -1) ? NULL : &timeout) < 0)
  1516. {
  1517. OUTRESULT(BfpFileResult_Timeout);
  1518. return 0;
  1519. }
  1520. }
  1521. intptr readCount = ::read(file->mHandle, buffer, size);
  1522. if (readCount < 0)
  1523. OUTRESULT(BfpFileResult_UnknownError);
  1524. else if (readCount != size)
  1525. OUTRESULT(BfpFileResult_PartialData);
  1526. else
  1527. OUTRESULT(BfpFileResult_Ok);
  1528. return readCount;
  1529. }
  1530. BFP_EXPORT void BFP_CALLTYPE BfpFile_Flush(BfpFile* file)
  1531. {
  1532. ::fsync(file->mHandle);
  1533. }
  1534. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_GetFileSize(BfpFile* file)
  1535. {
  1536. int64 oldPos = (int64)lseek64(file->mHandle, 0, SEEK_CUR);
  1537. int64 size = (int64)lseek64(file->mHandle, 0, SEEK_END);
  1538. lseek64(file->mHandle, oldPos, SEEK_SET);
  1539. return (int64)size;
  1540. }
  1541. BFP_EXPORT int64 BFP_CALLTYPE BfpFile_Seek(BfpFile* file, int64 offset, BfpFileSeekKind seekKind)
  1542. {
  1543. int whence;
  1544. if (seekKind == BfpFileSeekKind_Absolute)
  1545. whence = SEEK_SET;
  1546. else if (seekKind == BfpFileSeekKind_Relative)
  1547. whence = SEEK_CUR;
  1548. else
  1549. whence = SEEK_END;
  1550. return lseek64(file->mHandle, offset, whence);
  1551. }
  1552. BFP_EXPORT void BFP_CALLTYPE BfpFile_Truncate(BfpFile* file)
  1553. {
  1554. int64 curPos = (int64)lseek64(file->mHandle, 0, SEEK_CUR);
  1555. if (ftruncate64(file->mHandle, curPos) != 0)
  1556. {
  1557. //TODO: Report error?
  1558. }
  1559. }
  1560. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFile_GetTime_LastWrite(const char* path)
  1561. {
  1562. struct stat statbuf = {0};
  1563. int result = stat(path, &statbuf);
  1564. if (result != 0)
  1565. return 0;
  1566. return statbuf.st_mtime;
  1567. }
  1568. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFile_GetAttributes(const char* path, BfpFileResult* outResult)
  1569. {
  1570. NOT_IMPL;
  1571. return (BfpFileAttributes)0;
  1572. }
  1573. BFP_EXPORT void BFP_CALLTYPE BfpFile_SetAttributes(const char* path, BfpFileAttributes attribs, BfpFileResult* outResult)
  1574. {
  1575. NOT_IMPL;
  1576. }
  1577. BFP_EXPORT void BFP_CALLTYPE BfpFile_Copy(const char* oldPath, const char* newPath, BfpFileCopyKind copyKind, BfpFileResult* outResult)
  1578. {
  1579. int fd_to, fd_from;
  1580. char buf[4096];
  1581. ssize_t nread;
  1582. fd_from = open(oldPath, O_RDONLY);
  1583. if (fd_from < 0)
  1584. {
  1585. OUTRESULT(BfpFileResult_NotFound);
  1586. return;
  1587. }
  1588. fd_to = open(newPath, O_WRONLY | O_CREAT | O_EXCL, 0666);
  1589. if (fd_to < 0)
  1590. {
  1591. OUTRESULT(BfpFileResult_AlreadyExists);
  1592. goto out_error;
  1593. }
  1594. while (nread = read(fd_from, buf, sizeof buf), nread > 0)
  1595. {
  1596. char *out_ptr = buf;
  1597. ssize_t nwritten;
  1598. do {
  1599. nwritten = write(fd_to, out_ptr, nread);
  1600. if (nwritten >= 0)
  1601. {
  1602. nread -= nwritten;
  1603. out_ptr += nwritten;
  1604. }
  1605. else if (errno != EINTR)
  1606. {
  1607. OUTRESULT(BfpFileResult_UnknownError);
  1608. goto out_error;
  1609. }
  1610. } while (nread > 0);
  1611. }
  1612. if (nread == 0)
  1613. {
  1614. if (close(fd_to) < 0)
  1615. {
  1616. fd_to = -1;
  1617. OUTRESULT(BfpFileResult_UnknownError);
  1618. goto out_error;
  1619. }
  1620. close(fd_from);
  1621. /* Success! */
  1622. OUTRESULT(BfpFileResult_Ok);
  1623. return;
  1624. }
  1625. out_error:
  1626. close(fd_from);
  1627. if (fd_to >= 0)
  1628. close(fd_to);
  1629. }
  1630. BFP_EXPORT void BFP_CALLTYPE BfpFile_Rename(const char* oldPath, const char* newPath, BfpFileResult* outResult)
  1631. {
  1632. NOT_IMPL;
  1633. }
  1634. BFP_EXPORT void BFP_CALLTYPE BfpFile_Delete(const char* path, BfpFileResult* outResult)
  1635. {
  1636. if (remove(path) != 0)
  1637. {
  1638. switch (errno)
  1639. {
  1640. case ENOENT:
  1641. OUTRESULT(BfpFileResult_NotFound);
  1642. break;
  1643. default:
  1644. OUTRESULT(BfpFileResult_UnknownError);
  1645. break;
  1646. }
  1647. }
  1648. else
  1649. OUTRESULT(BfpFileResult_Ok);
  1650. }
  1651. BFP_EXPORT bool BFP_CALLTYPE BfpFile_Exists(const char* path)
  1652. {
  1653. struct stat statbuf = {0};
  1654. int result = stat(path, &statbuf);
  1655. if (result != 0)
  1656. return false;
  1657. return !S_ISDIR(statbuf.st_mode);
  1658. }
  1659. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempPath(char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  1660. {
  1661. NOT_IMPL;
  1662. }
  1663. static const char cHash64bToChar[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
  1664. 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
  1665. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  1666. 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_' };
  1667. static void HashEncode64(StringImpl& outStr, uint64 val)
  1668. {
  1669. for (int i = 0; i < 10; i++)
  1670. {
  1671. int charIdx = (int)((val >> (i * 6)) & 0x3F) - 1;
  1672. if (charIdx != -1)
  1673. outStr.Append(cHash64bToChar[charIdx]);
  1674. }
  1675. }
  1676. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetTempFileName(char* outName, int* inOutNameSize, BfpFileResult* outResult)
  1677. {
  1678. static uint32 uniqueIdx = 0;
  1679. BfpSystem_InterlockedExchangeAdd32(&uniqueIdx, 1);
  1680. Beefy::HashContext ctx;
  1681. ctx.Mixin(uniqueIdx);
  1682. ctx.Mixin(getpid());
  1683. ctx.Mixin(Beefy::BFGetTickCountMicro());
  1684. uint64 hash = ctx.Finish64();
  1685. String str = "/tmp/bftmp_";
  1686. HashEncode64(str, hash);
  1687. TryStringOut(str, outName, inOutNameSize, (BfpResult*)outResult);
  1688. }
  1689. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetFullPath(const char* inPath, char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  1690. {
  1691. String str;
  1692. if (inPath[0] == '/')
  1693. {
  1694. str = inPath;
  1695. }
  1696. else
  1697. {
  1698. char* cwdPtr = getcwd(NULL, 0);
  1699. Beefy::String cwdPath = cwdPtr;
  1700. free(cwdPtr);
  1701. str = GetAbsPath(inPath, cwdPath);
  1702. }
  1703. TryStringOut(str, outPath, inOutPathSize, (BfpResult*)outResult);
  1704. }
  1705. BFP_EXPORT void BFP_CALLTYPE BfpFile_GetActualPath(const char* inPath, char* outPath, int* inOutPathSize, BfpFileResult* outResult)
  1706. {
  1707. NOT_IMPL;
  1708. }
  1709. // BfpFindFileData
  1710. struct BfpFindFileData
  1711. {
  1712. BfpFindFileFlags mFlags;
  1713. DIR* mDirStruct;
  1714. Beefy::String mWildcard;
  1715. Beefy::String mDirPath;
  1716. dirent* mDirEnt;
  1717. bool mHasStat;
  1718. struct stat mStat;
  1719. };
  1720. BFP_EXPORT BfpFindFileData* BFP_CALLTYPE BfpFindFileData_FindFirstFile(const char* path, BfpFindFileFlags flags, BfpFileResult* outResult)
  1721. {
  1722. Beefy::String findStr = path;
  1723. Beefy::String wildcard;
  1724. int lastSlashPos = std::max((int)findStr.LastIndexOf('/'), (int)findStr.LastIndexOf('\\'));
  1725. if (lastSlashPos != -1)
  1726. {
  1727. wildcard = findStr.Substring(lastSlashPos + 1);
  1728. findStr = findStr.Substring(0, lastSlashPos);
  1729. }
  1730. if (wildcard == "*.*")
  1731. wildcard = "*";
  1732. DIR* dir = opendir(findStr.c_str());
  1733. if (dir == NULL)
  1734. {
  1735. OUTRESULT(BfpFileResult_NotFound);
  1736. return NULL;
  1737. }
  1738. BfpFindFileData* findData = new BfpFindFileData();
  1739. findData->mFlags = flags;
  1740. findData->mDirPath = findStr;
  1741. findData->mDirStruct = dir;
  1742. findData->mWildcard = wildcard;
  1743. findData->mHasStat = false;
  1744. findData->mDirEnt = NULL;
  1745. if (!BfpFindFileData_FindNextFile(findData))
  1746. {
  1747. OUTRESULT(BfpFileResult_NoResults);
  1748. delete findData;
  1749. return NULL;
  1750. }
  1751. OUTRESULT(BfpFileResult_Ok);
  1752. return findData;
  1753. }
  1754. static void GetStat(BfpFindFileData* findData)
  1755. {
  1756. if (findData->mHasStat)
  1757. return;
  1758. Beefy::String filePath = findData->mDirPath + "/" + findData->mDirEnt->d_name;
  1759. findData->mStat = { 0 };
  1760. int result = stat(filePath.c_str(), &findData->mStat);
  1761. findData->mHasStat = true;
  1762. }
  1763. static bool BfpFindFileData_CheckFilter(BfpFindFileData* findData)
  1764. {
  1765. bool isDir = false;
  1766. if (findData->mDirEnt->d_type == DT_DIR)
  1767. isDir = true;
  1768. if (findData->mDirEnt->d_type == DT_LNK)
  1769. {
  1770. GetStat(findData);
  1771. isDir = S_ISDIR(findData->mStat.st_mode);
  1772. }
  1773. if (isDir)
  1774. {
  1775. if ((findData->mFlags & BfpFindFileFlag_Directories) == 0)
  1776. return false;
  1777. if ((strcmp(findData->mDirEnt->d_name, ".") == 0) || (strcmp(findData->mDirEnt->d_name, "..") == 0))
  1778. return false;
  1779. }
  1780. else
  1781. {
  1782. if ((findData->mFlags & BfpFindFileFlag_Files) == 0)
  1783. return false;
  1784. }
  1785. //TODO: Check actual wildcards.
  1786. return true;
  1787. }
  1788. BFP_EXPORT bool BFP_CALLTYPE BfpFindFileData_FindNextFile(BfpFindFileData* findData)
  1789. {
  1790. while (true)
  1791. {
  1792. findData->mHasStat = false;
  1793. findData->mDirEnt = readdir(findData->mDirStruct);
  1794. if (findData->mDirEnt == NULL)
  1795. return false;
  1796. if (BfpFindFileData_CheckFilter(findData))
  1797. break;
  1798. }
  1799. return true;
  1800. }
  1801. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_GetFileName(BfpFindFileData* findData, char* outName, int* inOutNameSize, BfpFileResult* outResult)
  1802. {
  1803. Beefy::String name = findData->mDirEnt->d_name;
  1804. TryStringOut(name, outName, inOutNameSize, (BfpResult*)outResult);
  1805. }
  1806. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_LastWrite(BfpFindFileData* findData)
  1807. {
  1808. GetStat(findData);
  1809. return BfpToTimeStamp(findData->mStat.st_mtim);
  1810. }
  1811. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Created(BfpFindFileData* findData)
  1812. {
  1813. GetStat(findData);
  1814. return BfpToTimeStamp(findData->mStat.st_ctim);
  1815. }
  1816. BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpFindFileData_GetTime_Access(BfpFindFileData* findData)
  1817. {
  1818. GetStat(findData);
  1819. return BfpToTimeStamp(findData->mStat.st_atim);
  1820. }
  1821. BFP_EXPORT BfpFileAttributes BFP_CALLTYPE BfpFindFileData_GetFileAttributes(BfpFindFileData* findData)
  1822. {
  1823. BfpFileAttributes flags = BfpFileAttribute_None;
  1824. if (S_ISDIR(findData->mStat.st_mode))
  1825. flags = (BfpFileAttributes)(flags | BfpFileAttribute_Directory);
  1826. if (S_ISREG(findData->mStat.st_mode))
  1827. flags = (BfpFileAttributes)(flags | BfpFileAttribute_Normal);
  1828. else if (!S_ISLNK(findData->mStat.st_mode))
  1829. flags = (BfpFileAttributes)(flags | BfpFileAttribute_Device);
  1830. if ((findData->mStat.st_mode & S_IRUSR) == 0)
  1831. flags = (BfpFileAttributes)(flags | BfpFileAttribute_ReadOnly);
  1832. return flags;
  1833. }
  1834. BFP_EXPORT void BFP_CALLTYPE BfpFindFileData_Release(BfpFindFileData* findData)
  1835. {
  1836. delete findData;
  1837. }
  1838. BFP_EXPORT int BFP_CALLTYPE BfpStack_CaptureBackTrace(int framesToSkip, intptr* outFrames, int wantFrameCount)
  1839. {
  1840. //
  1841. return 0;
  1842. }
  1843. BFP_EXPORT void BFP_CALLTYPE BfpOutput_DebugString(const char* str)
  1844. {
  1845. fputs(str, stdout);
  1846. fflush(stdout);
  1847. }
  1848. //////////////////////////////////////////////////////////////////////////
  1849. void Beefy::BFFatalError(const StringImpl& message, const StringImpl& file, int line)
  1850. {
  1851. String error;
  1852. error += "ERROR: ";
  1853. error += message;
  1854. error += " in ";
  1855. error += file;
  1856. error += StrFormat(" line %d", line);
  1857. BfpSystem_FatalError(error.c_str(), "FATAL ERROR");
  1858. }