jmisc.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. //#define MINIMALTRACE // a more readable version of the trace file (IMO)
  14. //#define LOGCLOCK
  15. #include "platform.h"
  16. #include "stdio.h"
  17. #include <time.h>
  18. #include "jmisc.hpp"
  19. #include "jmutex.hpp"
  20. #include "jexcept.hpp"
  21. #include "jstring.hpp"
  22. #include "jdebug.hpp"
  23. #ifdef _WIN32
  24. #include <direct.h>
  25. #else
  26. #include <sys/wait.h>
  27. #include <pwd.h>
  28. #endif
  29. #ifdef LOGCLOCK
  30. #define MSGFIELD_PRINTLOG MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code | MSGFIELD_milliTime
  31. #else
  32. #define MSGFIELD_PRINTLOG MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code
  33. #endif
  34. #define FPRINTF(s) { fprintf(stdlog, "%s", s); \
  35. if (logFile) fprintf(logFile, "%s", s); }
  36. void _rev(size32_t len, void * _ptr)
  37. {
  38. byte * ptr = (byte *)_ptr;
  39. while (len > 1)
  40. {
  41. byte t = *ptr;
  42. *ptr = ptr[--len];
  43. ptr[len] = t;
  44. len--;
  45. ptr++;
  46. }
  47. }
  48. Mutex printMutex;
  49. FILE *logFile;
  50. FILE *stdlog = stderr;
  51. HiresTimer logTimer;
  52. class CStdLogIntercept: public ILogIntercept
  53. {
  54. bool nl;
  55. #ifdef MINIMALTRACE
  56. time_t lastt;
  57. unsigned lasttpid;
  58. #endif
  59. unsigned detail;
  60. public:
  61. CStdLogIntercept()
  62. {
  63. #ifdef MINIMALTRACE
  64. lasttpid = 0;
  65. lastt = 0;
  66. #endif
  67. nl = true;
  68. detail = _LOG_TIME | _LOG_PID | _LOG_TID;
  69. #ifdef LOGCLOCK
  70. detail |= _LOG_CLOCK;
  71. #endif
  72. queryStderrLogMsgHandler()->setMessageFields(detail);
  73. }
  74. unsigned setLogDetail(unsigned i)
  75. {
  76. unsigned ret = detail;
  77. detail = i;
  78. return ret;
  79. }
  80. void print(const char *str)
  81. {
  82. if (nl) {
  83. char timeStamp[32];
  84. time_t tNow;
  85. time(&tNow);
  86. #ifdef _WIN32
  87. struct tm ltNow = *localtime(&tNow);
  88. #else
  89. struct tm ltNow;
  90. localtime_r(&tNow, &ltNow);
  91. #endif
  92. #ifdef MINIMALTRACE
  93. unsigned tpid = GetCurrentThreadId();
  94. if (((detail & _LOG_TID) && tpid!=lasttpid)||((detail & _LOG_TIME) && memcmp(&tNow,&lastt,sizeof(tNow))!=0))
  95. {
  96. lasttpid = tpid;
  97. lastt = tNow;
  98. FPRINTF("[");
  99. if (detail & _LOG_TIME)
  100. {
  101. strftime(timeStamp, 32, "%H:%M:%S ", &ltNow);
  102. FPRINTF(timeStamp);
  103. }
  104. if (detail & _LOG_TID)
  105. {
  106. fprintf(stdlog, "TID=%d ", tpid);
  107. if (logFile)
  108. fprintf(logFile, "TID=%d ", tpid);
  109. }
  110. FPRINTF("]\n");
  111. }
  112. #else
  113. if (detail & _LOG_TIME)
  114. {
  115. strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S ", &ltNow);
  116. FPRINTF(timeStamp);
  117. }
  118. if (detail & _LOG_CLOCK)
  119. {
  120. unsigned t=msTick();
  121. fprintf(stdlog, "%u ", t);
  122. if (logFile)
  123. fprintf(logFile, "%u ", t);
  124. }
  125. if (detail & _LOG_HIRESCLOCK)
  126. {
  127. unsigned clock = usTick();
  128. fprintf(stdlog, " TICK=%u ", clock);
  129. if (logFile)
  130. fprintf(logFile, " TICK=%u ", clock);
  131. }
  132. #if defined(_WIN32)
  133. if (detail & _LOG_TID)
  134. {
  135. fprintf(stdlog, "TID=%d ", GetCurrentThreadId());
  136. if (logFile)
  137. fprintf(logFile, "TID=%d ", GetCurrentThreadId());
  138. }
  139. if (detail & _LOG_PID)
  140. {
  141. fprintf(stdlog, "PID=%d ", GetCurrentProcessId());
  142. if (logFile)
  143. fprintf(logFile, "PID=%d ", GetCurrentProcessId());
  144. }
  145. #else
  146. if (detail & _LOG_PID)
  147. {
  148. fprintf(stdlog, "PID=%d ", getpid());
  149. if (logFile)
  150. fprintf(logFile, "PID=%d ", getpid());
  151. }
  152. #endif
  153. if (detail & (_LOG_PID|_LOG_TID|_LOG_TIME))
  154. {
  155. fprintf(stdlog, "- ");
  156. if (logFile)
  157. fprintf(logFile, "- ");
  158. }
  159. #endif
  160. }
  161. if (str && *str)
  162. {
  163. nl = str[strlen(str)-1]=='\n';
  164. FPRINTF(str);
  165. }
  166. else
  167. nl = false;
  168. fflush(stdlog);
  169. if (logFile)
  170. {
  171. fflush(logFile);
  172. }
  173. }
  174. void close()
  175. {
  176. if (logFile) {
  177. fclose(logFile);
  178. logFile = 0;
  179. }
  180. }
  181. };
  182. static ILogIntercept *logintercept = NULL;
  183. jlib_decl ILogIntercept* interceptLog(ILogIntercept *intercept)
  184. {
  185. ILogIntercept *old=logintercept;
  186. logintercept = intercept;
  187. return old;
  188. }
  189. jlib_decl void openLogFile(StringBuffer & resolvedFS, const char *filename, unsigned detail, bool enterQueueMode, bool append)
  190. {
  191. if(enterQueueMode)
  192. queryLogMsgManager()->enterQueueingMode();
  193. Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(".", 0);
  194. lf->setCreateAliasFile(false);
  195. lf->setLocal(true);
  196. lf->setRolling(false);
  197. lf->setAppend(append);
  198. lf->setCompleteFilespec(filename);//user specified log filespec
  199. lf->setMaxDetail(detail ? detail : DefaultDetail);
  200. lf->setMsgFields(MSGFIELD_STANDARD);
  201. lf->beginLogging();
  202. resolvedFS.set(lf->queryLogFileSpec());
  203. }
  204. StringBuffer &addFileTimestamp(StringBuffer &fname, bool daily)
  205. {
  206. time_t tNow;
  207. time(&tNow);
  208. char timeStamp[32];
  209. #ifdef _WIN32
  210. struct tm *ltNow;
  211. ltNow = localtime(&tNow);
  212. strftime(timeStamp, 32, daily ? ".%Y_%m_%d" : ".%Y_%m_%d_%H_%M_%S", ltNow);
  213. #else
  214. struct tm ltNow;
  215. localtime_r(&tNow, &ltNow);
  216. strftime(timeStamp, 32, daily ? ".%Y_%m_%d" : ".%Y_%m_%d_%H_%M_%S", &ltNow);
  217. #endif
  218. return fname.append(timeStamp);
  219. }
  220. #define MAX_TRY_SIZE 0x8000000 // 256 MB
  221. jlib_decl void PrintMemoryStatusLog()
  222. {
  223. #ifdef _WIN32
  224. MEMORYSTATUS mS;
  225. GlobalMemoryStatus(&mS);
  226. LOG(MCdebugInfo, unknownJob, "Available Physical Memory = %dK", (unsigned)(mS.dwAvailPhys/1024));
  227. #ifdef FRAGMENTATION_CHECK
  228. // see if fragmented
  229. size32_t sz = MAX_TRY_SIZE;
  230. while (sz) {
  231. if (sz<mS.dwAvailPhys/4) {
  232. void *p=malloc(sz);
  233. if (p) {
  234. free(p);
  235. break;
  236. }
  237. }
  238. sz /= 2;
  239. }
  240. sz *= 2;
  241. if ((sz<MAX_TRY_SIZE)&&(sz<mS.dwAvailPhys/4)) {
  242. LOG(MCdebugInfo, unknownJob, "WARNING: Could not allocate block size %d", sz);
  243. _HEAPINFO hinfo;
  244. int heapstatus;
  245. hinfo._pentry = NULL;
  246. size32_t max=0;
  247. unsigned fragments=0;
  248. while( ( heapstatus = _heapwalk( &hinfo ) ) == _HEAPOK ) {
  249. if (hinfo._useflag != _USEDENTRY) {
  250. if (hinfo._size>max)
  251. max = hinfo._size;
  252. fragments++;
  253. }
  254. }
  255. LOG(MCdebugInfo, unknownJob, "Largest unused fragment = %d", max);
  256. LOG(MCdebugInfo, unknownJob, "Number of fragments = %d", fragments);
  257. }
  258. #endif
  259. #endif
  260. }
  261. static class _init_jmisc_class
  262. {
  263. public:
  264. ~_init_jmisc_class()
  265. {
  266. if (logFile)
  267. fclose(logFile);
  268. }
  269. } _init_jmisc;
  270. FILE *xfopen(const char *path, const char *mode)
  271. {
  272. char *s, *e, *p;
  273. p = s = strdup(path);
  274. e = s+strlen(path);
  275. bool alt=false;
  276. for (; p<e; p++)
  277. {
  278. #ifdef _WIN32
  279. if (*p == '/')
  280. #else
  281. if (*p == '\\')
  282. #endif
  283. {
  284. alt = true;
  285. *p = PATHSEPCHAR;
  286. }
  287. }
  288. if (alt)
  289. printf("XFOPEN ALTERED FILENAME FROM:%s TO %s\n", path, s);
  290. FILE *file = ::fopen(s, mode);
  291. free(s);
  292. return file;
  293. }
  294. const char * queryCcLogName()
  295. {
  296. const char* logFileName = getenv("ECL_CCLOG");
  297. if (!logFileName)
  298. {
  299. logFileName = "cclog.txt";
  300. }
  301. return logFileName;
  302. //More does output get redirected here?
  303. }
  304. StringBuffer& queryCcLogName(const char* wuid, StringBuffer& logname)
  305. {
  306. if(!wuid || !*wuid)
  307. logname.append(queryCcLogName());
  308. else
  309. {
  310. const char* presetName = getenv("ECL_CCLOG");
  311. if (presetName && *presetName)
  312. logname.append(presetName);
  313. else
  314. logname.append(wuid).trim().append(".cclog.txt");
  315. }
  316. return logname;
  317. }
  318. jlib_decl char* readarg(char*& curptr)
  319. {
  320. char *cur = curptr;
  321. if(cur == NULL || *cur == 0)
  322. return NULL;
  323. while(*cur == ' ' || *cur == '\t') {
  324. cur++;
  325. if (!*cur) {
  326. curptr = cur;
  327. return NULL;
  328. }
  329. }
  330. char quote = 0;
  331. if(*cur == '\'' || *cur == '"')
  332. {
  333. quote = *cur;
  334. cur++;
  335. }
  336. char *ret = cur;
  337. if (quote)
  338. {
  339. while (*cur && *cur!=quote)
  340. cur++;
  341. }
  342. else
  343. {
  344. do {
  345. cur++;
  346. } while(*cur && *cur != ' ' && *cur != '\t');
  347. }
  348. if(*cur != 0)
  349. {
  350. *cur = 0;
  351. cur++;
  352. }
  353. curptr = cur;
  354. return ret;
  355. }
  356. #ifdef _WIN32
  357. bool invoke_program(const char *command_line, DWORD &runcode, bool wait, const char *outfile, HANDLE *rethandle, bool throwException, bool newProcessGroup)
  358. {
  359. runcode = 0;
  360. if (rethandle)
  361. *rethandle = 0;
  362. if(!command_line || !*command_line)
  363. return false;
  364. STARTUPINFO StartupInfo;
  365. SECURITY_ATTRIBUTES security;
  366. _clear(security);
  367. security.nLength = sizeof(security);
  368. security.bInheritHandle = TRUE;
  369. _clear(StartupInfo);
  370. StartupInfo.cb = sizeof(StartupInfo);
  371. HANDLE outh = NULL;
  372. if (outfile&&*outfile) {
  373. outh = CreateFile(outfile,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,&security,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  374. if (outh == INVALID_HANDLE_VALUE)
  375. {
  376. OERRLOG("Cannot create file '%s' error code %d",outfile,(int)GetLastError());
  377. return false;
  378. }
  379. }
  380. if (outh) {
  381. if (!DuplicateHandle(GetCurrentProcess(),outh,GetCurrentProcess(),&StartupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS) ||
  382. !DuplicateHandle(GetCurrentProcess(),outh,GetCurrentProcess(),&StartupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS))
  383. {
  384. OERRLOG("Execution of \"%s\" failed, DuplicateHandle error = %d",command_line, (int)GetLastError());
  385. CloseHandle(outh);
  386. return false;
  387. }
  388. StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  389. StartupInfo.dwFlags = STARTF_USESTDHANDLES;
  390. CloseHandle(outh);
  391. }
  392. PROCESS_INFORMATION ProcessInformation;
  393. bool ok = CreateProcess(NULL,(char *)command_line,NULL,NULL,TRUE,0,NULL,NULL,&StartupInfo,&ProcessInformation)!=0;
  394. if (ok) {
  395. if (wait)
  396. {
  397. WaitForSingleObject(ProcessInformation.hProcess,INFINITE);
  398. GetExitCodeProcess(ProcessInformation.hProcess, &runcode);
  399. }
  400. CloseHandle(ProcessInformation.hThread);
  401. if (rethandle) {
  402. *rethandle = (HANDLE)ProcessInformation.hProcess;
  403. if (wait)
  404. CloseHandle(ProcessInformation.hProcess);
  405. }
  406. else
  407. CloseHandle(ProcessInformation.hProcess);
  408. }
  409. else
  410. {
  411. int lastError = (int)GetLastError(); // for debugging
  412. //print out why create process failed
  413. OERRLOG("Execution of \"%s\" failed, error = %d",command_line,lastError);
  414. }
  415. if (outh)
  416. {
  417. CloseHandle(StartupInfo.hStdOutput);
  418. CloseHandle(StartupInfo.hStdError);
  419. }
  420. return ok;
  421. }
  422. bool wait_program(HANDLE handle,DWORD &runcode,bool block)
  423. {
  424. runcode = (DWORD)-1;
  425. if ((handle==NULL)||(handle==(HANDLE)-1))
  426. return true; // actually it failed
  427. int ret = WaitForSingleObject(handle,block?INFINITE:0);
  428. int err = GetLastError();
  429. if (ret==WAIT_OBJECT_0) {
  430. GetExitCodeProcess(handle, &runcode);
  431. CloseHandle(handle);
  432. return true;
  433. }
  434. return false;
  435. }
  436. jlib_decl bool interrupt_program(HANDLE handle, bool stopChildren, int signum)
  437. {
  438. if (signum==0)
  439. return TerminateProcess(handle,1)!=FALSE;
  440. OERRLOG("interrupt_program signal %d not supported in windows",signum);
  441. return false;
  442. }
  443. void close_program(HANDLE handle)
  444. {
  445. CloseHandle(handle);
  446. }
  447. #else
  448. bool invoke_program(const char *command_line, DWORD &runcode, bool wait, const char *outfile, HANDLE *rethandle, bool throwException, bool newProcessGroup)
  449. {
  450. runcode = 0;
  451. if (rethandle)
  452. *rethandle = 0;
  453. if(!command_line || !*command_line)
  454. return false;
  455. pid_t pid = fork();
  456. if (pid == 0)
  457. {
  458. //Force the child process into its own process group, so we can terminate it and its children.
  459. if (newProcessGroup)
  460. setpgid(0,0);
  461. if (outfile&&*outfile) {
  462. int outh = open(outfile, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
  463. if(outh >= 0)
  464. {
  465. dup2(outh, STDOUT_FILENO);
  466. dup2(outh, STDERR_FILENO);
  467. close(outh);
  468. }
  469. else {
  470. OERRLOG("invoke_program: could not open %s",outfile);
  471. return false;
  472. }
  473. }
  474. int size = 10;
  475. char **args;
  476. char **argptr = args = (char **) malloc(sizeof(args) * size);
  477. char **over = argptr+size;
  478. char *cl = strdup(command_line);
  479. char *curptr = cl;
  480. *argptr = readarg(curptr);
  481. while (*argptr != NULL)
  482. {
  483. argptr++;
  484. if (argptr==over)
  485. {
  486. args = (char **) realloc(args, sizeof(args) * size * 2);
  487. argptr = args+size;
  488. size *= 2;
  489. over = args+size;
  490. }
  491. *argptr = readarg(curptr);
  492. }
  493. // JCSMORE - do I not need to free args, if successful exec?
  494. if (execvp(*args, args))
  495. {
  496. //print out why create process failed
  497. int err = errno;
  498. OERRLOG("invoke_program(%s) failed with error(%d): %s",command_line,err,strerror(err));
  499. }
  500. assertex(0); // don't expect to get here!
  501. _exit(0);
  502. }
  503. else if (pid < 0)
  504. {
  505. StringBuffer s("fork of \"");
  506. s.append(command_line).append("\" failed. fork() returned:");
  507. if (errno == EAGAIN)
  508. s.append("EAGAIN");
  509. else if (errno == ENOMEM)
  510. s.append("ENOMEM");
  511. else
  512. s.append(errno);
  513. OERRLOG("%s",s.str());
  514. if(throwException)
  515. throw MakeStringExceptionDirect(-1, s.str());
  516. return false;
  517. }
  518. if (rethandle)
  519. *rethandle = (HANDLE)pid;
  520. if (wait)
  521. {
  522. int retv;
  523. while (1)
  524. {
  525. auto wpid = waitpid(pid, &retv, 0);
  526. if (wpid == pid)
  527. break;
  528. if (errno != EINTR)
  529. {
  530. OERRLOG("invoke_program(%s): wait failed (%d, %d, %d)",command_line,(int) wpid, retv, errno);
  531. return false;
  532. }
  533. }
  534. if (!WIFEXITED(retv)) //did not exit normally
  535. {
  536. int err = errno;
  537. OERRLOG("invoke_program(%s): failed.",command_line);
  538. OERRLOG("The process was killed by signal %d%s.",(int)WTERMSIG(retv),WCOREDUMP(retv)?" - core dumped":"");
  539. OERRLOG("Last system error is %s",strerror(err));
  540. }
  541. runcode = WEXITSTATUS(retv);
  542. }
  543. return true; // it did run even if signalled
  544. }
  545. bool wait_program(HANDLE handle,DWORD &runcode,bool block)
  546. {
  547. pid_t pid = (pid_t)handle;
  548. runcode = (DWORD)-1;
  549. if ((int)pid<=0)
  550. return true; // actually it failed
  551. int retv;
  552. pid_t ret = waitpid(pid, &retv, block?0:WNOHANG);
  553. if (ret == (pid_t)-1) {
  554. IERRLOG("wait_program: wait failed (%d)",errno);
  555. return true; // actually it failed but assume finished
  556. }
  557. else if (ret==0)
  558. return false;
  559. runcode = WEXITSTATUS(retv);
  560. return true;
  561. }
  562. bool interrupt_program(HANDLE handle, bool stopChildren, int signum)
  563. {
  564. if (signum == 0)
  565. signum = SIGINT;
  566. pid_t pid = (pid_t)handle;
  567. if ((int)pid<=0)
  568. return false;
  569. //If we need to also stop child processes then kill the process group (same as the pid)
  570. //Note: This will not apply to grand-children started by the children by calling invoke_program()
  571. //since they will have a different process group
  572. if (stopChildren)
  573. pid = -pid;
  574. return (kill(pid, signum)==0);
  575. }
  576. void close_program(HANDLE handle)
  577. {
  578. // not needed in linux
  579. }
  580. #endif
  581. #ifndef _WIN32
  582. bool CopyFile(const char *file, const char *newfile, bool fail)
  583. {
  584. struct stat s;
  585. if ((fail) && (0 == stat((char *)newfile, &s))) return false;
  586. FILE *in=fopen(file,"rb"), *out=fopen(newfile,"wb");
  587. try
  588. {
  589. if (!in)
  590. throw MakeStringException(-1, "failed to open %s for copy",file);
  591. if (!out)
  592. throw MakeStringException(-1, "failed to create %s",newfile);
  593. char b[1024];
  594. while (true)
  595. {
  596. int c=fread(b,1,sizeof(b),in);
  597. if (!c) break;
  598. if (!fwrite(b,c,1,out)) throw MakeStringException(-1, "failed to copy file %s to %s",file,newfile);
  599. }
  600. fclose(in);
  601. fclose(out);
  602. stat((char *)file, &s);
  603. chmod(newfile, s.st_mode);
  604. } catch (...)
  605. {
  606. if (in) fclose(in);
  607. if (out) fclose(out);
  608. return false;
  609. }
  610. return true;
  611. }
  612. #endif
  613. //========================================================================================================================
  614. static bool hadAbortSignal = false;
  615. static bool handlerInstalled = false;
  616. CriticalSection abortCrit;
  617. class AbortHandlerInfo : public CInterface
  618. {
  619. public:
  620. ThreadId installer;
  621. AbortHandler handler;
  622. SimpleAbortHandler shandler;
  623. IAbortHandler *ihandler;
  624. AbortHandlerInfo(AbortHandler _handler)
  625. {
  626. handler = _handler;
  627. shandler = NULL;
  628. ihandler = NULL;
  629. installer = GetCurrentThreadId();
  630. }
  631. AbortHandlerInfo(SimpleAbortHandler _handler)
  632. {
  633. handler = NULL;
  634. shandler = _handler;
  635. ihandler = NULL;
  636. installer = GetCurrentThreadId();
  637. }
  638. AbortHandlerInfo(IAbortHandler *_ihandler)
  639. {
  640. handler = NULL;
  641. shandler = NULL;
  642. ihandler = _ihandler;
  643. installer = GetCurrentThreadId();
  644. }
  645. bool handle(ahType type)
  646. {
  647. #ifndef _WIN32
  648. if (installer == GetCurrentThreadId())
  649. #endif
  650. {
  651. // DBGLOG("handle abort %x", GetCurrentThreadId());
  652. if (handler)
  653. return handler(type);
  654. else if (shandler)
  655. return shandler();
  656. else
  657. return ihandler->onAbort();
  658. }
  659. #ifndef _WIN32
  660. else
  661. return false;
  662. #endif
  663. }
  664. };
  665. CIArrayOf<AbortHandlerInfo> handlers;
  666. bool notifyOnAbort(ahType type)
  667. {
  668. // DBGLOG("notifyOnAbort %x", GetCurrentThreadId());
  669. // CriticalBlock c(abortCrit); You would think that this was needed, but it locks up.
  670. // If it needs to be threadsafe, have to clone the list or something
  671. bool doExit = false;
  672. ForEachItemInRev(idx, handlers)
  673. {
  674. if (handlers.item(idx).handle(type))
  675. doExit = true;
  676. }
  677. // DBGLOG("notifyOnAbort returning %d", (int) doExit);
  678. return doExit;
  679. }
  680. #ifdef _WIN32
  681. BOOL WINAPI WindowsAbortHandler ( DWORD dwCtrlType )
  682. {
  683. switch( dwCtrlType )
  684. {
  685. case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate
  686. case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode
  687. case CTRL_CLOSE_EVENT:
  688. {
  689. hadAbortSignal = true;
  690. bool doExit = notifyOnAbort(ahInterrupt);
  691. return !doExit;
  692. }
  693. case CTRL_LOGOFF_EVENT:
  694. case CTRL_SHUTDOWN_EVENT:
  695. hadAbortSignal = true;
  696. notifyOnAbort(ahTerminate);
  697. return FALSE;
  698. }
  699. return FALSE;
  700. }
  701. BOOL WINAPI ModuleExitHandler ( DWORD dwCtrlType )
  702. {
  703. switch( dwCtrlType )
  704. {
  705. case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate
  706. case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode
  707. case CTRL_CLOSE_EVENT:
  708. case CTRL_LOGOFF_EVENT:
  709. case CTRL_SHUTDOWN_EVENT:
  710. ExitModuleObjects();
  711. }
  712. return FALSE;
  713. }
  714. #elif defined(__linux__)
  715. static void UnixAbortHandler(int signo)
  716. {
  717. ahType type = ahInterrupt;
  718. if (SIGTERM == signo)
  719. type = ahTerminate;
  720. hadAbortSignal = true;
  721. if (handlers.length()==0 || notifyOnAbort(type))
  722. {
  723. _exit(0);
  724. }
  725. }
  726. #endif
  727. void queryInstallAbortHandler()
  728. {
  729. if (handlerInstalled)
  730. return;
  731. #if defined(_WIN32)
  732. SetConsoleCtrlHandler( WindowsAbortHandler, TRUE );
  733. #elif defined(__linux__)
  734. struct sigaction action;
  735. sigemptyset(&action.sa_mask);
  736. action.sa_flags = SA_RESTART;
  737. action.sa_handler = (void(*)(int))UnixAbortHandler;
  738. if (sigaction(SIGINT, &action, NULL) == -1 ||
  739. sigaction(SIGQUIT, &action, NULL) == -1 ||
  740. sigaction(SIGTERM, &action, NULL) == -1)
  741. {
  742. perror("sigaction in queryInstallAbortHandler failed");
  743. }
  744. #endif
  745. handlerInstalled = true;
  746. }
  747. void queryUninstallAbortHandler()
  748. {
  749. if (handlers.ordinality())
  750. return;
  751. #if defined(_WIN32)
  752. if (handlerInstalled)
  753. {
  754. SetConsoleCtrlHandler( WindowsAbortHandler, FALSE);
  755. handlerInstalled = false;
  756. }
  757. #else
  758. // Don't uninstall - we always want one for the module exit support
  759. #endif
  760. }
  761. MODULE_INIT(INIT_PRIORITY_JMISC2)
  762. {
  763. #if defined(_WIN32)
  764. // NOTE: handlers are called in LIFO order and hence any handler that returns false
  765. // (e.g CTRL-C not wanting to abort)) will stop this handler being called also (correctly).
  766. SetConsoleCtrlHandler( ModuleExitHandler, TRUE);
  767. #elif defined(__linux__)
  768. queryInstallAbortHandler();
  769. #endif
  770. return true;
  771. }
  772. void addAbortHandler(AbortHandler handler)
  773. {
  774. CriticalBlock c(abortCrit);
  775. queryInstallAbortHandler();
  776. handlers.append(*new AbortHandlerInfo(handler));
  777. }
  778. void addAbortHandler(SimpleAbortHandler handler)
  779. {
  780. CriticalBlock c(abortCrit);
  781. queryInstallAbortHandler();
  782. handlers.append(*new AbortHandlerInfo(handler));
  783. }
  784. void addAbortHandler(IAbortHandler & handler)
  785. {
  786. CriticalBlock c(abortCrit);
  787. queryInstallAbortHandler();
  788. handlers.append(*new AbortHandlerInfo(&handler));
  789. }
  790. void removeAbortHandler(AbortHandler handler)
  791. {
  792. CriticalBlock c(abortCrit);
  793. ForEachItemInRev(idx, handlers)
  794. {
  795. if (handlers.item(idx).handler == handler)
  796. {
  797. handlers.remove(idx);
  798. break;
  799. }
  800. }
  801. queryUninstallAbortHandler();
  802. }
  803. void removeAbortHandler(SimpleAbortHandler handler)
  804. {
  805. CriticalBlock c(abortCrit);
  806. ForEachItemInRev(idx, handlers)
  807. {
  808. if (handlers.item(idx).shandler == handler)
  809. {
  810. handlers.remove(idx);
  811. break;
  812. }
  813. }
  814. queryUninstallAbortHandler();
  815. }
  816. void removeAbortHandler(IAbortHandler & handler)
  817. {
  818. CriticalBlock c(abortCrit);
  819. ForEachItemInRev(idx, handlers)
  820. {
  821. if (handlers.item(idx).ihandler == &handler)
  822. {
  823. handlers.remove(idx);
  824. break;
  825. }
  826. }
  827. queryUninstallAbortHandler();
  828. }
  829. bool isAborting()
  830. {
  831. return hadAbortSignal;
  832. }
  833. void throwAbortException()
  834. {
  835. throw MakeStringException(JLIBERR_UserAbort, "Operation aborted by user");
  836. }
  837. void throwExceptionIfAborting()
  838. {
  839. if (isAborting())
  840. throwAbortException();
  841. }
  842. //========================================================================================================================
  843. StringBuffer & hexdump2string(byte const * in, size32_t inSize, StringBuffer & out)
  844. {
  845. out.append("[");
  846. byte last = 0;
  847. unsigned seq = 1;
  848. for(unsigned i=0; i<inSize; ++i)
  849. {
  850. if((i>0) && (in[i]==last))
  851. {
  852. ++seq;
  853. }
  854. else
  855. {
  856. if(seq>1)
  857. {
  858. if(seq==2)
  859. out.appendf(" %02X", last);
  860. else
  861. out.appendf("x%u", seq);
  862. seq = 1;
  863. }
  864. out.appendf(" %02X", in[i]);
  865. last = in[i];
  866. }
  867. }
  868. if(seq>1)
  869. out.appendf("x%u", seq);
  870. out.append(" ]");
  871. return out;
  872. }
  873. jlib_decl bool getHomeDir(StringBuffer & homepath)
  874. {
  875. #ifdef _WIN32
  876. const char *home = getenv("APPDATA");
  877. // Not the 'official' way - which changes with every windows version
  878. // but should work well enough for us (and avoids sorting out windows include mess)
  879. #else
  880. const char *home = getenv("HOME");
  881. if (!home)
  882. {
  883. struct passwd *pw = getpwuid(getuid());
  884. home = pw->pw_dir;
  885. }
  886. #endif
  887. if (!home)
  888. return false;
  889. homepath.append(home);
  890. return true;
  891. }
  892. #ifdef _WIN32
  893. char *mkdtemp(char *_template)
  894. {
  895. if (!_template || strlen(_template) < 6 || !streq(_template+strlen(_template)-6, "XXXXXX"))
  896. {
  897. errno = EINVAL;
  898. return nullptr;
  899. }
  900. char * tail = _template + strlen(_template) - 6;
  901. for (int i = 0; i < 100; i++)
  902. {
  903. snprintf(tail, 7, "%06d", fastRand());
  904. if (!_mkdir(_template))
  905. return _template;
  906. if (errno != EEXIST)
  907. return nullptr;
  908. }
  909. errno = EINVAL;
  910. return nullptr;
  911. }
  912. #endif