jmisc.cpp 25 KB

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