PosixCommon.cpp 62 KB

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