PosixCommon.cpp 72 KB

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