CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
Utils.cpp
Go to the documentation of this file.
1
7#ifdef _WIN32
8 // To avoid complaints about fopen and _open
9 #define _CRT_SECURE_NO_WARNINGS
10#endif
11
12#include "Utils.h"
13#include "ObjectIDs.h"
14#include "HTML.h"
15#include "ThreadManager.h"
16#include "UnitTestFramework.h"
17#include <thread>
18#include <atomic>
19
20#ifdef __APPLE__
21#include <mach/vm_statistics.h>
22#include <libproc.h>
23#include <mach/host_info.h>
24#include <mach/task_info.h>
25#include <mach/thread_act.h>
26#include <sys/sysctl.h>
27#endif
28
29#ifndef _WIN32
30#include <termios.h>
31#include <sys/ioctl.h>
32#include <mutex>
33#include <condition_variable>
34#endif
35
36#ifdef __APPLE__
37#include <sys/event.h>
38#include <sys/types.h>
39#include <sys/proc.h>
40#endif
41
42// Named-mutex lock word (CMSDK_MUTEX_PID_RECOVERY, macOS): kernel wait/wake on a shared address.
43#if defined(__APPLE__)
44 #if defined(__has_include)
45 #if __has_include(<os/os_sync_wait_on_address.h>)
46 #include <os/os_sync_wait_on_address.h>
47 #include <os/clock.h>
48 #define CMSDK_HAVE_OS_SYNC 1
49 #endif
50 #endif
51 #ifndef CMSDK_HAVE_OS_SYNC
52 #define CMSDK_HAVE_OS_SYNC 0
53 #endif
54 // libsystem_kernel's ulock (what os_sync wraps; exported since macOS 10.12), for macOS before 14.4
55 extern "C" int __ulock_wait(uint32_t operation, void* addr, uint64_t value, uint32_t timeout_us);
56 extern "C" int __ulock_wake(uint32_t operation, void* addr, uint64_t wake_value);
57 #define CMSDK_UL_COMPARE_AND_WAIT_SHARED 3
58 #define CMSDK_ULF_NO_ERRNO 0x01000000
59 #define CMSDK_ULF_WAKE_ALL 0x00000100
60#elif !defined(_WIN32)
61 #include <sys/syscall.h>
62 #include <linux/futex.h>
63 #include <limits.h>
64#endif
65
66namespace cmlabs {
67
69// INIT/EXIT //
71
74
78
88
90
93 std::map<std::string, utils::Semaphore*>::iterator si;
94 while (utils::SharedMemorySemaphoreMap->size()) {
96 delete(si->second);
97 utils::SharedMemorySemaphoreMap->erase(si->first);
98 }
104 }
105
108 std::map<std::string, utils::Event*>::iterator ei;
109 while (utils::SharedMemoryEventMap->size()) {
110 ei = utils::SharedMemoryEventMap->begin();
111 delete(ei->second);
112 utils::SharedMemoryEventMap->erase(ei->first);
113 }
119 }
120
123 std::map<std::string, utils::Mutex*>::iterator mi;
124 while (utils::SharedMemoryMutexMap->size()) {
125 mi = utils::SharedMemoryMutexMap->begin();
126 delete(mi->second);
127 utils::SharedMemoryMutexMap->erase(mi->first);
128 }
134 }
135
136 delete(utils::DrumBeatMap);
137 utils::DrumBeatMap = NULL;
138
141
142 delete(utils::Timer::timers);
144
147
148 return true;
149}
150
151utils::CommandLineInfo* utils::CommandLineInfo::CommandLineInfoSingleton = NULL;
152
154// Objects //
156
157std::string GetDataTypeName(uint32 datatype) {
158 switch (datatype) {
159 case CONSTCHARID:
160 return "String";
161 case TIMEID:
162 return "Time";
163 case INTID:
164 return "Integer";
165 case DOUBLEID:
166 return "Float";
167 case CHARDATAID:
168 return "Binary";
169 case DATAMESSAGEID:
170 return "Message";
171 case CONSTCHARINFOID:
172 return "String info";
173 case CHARDATAINFOID:
174 return "Binary info";
176 return "Message info";
177 default:
178 return "Unknown type";
179 }
180}
181
182uint32 GetDataTypeID(const char* typeName) {
183 if ((stricmp(typeName, "string") == 0) || (stricmp(typeName, "text") == 0))
184 return CONSTCHARID;
185 else if (stricmp(typeName, "time") == 0)
186 return CONSTCHARID;
187 else if ((stricmp(typeName, "integer") == 0) || (stricmp(typeName, "int") == 0))
188 return INTID;
189 else if ((stricmp(typeName, "float") == 0) || (stricmp(typeName, "double") == 0))
190 return DOUBLEID;
191 else if (stricmp(typeName, "binary") == 0)
192 return CHARDATAID;
193 else if (stricmp(typeName, "message") == 0)
194 return DATAMESSAGEID;
195 else if (stricmp(typeName, "string info") == 0)
196 return CONSTCHARINFOID;
197 else if (stricmp(typeName, "binary info") == 0)
198 return CHARDATAINFOID;
199 else if (stricmp(typeName, "message info") == 0)
200 return DATAMESSAGEINFOID;
201 else
202 return 0;
203}
204
206// Logging //
208
210 if (!LogSingleton) {
211 LogSingleton = new LogSystem();
212 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
213 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
214 LogSingleton->logReceiverObj = NULL;
215 }
216 LogSingleton->logReceiverObj = rec;
217 return true;
218}
219
221 if (!LogSingleton) {
222 LogSingleton = new LogSystem();
223 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
224 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
225 LogSingleton->logReceiverObj = NULL;
226 }
227 memset(LogSingleton->logLevelDebug, level, LOG_MAXCOUNT);
228 return true;
229}
230
231bool LogSystem::SetLogLevelDebug(uint8 subject, uint8 level) {
232 if (subject >= LOG_MAXCOUNT)
233 return false;
234 if (!LogSingleton) {
235 LogSingleton = new LogSystem();
236 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
237 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
238 LogSingleton->logReceiverObj = NULL;
239 }
240 LogSingleton->logLevelDebug[subject] = level;
241 return true;
242}
243
245 if (!LogSingleton) {
246 LogSingleton = new LogSystem();
247 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
248 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
249 LogSingleton->logReceiverObj = NULL;
250 }
251 memset(LogSingleton->logLevelVerbose, level, LOG_MAXCOUNT);
252 return true;
253}
254
255bool LogSystem::SetLogLevelVerbose(uint8 subject, uint8 level) {
256 if (subject >= LOG_MAXCOUNT)
257 return false;
258 if (!LogSingleton) {
259 LogSingleton = new LogSystem();
260 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
261 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
262 LogSingleton->logReceiverObj = NULL;
263 }
264 LogSingleton->logLevelVerbose[subject] = level;
265 return true;
266}
267
268
270 logfile = NULL;
271 printToStdOut = true;
272}
274 if (logfile)
275 delete [] logfile;
276 logfile = NULL;
277 printToStdOut = true;
278}
279
280const char* LogEntry::getText(uint32& len) {
281 if (len = this->size - sizeof(LogEntry))
282 return (char*)this+sizeof(LogEntry);
283 else
284 return NULL;
285}
286
287bool LogEntry::setText(char* text, uint32 len) {
288 if (!text || !len)
289 return false;
290 int32 avail = (int32)size - sizeof(LogEntry) - 1;
291 if (avail < (int32)len)
292 return false;
293 memcpy((char*)this+sizeof(LogEntry), text, len);
294 *((char*)this+sizeof(LogEntry)+len) = 0;
295 return true;
296}
297
298std::string LogEntry::toJSON() {
299 uint32 len;
300 const char* text = getText(len);
301 return utils::StringFormat(
302 "{ \"time\": %llu, \"level\": %u, \"source\": %u, \"subject\": %u, \"type\": %u, \"text\": \"%s\" }",
303 time, level, source, subject, type, utils::EncodeJSON(text).c_str());
304}
305
306std::string LogEntry::toXML() {
307 uint32 len;
308 const char* text = getText(len);
309 return utils::StringFormat(
310 "<entry time=\"%llu\" level=\"%u\" source=\"%u\" subject=\"%u\" type=\"%u\" text=\"%s\" />\n",
311 time, level, source, subject, type, html::EncodeHTML(text).c_str());
312}
313
314
315bool LogSystem::SetLogFileOutput(const char* logfile, bool printOut) {
316
317 if (!LogSingleton) {
318 LogSingleton = new LogSystem();
319 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
320 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
321 LogSingleton->logReceiverObj = NULL;
322 }
323
324 uint32 len;
325 if (!logfile || !(len = (uint32)strlen(logfile))) {
326 if (LogSingleton->logfile) {
327 delete [] LogSingleton->logfile;
328 LogSingleton->logfile = NULL;
329 }
330 }
331 else {
332 if (LogSingleton->logfile)
333 delete [] LogSingleton->logfile;
334 LogSingleton->logfile = new char[len+1];
335 utils::strcpyavail(LogSingleton->logfile, logfile, len+1, true);
336 }
337 LogSingleton->printToStdOut = printOut;
338 return true;
339}
340
341//#pragma data_seg(".shared") // Begin the shared data segment.
343//#pragma data_seg() // End the shared data segment
344//#pragma comment(linker, "/section:.shared,RWS")
345
346bool LogSystem::LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... ) {
347
348 if (!LogSingleton) {
349 LogSingleton = new LogSystem();
350 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
351 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
352 LogSingleton->logReceiverObj = NULL;
353 }
354
355 LogEntry* entry;
356 char* str;
357 uint32 len;
358 bool res = true;
359
360 if (LogSingleton->logLevelVerbose[subject] >= level) {
361 va_list args;
362 va_start(args, formatstring);
363 str = utils::StringFormatVA(len, formatstring, args);
364 va_end(args);
365 if (!str || !len)
366 res = false;
367 else {
368 if (LogSingleton->logReceiverObj) {
369 entry = (LogEntry*) malloc(sizeof(LogEntry)+len+1);
370 entry->size = sizeof(LogEntry)+len+1;
371 entry->cid = LOGENTRYID;
372 entry->time = GetTimeNow();
373 entry->source = source;
374 entry->subject = subject;
375 entry->level = level;
376 entry->type = LOGPRINT;
377 entry->setText(str, len);
378 free(str);
379 return LogSingleton->logReceiverObj->logEntry(entry);
380 }
381 if (LogSingleton->logfile || LogSingleton->printToStdOut) {
382 std::string strline = utils::StringFormat("%s %s\n", PrintTimeNowString().c_str(), str);
383 if (LogSingleton->logfile && strlen(LogSingleton->logfile))
384 utils::AppendToAFile(LogSingleton->logfile, strline.c_str(), (uint32)strline.length());
385 if (LogSingleton->printToStdOut)
386 std::cout << strline;
387 }
388 }
389 free(str);
390 }
391 return res;
392}
393
394bool LogSystem::LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring, ... ) {
395
396 if (!LogSingleton) {
397 LogSingleton = new LogSystem();
398 memset(LogSingleton->logLevelVerbose, 1, LOG_MAXCOUNT);
399 memset(LogSingleton->logLevelDebug, 0, LOG_MAXCOUNT);
400 LogSingleton->logReceiverObj = NULL;
401 }
402
403 LogEntry* entry;
404 char* str;
405 uint32 len;
406 bool res = true;
407
408 if (LogSingleton->logLevelDebug[subject] >= level) {
409 va_list args;
410 va_start(args, formatstring);
411 str = utils::StringFormatVA(len, formatstring, args);
412 va_end(args);
413 if (!str || !len)
414 res = false;
415 else {
416 if (LogSingleton->logReceiverObj) {
417 entry = (LogEntry*) malloc(sizeof(LogEntry)+len+1);
418 entry->size = sizeof(LogEntry)+len+1;
419 entry->cid = LOGENTRYID;
420 entry->time = GetTimeNow();
421 entry->source = source;
422 entry->subject = subject;
423 entry->level = level;
424 entry->type = LOGDEBUG;
425 entry->setText(str, len);
426 free(str);
427 return LogSingleton->logReceiverObj->logEntry(entry);
428 }
429 else
430 std::cout << PrintTimeNowString() << " [DEBUG] " << str << std::endl;
431 }
432 free(str);
433 }
434 return res;
435}
436
437#ifdef __APPLE__
438 /*
439 * A pthread_mutex_timedlock() impl for OSX/macOS, which lacks the
440 * real thing.
441 * NOTE: Unlike the real McCoy, won't return EOWNERDEAD, EDEADLK
442 * or EOWNERDEAD
443 */
444 static int macos_pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *abs_timeout)
445 {
446 // abs_timeout is an ABSOLUTE deadline (CalcTimeout builds it from
447 // gettimeofday()). The previous implementation mistook it for a relative
448 // "remaining" duration and initialised its countdown to the absolute
449 // epoch time (~1.78e9 s), so the deadline check effectively never fired
450 // and mutex.enter(timeoutMS) would wait FOREVER whenever the lock was
451 // actually held by another thread - a process-wide latent hang on macOS.
452 // Compare the real clock against the deadline and poll trylock instead.
453 int rv;
454 while ((rv = pthread_mutex_trylock(mutex)) == EBUSY) {
455 struct timeval now;
456 gettimeofday(&now, NULL);
457 if (now.tv_sec > abs_timeout->tv_sec ||
458 (now.tv_sec == abs_timeout->tv_sec &&
459 (long)(now.tv_usec) * 1000L >= abs_timeout->tv_nsec))
460 return ETIMEDOUT;
461 struct timespec nap = { 0, 1000000 }; // poll every 1ms
462 nanosleep(&nap, NULL);
463 }
464 return rv;
465 }
466#endif
467
468#ifndef WINDOWS
469// ---------------------------------------------------------------------------------------------------------------
470// Owner-death recovery for named (process-shared) mutexes (17 Nov 2026). A process that died holding one (e.g. a
471// crashed external component holding PsycloneProcessMemoryMutex_<port>) used to leave every other process on the
472// node waiting on it for ever ("Mutex enter timeout 5000: 'waitForQ' ... held by 0"; psy_extexec_limit on macOS,
473// found by Isaac). Windows already hands the mutex over with WAIT_ABANDONED. Linux: robust mutexes - the next locker
474// gets EOWNERDEAD and marks it consistent. macOS has no robust mutexes, so there a named mutex is a lock word holding
475// its owner's pid (SharedLockAcquire below). Either way the data the mutex guarded may be half-updated (as on
476// Windows), and a warning is logged.
477// ---------------------------------------------------------------------------------------------------------------
478#ifndef CMSDK_MUTEX_PID_RECOVERY
479// Linux: a process-shared, recursive, robust mutex.
480static void InitSharedMutexObject(pthread_mutex_t* m) {
481 pthread_mutexattr_t attr;
482 pthread_mutexattr_init(&attr);
483 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
484 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
485 pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
486 pthread_mutex_init(m, &attr);
487 pthread_mutexattr_destroy(&attr);
488}
489#endif
490
491// Kernel wait/wake on a 32-bit word in shared memory (os_sync/ulock on macOS, futex on Linux), used by the macOS
492// named-mutex lock word, the macOS named-semaphore word and every POSIX named Event.
493// Sleep while *addr == value, at most timeoutUS. Spurious and early returns are fine (the caller loops).
494static void SharedLockWait(volatile uint32_t* addr, uint32_t value, uint32_t timeoutUS) {
495 #if defined(__APPLE__)
496 #if CMSDK_HAVE_OS_SYNC
497 if (__builtin_available(macOS 14.4, *)) {
498 os_sync_wait_on_address_with_timeout((void*)addr, value, 4, OS_SYNC_WAIT_ON_ADDRESS_SHARED,
499 OS_CLOCK_MACH_ABSOLUTE_TIME, (uint64_t)timeoutUS * 1000ULL);
500 return;
501 }
502 #endif
503 __ulock_wait(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO, (void*)addr, value, timeoutUS ? timeoutUS : 1);
504 #else
505 struct timespec ts = { (time_t)(timeoutUS / 1000000), (long)(timeoutUS % 1000000) * 1000L };
506 syscall(SYS_futex, (uint32_t*)addr, FUTEX_WAIT, value, &ts, NULL, 0);
507 #endif
508}
509
510static void SharedLockWakeOne(volatile uint32_t* addr) {
511 #if defined(__APPLE__)
512 #if CMSDK_HAVE_OS_SYNC
513 if (__builtin_available(macOS 14.4, *)) {
514 os_sync_wake_by_address_any((void*)addr, 4, OS_SYNC_WAKE_BY_ADDRESS_SHARED);
515 return;
516 }
517 #endif
518 __ulock_wake(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO, (void*)addr, 0);
519 #else
520 syscall(SYS_futex, (uint32_t*)addr, FUTEX_WAKE, 1, NULL, NULL, 0);
521 #endif
522}
523
524static void SharedLockWakeAll(volatile uint32_t* addr) {
525 #if defined(__APPLE__)
526 #if CMSDK_HAVE_OS_SYNC
527 if (__builtin_available(macOS 14.4, *)) {
528 os_sync_wake_by_address_all((void*)addr, 4, OS_SYNC_WAKE_BY_ADDRESS_SHARED);
529 return;
530 }
531 #endif
532 __ulock_wake(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO | CMSDK_ULF_WAKE_ALL, (void*)addr, 0);
533 #else
534 syscall(SYS_futex, (uint32_t*)addr, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
535 #endif
536}
537
538#if defined(CMSDK_MUTEX_PID_RECOVERY) || defined(CMSDK_SEMAPHORE_WORD)
539// ---------------------------------------------------------------------------------------------------------------
540// macOS named mutexes: a lock word that IS the owner's pid (17 Nov 2026, v2; design from Isaac's macOS review).
541// v1 kept a pthread mutex plus a separate owner-pid record. Locking and recording were two steps, so a process
542// killed between them left a held mutex with no owner on record, which could never be recovered. It also polled
543// with trylock, which cost 30-65% latency on a busy Mac (processmemory_perf). Here:
544// - owner: 0 = free, else the pid of the holder. It is taken with one CAS (0 -> pid), so the owner is on record
545// from the first instant of the hold.
546// - tid + depth make it recursive per thread. They are written only by the holder; tid is set right after the CAS
547// and cleared before the release. A thread of the owning process that sees owner == its pid but a different tid
548// (or 0, in the gap) simply waits.
549// - Waiters spin briefly, then sleep in the kernel on the lock word: os_sync_wait_on_address (macOS 14.4+) or
550// __ulock_wait (older macOS), both cross-process (SHARED). On Linux, futex is used (the scheme is only built
551// there with -DCMSDK_MUTEX_PID_RECOVERY, to test it). The sleep is capped at 50 ms. After each sleep the waiter
552// checks whether the owner process still exists (kill(pid, 0) == ESRCH, or a zombie: exited but not reaped yet).
553// If it does not, the waiter takes the mutex over with one CAS (dead pid -> its pid) and logs a warning. The
554// data the mutex guarded may be half-updated, as with Windows' WAIT_ABANDONED and Linux's EOWNERDEAD.
555// - Not covered: a thread (not process) that ends holding the mutex, and pid reuse within 50 ms.
556// ---------------------------------------------------------------------------------------------------------------
557struct SharedLockWord {
558 volatile uint32_t owner; // 0 = free, else the holder's pid (the futex/ulock word)
559 volatile uint32_t waiters; // threads sleeping on owner
560 volatile uint64_t tid; // holding thread (0 while being set / cleared)
561 volatile uint32_t depth; // recursion depth (holder only)
562 volatile uint32_t recoveries; // times taken over from a dead owner (diagnostics)
563};
564static_assert(sizeof(SharedLockWord) <= MUTEXMEMSIZE, "MUTEXMEMSIZE too small for the lock word");
565
566static inline SharedLockWord* SharedLockOf(pthread_mutex_t* m) { return (SharedLockWord*)(void*)m; }
567
568// The caller's pid and thread id, cached per thread: getpid()/gettid() are system calls, and four of them per
569// lock/unlock made v2 slower than v1 (processmemory_perf on Linux, 17 Nov 2026). A fork generation (bumped in the
570// child by pthread_atfork) makes the forking thread refresh both in the child.
571static volatile uint32_t g_sharedLockForkGen = 1;
572static void SharedLockAtForkChild() { g_sharedLockForkGen++; }
573static pthread_once_t g_sharedLockAtForkOnce = PTHREAD_ONCE_INIT;
574static void SharedLockRegisterAtFork() { pthread_atfork(NULL, NULL, SharedLockAtForkChild); }
575static thread_local uint32_t t_sharedLockGen = 0;
576static thread_local uint32_t t_sharedLockPid = 0;
577static thread_local uint64_t t_sharedLockTid = 0;
578
579static inline void SharedLockSelf(uint32_t& pid, uint64_t& tid) {
580 if (t_sharedLockGen != g_sharedLockForkGen) {
581 pthread_once(&g_sharedLockAtForkOnce, SharedLockRegisterAtFork);
582 t_sharedLockPid = (uint32_t)getpid();
583 #ifdef __APPLE__
584 uint64_t t = 0;
585 pthread_threadid_np(NULL, &t);
586 t_sharedLockTid = t;
587 #else
588 t_sharedLockTid = (uint64_t)syscall(SYS_gettid);
589 #endif
590 t_sharedLockGen = g_sharedLockForkGen;
591 }
592 pid = t_sharedLockPid;
593 tid = t_sharedLockTid;
594}
595
596// Dead = gone (ESRCH) or a zombie (exited, not reaped yet - kill() still succeeds for those).
597static bool SharedLockPidIsDead(uint32_t pid, uint32_t mypid) {
598 if (!pid || (pid == mypid))
599 return false;
600 if (kill((pid_t)pid, 0) != 0)
601 return (errno == ESRCH);
602 #ifdef __APPLE__
603 struct kinfo_proc kp;
604 size_t len = sizeof(kp);
605 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid };
606 memset(&kp, 0, sizeof(kp));
607 if ((sysctl(mib, 4, &kp, &len, NULL, 0) == 0) && (len > 0))
608 return (kp.kp_proc.p_stat == SZOMB);
609 return false;
610 #else
611 char path[64], buf[512];
612 snprintf(path, sizeof(path), "/proc/%u/stat", pid);
613 FILE* f = fopen(path, "r");
614 if (!f) return false;
615 size_t n = fread(buf, 1, sizeof(buf) - 1, f);
616 fclose(f);
617 buf[n] = 0;
618 const char* p = strrchr(buf, ')'); // state follows the (comm), which may contain spaces
619 return (p && p[1] == ' ' && p[2] == 'Z');
620 #endif
621}
622
623static inline void SharedLockTake(SharedLockWord* w, uint64_t me) {
624 w->tid = me;
625 w->depth = 1;
626 __atomic_thread_fence(__ATOMIC_SEQ_CST);
627}
628
629// Acquire. timeoutMS 0 = wait for ever. Returns 0, ETIMEDOUT or EINVAL.
630static int SharedLockAcquire(pthread_mutex_t* m, uint32 timeoutMS, bool infinite, const char* name) {
631 SharedLockWord* w = SharedLockOf(m);
632 if (!w) return EINVAL;
633 uint32_t mypid;
634 uint64_t me;
635 SharedLockSelf(mypid, me);
636 uint64 start = 0, lastCheck = 0;
637 uint32 spins = 0;
638 for (;;) {
639 uint32_t cur = __atomic_load_n(&w->owner, __ATOMIC_SEQ_CST);
640 if (cur == mypid && w->tid == me) { // recursive re-entry (only we can have set tid == me)
641 w->depth++;
642 return 0;
643 }
644 if (cur == 0) {
645 uint32_t expected = 0;
646 if (__atomic_compare_exchange_n(&w->owner, &expected, mypid, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
647 SharedLockTake(w, me);
648 return 0;
649 }
650 continue;
651 }
652 if (spins < 32) { // short spin first: most holds last microseconds (no sched_yield: on a loaded
653 spins++; // box it hands the CPU to someone else and the lock goes cold; v2a, 17 Nov 2026)
654 #if defined(__x86_64__) || defined(__i386__)
655 __builtin_ia32_pause();
656 #elif defined(__aarch64__)
657 __asm__ __volatile__("yield");
658 #endif
659 continue;
660 }
661 if (!start)
662 start = lastCheck = GetTimeNow();
663 if (!infinite && (GetTimeAgeMS(start) >= (int64)timeoutMS))
664 return ETIMEDOUT;
665 // sleep on the word (at most 50 ms, or what is left of the timeout)
666 uint32_t sleepUS = 50000;
667 if (!infinite) {
668 int64 leftMS = (int64)timeoutMS - GetTimeAgeMS(start);
669 if (leftMS <= 0) return ETIMEDOUT;
670 if (leftMS * 1000 < (int64)sleepUS) sleepUS = (uint32_t)(leftMS * 1000);
671 }
672 __atomic_fetch_add(&w->waiters, 1, __ATOMIC_SEQ_CST);
673 SharedLockWait(&w->owner, cur, sleepUS);
674 __atomic_fetch_sub(&w->waiters, 1, __ATOMIC_SEQ_CST);
675 // still held by the same other process, and we have waited 50 ms since the last look: is it alive?
676 if ((cur != mypid) && (__atomic_load_n(&w->owner, __ATOMIC_SEQ_CST) == cur) && (GetTimeAgeMS(lastCheck) >= 50)) {
677 lastCheck = GetTimeNow();
678 if (!SharedLockPidIsDead(cur, mypid))
679 continue;
680 uint32_t expected = cur;
681 if (__atomic_compare_exchange_n(&w->owner, &expected, mypid, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
682 SharedLockTake(w, me);
683 __atomic_fetch_add(&w->recoveries, 1, __ATOMIC_SEQ_CST);
684 LogPrint(0, LOG_SYSTEM, 0, "Mutex '%s': owner process %u died holding it - recovered (the data it guarded may be inconsistent)",
685 name ? name : "-", cur);
686 return 0;
687 }
688 }
689 }
690}
691
692// Release one level. False if the calling thread does not hold it.
693static bool SharedLockRelease(pthread_mutex_t* m) {
694 SharedLockWord* w = SharedLockOf(m);
695 if (!w) return false;
696 uint32_t mypid;
697 uint64_t me;
698 SharedLockSelf(mypid, me);
699 if ((__atomic_load_n(&w->owner, __ATOMIC_SEQ_CST) != mypid) || (w->tid != me))
700 return false;
701 if (w->depth > 1) {
702 w->depth--;
703 return true;
704 }
705 w->depth = 0;
706 w->tid = 0;
707 __atomic_store_n(&w->owner, 0, __ATOMIC_SEQ_CST);
708 if (__atomic_load_n(&w->waiters, __ATOMIC_SEQ_CST))
709 SharedLockWakeOne(&w->owner);
710 return true;
711}
712#endif // CMSDK_MUTEX_PID_RECOVERY || CMSDK_SEMAPHORE_WORD
713#endif // !WINDOWS
714
715
716namespace utils {
717
718#ifndef WINDOWS
719//#if defined LINUX
720 bool CalcTimeout(struct timespec &timeout, uint32 ms) {
721 struct timeval now;
722 if (gettimeofday(&now, NULL) != 0)
723 return false;
724
725 timeout.tv_sec = now.tv_sec + (ms / 1000);
726 int64 us = (int64)(now.tv_usec) + ((ms % 1000)*1000);
727 while (us >= 1000000) {
728 timeout.tv_sec++;
729 us -= 1000000;
730 }
731 timeout.tv_nsec = (long)(us * 1000); // usec -> nsec
732 return true;
733 }
734
735 uint64 GetTime() {
736 struct timeval tv;
737 if ( gettimeofday(&tv, NULL))
738 return 0;
739 return (tv.tv_usec + tv.tv_sec * 1000000LL);
740 }
741#endif
742
743// https://stackoverflow.com/questions/44807302/create-c-timer-in-macos/52905687#52905687
744
745#ifdef WINDOWS
746 VOID CALLBACK DrumBeatCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) {
747 DrumBeatInfo* info = (DrumBeatInfo*) lpParameter;
748 DrumBeatFunc func = info->func;
749 if (!info->id || !info->createdTime || !info->started || !func)
750 return;
751 info->count++;
752 if (!info->func(info->id, info->count))
753 StopDrumBeat(info->id);
754 }
755#else
756 #ifndef __APPLE__
757 static void DrumBeatCallback(union sigval p) {
758 DrumBeatInfo* info = (DrumBeatInfo*) p.sival_ptr;
759 DrumBeatFunc func = info->func;
760 if (!info->id || !info->createdTime || !info->started || !func)
761 return;
762 info->count++;
763 if (!info->func(info->id, info->count))
764 StopDrumBeat(info->id);
765 }
766 #endif
767#endif
768
769bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart) {
770
771 if (!DrumBeatMap)
772 DrumBeatMap = new std::map<uint32, DrumBeatInfo>;
773 DrumBeatInfo* info = &(*DrumBeatMap)[id];
774
775 // check if it already exists
776 if (info->id && info->createdTime)
777 return false;
778
779 // Windows threadpool size limit is 500, we probably shouldn't create more than that anyway
780 // Could change the limit with WT_SET_MAX_THREADPOOL_THREAD
781 if (DrumBeatMap->size() > 450)
782 return false;
783
784 info->id = id;
785 info->createdTime = GetTimeNow();
786 info->func = func;
787 info->count = 0;
788 info->interval = interval;
789
790 #ifdef WINDOWS
791 #else
792 #ifdef __APPLE__
793 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
794 dispatch_source_t timer_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
795 if (timer_source)
796 info->handle = timer_source;
797 #else
798 // struct sigaction sa;
799 struct sigevent timer_event;
800
801 //sigemptyset(&sa.sa_mask);
802 //sa.sa_flags = SA_SIGINFO; /* Real-Time signal */
803 //sa.sa_sigaction = timer_signal_handler;
804 //sigaction(SIGRTMIN, &sa, NULL);
805
806 timer_event.sigev_notify = SIGEV_THREAD;
807 timer_event.sigev_notify_attributes = NULL;
808 timer_event.sigev_notify_function = DrumBeatCallback;
809 timer_event.sigev_value.sival_ptr = (void *)info;
810 int ret = timer_create(CLOCK_REALTIME, &timer_event, &info->handle);
811 if (ret != 0) {
812 LogPrint(0,LOG_SYSTEM,0,"Error creating timer: %d", ret);
813 }
814 #endif
815 #endif
816
817 if (autostart)
818 StartDrumBeat(id);
819 return true;
820}
821
822bool StartDrumBeat(uint32 id) {
823 if (!DrumBeatMap)
824 return false;
825 DrumBeatInfo* info = &(*DrumBeatMap)[id];
826 if (!info->id || !info->createdTime)
827 return false;
828
829 if (info->started)
830 return true;
831
832 #ifdef WINDOWS
833 // To compile an application that uses this function, define _WIN32_WINNT as 0x0500 or later
834 CreateTimerQueueTimer(&info->handle, NULL, DrumBeatCallback, info, info->interval, info->interval, WT_EXECUTEINTIMERTHREAD);
835 info->started = info->createdTime;
836 #else
837 #ifdef __APPLE__
838 if (info->handle) {
839 uint64 intervalNs = (uint64)info->interval * 1000000;
840 dispatch_source_set_timer(info->handle, dispatch_time(DISPATCH_TIME_NOW, (int64_t)intervalNs), intervalNs, 0);
841 DrumBeatInfo* inf = info;
842 dispatch_source_set_event_handler(info->handle, ^{
843 inf->count++;
844 if (!inf->func(inf->id, inf->count))
845 StopDrumBeat(inf->id);
846 });
847 dispatch_resume(info->handle);
848 info->started = info->createdTime;
849 }
850 #else
851 struct itimerspec newtv;
852 uint64 p = info->interval * 1000; // convert to nanosec
853 newtv.it_interval.tv_sec = p / 1000000;
854 newtv.it_interval.tv_nsec = (p % 1000000)*1000;
855 newtv.it_value.tv_sec = p / 1000000;
856 newtv.it_value.tv_nsec = (p % 1000000)*1000;
857
858 int ret = timer_settime(info->handle, 0, &newtv, NULL);
859 if (ret != 0) {
860 LogPrint(0,LOG_SYSTEM,0,"Error arming timer: %d", ret);
861 }
862 info->started = info->createdTime;
863 #endif
864 #endif
865 return true;
866}
867
868bool StopDrumBeat(uint32 id) {
869 if (!DrumBeatMap)
870 return false;
871 DrumBeatInfo* info = &(*DrumBeatMap)[id];
872 if (!info->id || !info->createdTime)
873 return false;
874
875 if (!info->started)
876 return true;
877
878 #ifdef WINDOWS
879 DeleteTimerQueueTimer(NULL, info->handle, NULL);
880 info->started = 0;
881 info->handle = NULL;
882 #else
883 #ifdef __APPLE__
884 if (info->handle) {
885 dispatch_suspend(info->handle);
886 info->started = 0;
887 }
888 #else
889 struct itimerspec newtv;
890 memset(&newtv, 0, sizeof(itimerspec));
891 int ret = timer_settime(info->handle, 0, &newtv, NULL);
892 if (ret != 0) {
893 LogPrint(0,LOG_SYSTEM,0,"Error arming timer: %d", ret);
894 }
895 info->started = 0;
896 #endif
897 #endif
898 return true;
899}
900
901bool EndDrumBeat(uint32 id) {
902 if (!DrumBeatMap)
903 return false;
904 DrumBeatInfo* info = &(*DrumBeatMap)[id];
905 if (!info->id || !info->createdTime)
906 return false;
907
908 #ifdef WINDOWS
909 if (info->started)
910 StopDrumBeat(id);
911 #else
912 #ifdef __APPLE__
913 if (info->handle) {
914 // libdispatch contract: a dispatch source must NOT be released while
915 // suspended — releasing a suspended source raises EXC_BREAKPOINT
916 // (SIGTRAP). StopDrumBeat leaves the source SUSPENDED (started==0), so a
917 // stopped-then-ended drumbeat crashed here on the old code path.
918 // Correct teardown: cancel FIRST (prevents any future handler firing),
919 // THEN, if suspended, resume to rebalance the suspend count to zero so
920 // the release is legal. Resuming an already-cancelled source does not
921 // re-run the timer handler, so there is no teardown race on the global
922 // concurrent queue the source runs on.
923 dispatch_source_cancel(info->handle);
924 if (!info->started)
925 dispatch_resume(info->handle);
926 dispatch_release(info->handle);
927 info->handle = NULL;
928 info->started = 0;
929 }
930 #else
931 timer_delete(info->handle);
932 info->started = 0;
933 info->handle = 0;
934 #endif
935 #endif
936
937 info->createdTime = 0;
938 info->func = NULL;
939 info->count = 0;
940 info->interval = 0;
941 return true;
942}
943
944
945bool EnterMutex(const char* name, uint32 ms, bool autocreate) {
947 SharedMemoryMutexMap = new std::map<std::string, Mutex*>;
950
951 Mutex* mutex;
952 std::map<std::string, Mutex*>::iterator i = SharedMemoryMutexMap->find(name);
953 std::map<std::string, Mutex*>::iterator e = SharedMemoryMutexMap->end();
954 if (i == e) {
956 i = SharedMemoryMutexMap->find(name);
957 if (i == e) {
958 if (!autocreate) {
960 return false;
961 }
962 mutex = new Mutex(name);
964 }
965 else {
966 // try again
967 if (i->second)
968 mutex = i->second;
969 else {
970 if (!autocreate) {
972 return false;
973 }
974 mutex = new Mutex(name);
976 }
977 }
979 }
980 else
981 mutex = i->second;
982 return (mutex->enter(ms));
983}
984
985bool LeaveMutex(const char* name) {
987 SharedMemoryMutexMap = new std::map<std::string, Mutex*>;
990
991 std::map<std::string, Mutex*>::iterator i = SharedMemoryMutexMap->find(name);
992 std::map<std::string, Mutex*>::iterator e = SharedMemoryMutexMap->end();
993 if (i == e)
994 return false;
995 return (i->second->leave());
996}
997
998bool DestroyMutex(const char* name) {
1000 SharedMemoryMutexMap = new std::map<std::string, Mutex*>;
1004
1005 std::map<std::string, Mutex*>::iterator i = SharedMemoryMutexMap->find(name);
1006 std::map<std::string, Mutex*>::iterator e = SharedMemoryMutexMap->end();
1007 if (i == e)
1008 return false;
1009 delete(i->second);
1010 SharedMemoryMutexMap->erase(i);
1012 return true;
1013}
1014
1015
1016
1017
1018
1019
1020
1021
1022#ifndef WINDOWS
1023// Named shared segments and semaphores: who may remove the name (18 Nov 2026).
1024// On POSIX a name outlives its users until someone unlinks it, and everyone opening the name later gets whatever the
1025// name points at by then. CloseSharedMemorySegment used to unlink the name in ANY process that closed a segment, and
1026// a named Semaphore removed its name in every process that deleted one. So a child that cleanly closed (or merely
1027// opened and closed) a node segment, a named Mutex, Event or Semaphore removed the name for everyone; the next process
1028// to open it got nothing, or for a Mutex/Event/Semaphore a brand-new object that no longer excluded against, or woke,
1029// the node. (Windows keeps a name while any handle is open, which is what the callers were written for.)
1030// Now only the process that created a name removes it, when it closes it. Names that belong to a node rather than to
1031// the process that happened to create them (segments made by a resize in any process, queue semaphores made on first
1032// use) are disowned, and the node removes them all (RemovePortSharedSegments) when it shuts down.
1034 std::string path; // file (macOS) or shm name (Linux)
1035 uint64 size; // mapped length (munmap uses this, not the caller's guess)
1036 pid_t creator; // pid that created the name and so removes it on close; 0 = nobody (disowned/opened)
1037};
1038static pthread_mutex_t SharedSegmentLock = PTHREAD_MUTEX_INITIALIZER;
1039static std::map<void*, SharedSegmentInfo>* SharedSegments = NULL; // never freed: closes can run during exit
1040static std::map<const void*, pid_t>* SharedSemaphoreCreators = NULL; // named Semaphore objects that own their name
1041
1042static void RegisterSharedSegment(void* data, const char* path, uint64 size, bool created) {
1043 pthread_mutex_lock(&SharedSegmentLock);
1044 if (!SharedSegments)
1045 SharedSegments = new std::map<void*, SharedSegmentInfo>;
1046 SharedSegmentInfo& info = (*SharedSegments)[data];
1047 info.path = path;
1048 info.size = size;
1049 info.creator = created ? getpid() : 0;
1050 pthread_mutex_unlock(&SharedSegmentLock);
1051}
1052
1053// True if this process created the segment's name (and has not disowned it). A forked child inherits the parent's
1054// table but not its ownership.
1055static bool SharedSegmentIsOwned(void* data) {
1056 bool owned = false;
1057 pthread_mutex_lock(&SharedSegmentLock);
1058 if (SharedSegments) {
1059 std::map<void*, SharedSegmentInfo>::iterator i = SharedSegments->find(data);
1060 owned = (i != SharedSegments->end()) && i->second.creator && (i->second.creator == getpid());
1061 }
1062 pthread_mutex_unlock(&SharedSegmentLock);
1063 return owned;
1064}
1065
1066static void SetSemaphoreOwnsName(const void* sem, bool owns) {
1067 pthread_mutex_lock(&SharedSegmentLock);
1069 SharedSemaphoreCreators = new std::map<const void*, pid_t>;
1070 if (owns)
1071 (*SharedSemaphoreCreators)[sem] = getpid();
1072 else
1073 SharedSemaphoreCreators->erase(sem);
1074 pthread_mutex_unlock(&SharedSegmentLock);
1075}
1076
1077// Forget the semaphore object; true if it owned its name.
1078static bool TakeSemaphoreOwnsName(const void* sem) {
1079 bool owns = false;
1080 pthread_mutex_lock(&SharedSegmentLock);
1082 std::map<const void*, pid_t>::iterator i = SharedSemaphoreCreators->find(sem);
1083 if (i != SharedSemaphoreCreators->end()) {
1084 owns = (i->second == getpid());
1085 SharedSemaphoreCreators->erase(i);
1086 }
1087 }
1088 pthread_mutex_unlock(&SharedSegmentLock);
1089 return owns;
1090}
1091#else
1092static inline void SetSemaphoreOwnsName(const void*, bool) {}
1093#endif
1094
1095Semaphore* GetSemaphore(const char* name, bool autocreate) {
1097 SharedMemorySemaphoreMap = new std::map<std::string, Semaphore*>;
1100 Semaphore* semaphore;
1101 std::map<std::string, Semaphore*>::iterator i = SharedMemorySemaphoreMap->find(name);
1102 std::map<std::string, Semaphore*>::iterator e = SharedMemorySemaphoreMap->end();
1103 if (i == e) {
1105 i = SharedMemorySemaphoreMap->find(name);
1106 if (i == e) {
1107 if (!autocreate) {
1109 return NULL;
1110 }
1111 semaphore = new Semaphore(name);
1112 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1114 }
1115 else {
1116 // try again
1117 if (i->second)
1118 semaphore = i->second;
1119 else {
1120 if (!autocreate) {
1122 return NULL;
1123 }
1124 semaphore = new Semaphore(name);
1125 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1127 }
1128 }
1130 }
1131 else
1132 semaphore = i->second;
1133 return semaphore;
1134}
1135
1136bool WaitForSemaphore(const char* name, uint32 ms, bool autocreate) {
1138 SharedMemorySemaphoreMap = new std::map<std::string, Semaphore*>;
1141 Semaphore* semaphore;
1142 std::map<std::string, Semaphore*>::iterator i = SharedMemorySemaphoreMap->find(name);
1143 std::map<std::string, Semaphore*>::iterator e = SharedMemorySemaphoreMap->end();
1144 if (i == e) {
1146 i = SharedMemorySemaphoreMap->find(name);
1147 if (i == e) {
1148 if (!autocreate) {
1150 return false;
1151 }
1152 semaphore = new Semaphore(name);
1153 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1155 }
1156 else {
1157 // try again
1158 if (i->second)
1159 semaphore = i->second;
1160 else {
1161 if (!autocreate) {
1163 return false;
1164 }
1165 semaphore = new Semaphore(name);
1166 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1168 }
1169 }
1171 }
1172 else
1173 semaphore = i->second;
1174 return (semaphore->wait(ms));
1175}
1176
1177bool SignalSemaphore(const char* name) {
1179 SharedMemorySemaphoreMap = new std::map<std::string, Semaphore*>;
1182
1183 Semaphore* semaphore;
1184 std::map<std::string, Semaphore*>::iterator i = SharedMemorySemaphoreMap->find(name);
1185 std::map<std::string, Semaphore*>::iterator e = SharedMemorySemaphoreMap->end();
1186 if (i == e) {
1188 i = SharedMemorySemaphoreMap->find(name);
1189 if (i == e) {
1190 semaphore = new Semaphore(name);
1191 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1193 }
1194 else {
1195 // try again
1196 if (i->second)
1197 semaphore = i->second;
1198 else {
1199 semaphore = new Semaphore(name);
1200 SetSemaphoreOwnsName(semaphore, false); // shared by name for the node's lifetime
1202 }
1203 }
1205 }
1206 else
1207 semaphore = i->second;
1208 return (semaphore->signal());
1209}
1210
1211bool DestroySemaphore(const char* name) {
1213 SharedMemorySemaphoreMap = new std::map<std::string, Semaphore*>;
1217
1218 std::map<std::string, Semaphore*>::iterator i = SharedMemorySemaphoreMap->find(name);
1219 std::map<std::string, Semaphore*>::iterator e = SharedMemorySemaphoreMap->end();
1220 if (i == e) {
1222 return false;
1223 }
1224 delete(i->second);
1225 SharedMemorySemaphoreMap->erase(i);
1227 return true;
1228}
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240bool WaitForNextEvent(const char* name, uint32 ms, bool autocreate) {
1242 SharedMemoryEventMap = new std::map<std::string, Event*>;
1245 Event* event;
1246 std::map<std::string, Event*>::iterator i = SharedMemoryEventMap->find(name);
1247 std::map<std::string, Event*>::iterator e = SharedMemoryEventMap->end();
1248 if (i == e) {
1250 i = SharedMemoryEventMap->find(name);
1251 if (i == e) {
1252 if (!autocreate) {
1254 return false;
1255 }
1256 event = new Event(name);
1257 SharedMemoryEventMap->insert(SharedMemoryEventMapPair(name, event));
1258 }
1259 else {
1260 // try again
1261 if (i->second)
1262 event = i->second;
1263 else {
1264 if (!autocreate) {
1266 return false;
1267 }
1268 event = new Event(name);
1269 SharedMemoryEventMap->insert(SharedMemoryEventMapPair(name, event));
1270 }
1271 }
1273 }
1274 else
1275 event = i->second;
1276 return (event->waitNext(ms));
1277}
1278
1279bool SignalEvent(const char* name) {
1281 SharedMemoryEventMap = new std::map<std::string, Event*>;
1284 std::map<std::string, Event*>::iterator i = SharedMemoryEventMap->find(name);
1285 std::map<std::string, Event*>::iterator e = SharedMemoryEventMap->end();
1286 if (i == e)
1287 return false;
1288 else
1289 return (i->second->signal());
1290}
1291
1292bool DestroyEvent(const char* name) {
1294 SharedMemoryEventMap = new std::map<std::string, Event*>;
1298
1299 std::map<std::string, Event*>::iterator i = SharedMemoryEventMap->find(name);
1300 std::map<std::string, Event*>::iterator e = SharedMemoryEventMap->end();
1301 if (i == e)
1302 return false;
1303 delete(i->second);
1304 SharedMemoryEventMap->erase(i);
1306 return true;
1307}
1308
1309
1310
1311
1312
1313bool SetSharedSystemInstance(uint32 inst) {
1314 SharedSystemInstance = inst;
1315 return true;
1316}
1317
1319 return SharedSystemInstance;
1320}
1321
1322
1323// ---------------------------------------------------------------------------
1324// Cancel-safe mutex support, stored OUT-OF-LINE so sizeof(Mutex) and its member
1325// layout stay byte-identical to the original (Mutex is embedded by value in
1326// size/layout-sensitive structs across shared objects; growing it corrupted the
1327// Linux libPsySystem.so build). The "is this mutex cancel-safe?" bit lives in a
1328// small pointer-keyed set; the saved cancel state is per-thread (thread_local),
1329// which is where cancel state conceptually belongs anyway.
1330#ifndef WINDOWS
1331static pthread_mutex_t g_cancelSafeSetLock = PTHREAD_MUTEX_INITIALIZER;
1332static std::map<const void*, bool>* g_cancelSafeSet = NULL; // present+true => cancel-safe
1333static __thread int g_savedCancelState = 0;
1334
1335// Lock-free fast-path guard: an exact count of how many mutexes are currently
1336// registered cancel-safe. MutexIsCancelSafe() runs on EVERY Mutex::enter() and
1337// every outermost Mutex::leave() of EVERY mutex in the process, so taking
1338// g_cancelSafeSetLock unconditionally made one global pthread mutex plus a
1339// red-black-tree lookup into a process-wide serialisation point sitting directly
1340// on the hot network/messaging path. Almost always nothing is registered, and
1341// this counter answers "no" without touching the lock or the map.
1342//
1343// Safety of the unlocked read: the counter is only mutated under
1344// g_cancelSafeSetLock and is kept an exact count of map entries, so it can never
1345// read 0 while an entry exists. A stale read is therefore only possible against
1346// a concurrent registration - and registration happens during object setup
1347// (ThreadManager construction, connection creation) before that object can be a
1348// cancel target, so reading 0 cannot drop a guarantee already established.
1349static volatile int g_cancelSafeCount = 0;
1350
1351static inline bool AnyCancelSafeMutexes() {
1352 #if defined(__GNUC__) || defined(__clang__)
1353 return __atomic_load_n(&g_cancelSafeCount, __ATOMIC_ACQUIRE) != 0;
1354 #else
1355 return g_cancelSafeCount != 0;
1356 #endif
1357}
1358
1359static bool MutexIsCancelSafe(const void* m) {
1360 if (!AnyCancelSafeMutexes())
1361 return false; // fast path: no global lock, no map lookup
1362 pthread_mutex_lock(&g_cancelSafeSetLock);
1363 bool r = (g_cancelSafeSet && g_cancelSafeSet->find(m) != g_cancelSafeSet->end());
1364 pthread_mutex_unlock(&g_cancelSafeSetLock);
1365 return r;
1366}
1367#endif
1368
1370 #ifndef WINDOWS
1371 pthread_mutex_lock(&g_cancelSafeSetLock);
1372 if (!g_cancelSafeSet)
1373 g_cancelSafeSet = new std::map<const void*, bool>();
1374 if (on) {
1375 // Only count real insertions/erasures, so the counter stays an exact
1376 // entry count (re-registering an already-registered mutex must not
1377 // inflate it, or it could never fall back to 0).
1378 if (g_cancelSafeSet->find(this) == g_cancelSafeSet->end()) {
1379 (*g_cancelSafeSet)[this] = true;
1381 }
1382 }
1383 else {
1384 if (g_cancelSafeSet->erase(this) > 0 && g_cancelSafeCount > 0)
1386 }
1387 pthread_mutex_unlock(&g_cancelSafeSetLock);
1388 #else
1389 (void)on;
1390 #endif
1391}
1392
1394 //uint32 tt;
1395 //utils::GetCurrentThreadOSID(tt);
1396 //printf("Mutex[%p] create by thread: %u\n", this, tt);
1397 name = NULL;
1398 osid = 0;
1399 count = 0;
1400 total = 0;
1401 created = true;
1402 #ifdef WINDOWS
1403 mutex = ::CreateMutex(NULL, FALSE, NULL);
1404 #else
1405 mutex = new pthread_mutex_t;
1406 pthread_mutexattr_t attr;
1407 pthread_mutexattr_init(&attr);
1408 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1409 pthread_mutex_init(mutex, &attr);
1410
1411 //semaphore = new sem_t;
1412 //if (sem_init(semaphore, 0, 1) != 0) {
1413 // delete(semaphore);
1414 // semaphore = NULL;
1415 //}
1416
1417 pthread_mutexattr_destroy(&attr);
1418 #endif
1419}
1420
1421Mutex::Mutex(const char* name, bool force) {
1422 this->name = new char[MAXSHMEMNAMELEN];
1423 osid = 0;
1424 count = 0;
1425 total = 0;
1426 created = true;
1427 #ifdef WINDOWS
1428 //sprintf(this->name, "Global\\Mutex_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
1429 snprintf(this->name, MAXSHMEMNAMELEN, "%s\\Mutex_%s", WINSHMEMSPACE, name);
1430 mutex = ::CreateMutex(NULL, FALSE, this->name);
1431 #else
1432 mutex = NULL;
1433// sprintf(this->name, "/Cond_%s", name);
1434// semaphore = sem_open(name, O_CREAT, 0666, 1);
1435
1436 snprintf(this->name, MAXSHMEMNAMELEN, "Mutex_%s", name);
1437
1438 // test if shared memory exists
1439 char* data = NULL;
1440
1441 if (!force)
1442 data = OpenSharedMemorySegment(this->name, MUTEXMEMSIZE);
1443 if (data) {
1444 mutex = (pthread_mutex_t*) data;
1445 created = false;
1446 }
1447 else {
1448 // create shared mutex
1449 if (data = CreateSharedMemorySegment(this->name, MUTEXMEMSIZE, force)) {
1450 // create mutex
1451 mutex = (pthread_mutex_t*) data;
1452 #ifdef CMSDK_MUTEX_PID_RECOVERY
1453 memset(data, 0, MUTEXMEMSIZE); // macOS: a free lock word (owner-death recovery)
1454 #else
1455 InitSharedMutexObject(mutex); // Linux: robust (owner-death recovery)
1456 #endif
1457 }
1458 }
1459 #endif
1460}
1461
1462#ifdef WINDOWS
1463bool CloseMutexHandle(HANDLE mutex) {
1464 // had to do this to catch exceptions in 32-bit Windows
1465 // as using __try+__except in C++ objects gave linker error
1466 __try {
1467 CloseHandle(mutex);
1468 }
1469 __except (EXCEPTION_EXECUTE_HANDLER) {
1470 }
1471 return true;
1472}
1473#endif
1474
1476 //uint32 tt;
1477 //utils::GetCurrentThreadOSID(tt);
1478 //printf("Mutex[%p] DELETE by thread: %u\n", this, tt);
1479 #ifndef WINDOWS
1480 // Unregister from the out-of-line cancel-safe side map, else a stale
1481 // entry keyed on this address would alias onto a future Mutex allocated
1482 // at the same address (harmless but wrong) and the map would grow
1483 // unboundedly for short-lived cancel-safe mutexes (per-connection ones).
1484 setCancelSafe(false);
1485 #endif
1486 #ifdef WINDOWS
1487 if (mutex == NULL)
1488 return;
1489
1490 CloseMutexHandle(mutex);
1491 mutex = NULL;
1492 delete [] name;
1493 #else
1494 if (!name) {
1495 pthread_mutex_destroy(mutex);
1496 // sem_destroy(semaphore);
1497 // delete(semaphore);
1498 }
1499 else {
1500 #ifndef CMSDK_MUTEX_PID_RECOVERY
1501 if (created)
1502 pthread_mutex_destroy(mutex);
1503 #endif
1505 mutex = NULL;
1506 // sem_close(semaphore);
1507 delete [] name;
1508 }
1509 #endif
1510}
1511
1513 #ifdef WINDOWS
1514 DWORD reply;
1515 reply = WaitForSingleObject(mutex, INFINITE);
1516 // WAIT_ABANDONED means the previous owner died while holding the mutex;
1517 // ownership IS granted to us, so treat it as a successful (if suspect) lock.
1518 // Returning false here while secretly owning the mutex would deadlock all
1519 // future waiters, which is exactly what intermittently broke the CMSDK tests.
1520 if (reply == WAIT_OBJECT_0 || reply == WAIT_ABANDONED) {
1522// if (count)
1523// int n=0;
1524 count++;
1525 total++;
1526 return true;
1527 }
1528 else if (reply == WAIT_FAILED && GetLastError() == ERROR_INVALID_HANDLE) {
1529 // The mutex handle is invalid (closed elsewhere, e.g. during teardown
1530 // storms where a stale/double CloseHandle invalidated it). Mirror the
1531 // timeout variant: treat as acquired so callers (typically shutdown
1532 // paths) proceed instead of failing; hanging here forever was the
1533 // alternative when the handle value got recycled into another object.
1534 LogPrint(0, LOG_SYSTEM, 1, "Mutex::enter on invalid handle [%p] - treating as acquired", mutex);
1535 return true;
1536 }
1537 else {
1538 return false;
1539 }
1540 #else
1541 // Cancel-safe mutexes disable thread cancellation BEFORE blocking on the
1542 // lock, so a pthread_cancel (e.g. during teardown) can never fire while we
1543 // hold it and orphan it. State kept out-of-line (see setCancelSafe): the
1544 // "is cancel-safe" bit in a side map, the saved cancel state in a thread-local.
1545 bool cs = MutexIsCancelSafe(this);
1546 int prevCancelState = 0;
1547 if (cs)
1548 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &prevCancelState);
1549 #ifdef CMSDK_MUTEX_PID_RECOVERY
1550 int error = name ? SharedLockAcquire(mutex, 0, true, name) : pthread_mutex_lock(mutex);
1551 #else
1552 int error = pthread_mutex_lock(mutex);
1553 if (error == EOWNERDEAD) {
1554 // robust (named) mutex: its owner died holding it, and we own it now
1555 pthread_mutex_consistent(mutex);
1556 LogPrint(0, LOG_SYSTEM, 0, "Mutex '%s': owner died holding it - recovered (the data it guarded may be inconsistent)", name ? name : "-");
1557 error = 0;
1558 }
1559 #endif
1560 if (error == 0) {
1562 // Capture the caller's real cancel state only on the OUTERMOST acquire
1563 // (recursive re-entry just re-disables an already-disabled state).
1564 if (cs && count == 0)
1565 g_savedCancelState = prevCancelState;
1566 count++;
1567 return true;
1568 }
1569 else {
1570 if (cs)
1571 pthread_setcancelstate(prevCancelState, NULL);
1572 LogPrint(0, LOG_SYSTEM, 0, "Lock of mutex failed: %s (%d)", name ? name : "-", error);
1573 return false;
1574 }
1575 #endif
1576}
1577
1578bool Mutex::enter(uint32 timeout, const char* errorMsg) {
1579// printf("*** %s ***\n", errorMsg);
1580// uint32 tt;
1581// utils::GetCurrentThreadOSID(tt);
1582// printf("Mutex[%p] locking by thread: %u\n", this, tt);
1583
1584 #ifdef WINDOWS
1585 DWORD reply;
1586 reply = WaitForSingleObject(mutex, timeout);
1587 // See Mutex::enter(): WAIT_ABANDONED grants ownership; treat as success.
1588 if (reply == WAIT_OBJECT_0 || reply == WAIT_ABANDONED) {
1590 //if (count)
1591 // printf("*** [%u]Mutex[%p](%s) locked more than once: %u\n", osid, mutex, errorMsg, count);
1592 //else
1593 // printf("--- [%u]Mutex[%p](%s) locked\n", osid, mutex, errorMsg);
1594 // if (count)
1595 // printf("Mutex[%p] double locking by thread: %u\n", this, tt);
1596
1597 count++;
1598 total++;
1599 return true;
1600 }
1601 //if (errorMsg) {
1602 uint32 osid2;
1604 if (reply == WAIT_TIMEOUT) {
1605 LogPrint(0, LOG_SYSTEM, 0, "[%u]Mutex enter timeout[%p](%s) - currently held by %u, count %u, total %u",
1606 osid2, mutex, errorMsg ? errorMsg : "-", osid, count, total);
1607 //if (!errorMsg)
1608 // int n = 0;
1609 }
1610 else if (reply == WAIT_FAILED) {
1611 DWORD mtxErr = GetLastError();
1612 if (mtxErr == ERROR_INVALID_HANDLE)
1613 return true;
1614 char* msg = new char[2048];
1615 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1616 NULL, mtxErr, 0, msg, 2048, NULL);
1617 msg[length] = '\0';
1618 LogPrint(0, LOG_SYSTEM, 0, "[%u]Mutex enter failed[%p](%s): %s - currently held by %u, count %u, total %u",
1619 osid2, mutex, errorMsg ? errorMsg : "-", msg, osid, count, total);
1620 delete[] msg;
1621 }
1622 else
1623 //[36136]Mutex enter error[00000000000016E0](-): 4294967295 - currently held by 0, count 0, total 7
1624 LogPrint(0,LOG_SYSTEM,0,"[%u]Mutex enter error[%p](%s): %d - currently held by %u, count %u, total %u",
1625 osid2, mutex, errorMsg ? errorMsg : "-", reply, osid, count, total);
1626 //}
1627 return false;
1628 #else
1629 struct timespec ts;
1630 CalcTimeout(ts, timeout);
1631 // See Mutex::enter(): disable cancellation before blocking on a cancel-safe
1632 // lock so a cancel can never orphan it. State is out-of-line (setCancelSafe).
1633 bool cs = MutexIsCancelSafe(this);
1634 int prevCancelState = 0;
1635 if (cs)
1636 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &prevCancelState);
1637 #if defined(CMSDK_MUTEX_PID_RECOVERY) && defined(__APPLE__)
1638 int error = name ? SharedLockAcquire(mutex, timeout, false, name) : macos_pthread_mutex_timedlock(mutex, &ts);
1639 #elif defined(CMSDK_MUTEX_PID_RECOVERY)
1640 int error = name ? SharedLockAcquire(mutex, timeout, false, name) : pthread_mutex_timedlock(mutex, &ts);
1641 #elif defined(__APPLE__)
1642 int error = macos_pthread_mutex_timedlock(mutex, &ts);
1643 #else
1644 int error = pthread_mutex_timedlock(mutex, &ts);
1645 if (error == EOWNERDEAD) {
1646 // robust (named) mutex: its owner died holding it, and we own it now
1647 pthread_mutex_consistent(mutex);
1648 LogPrint(0, LOG_SYSTEM, 0, "Mutex '%s': owner died holding it - recovered (the data it guarded may be inconsistent)", name ? name : "-");
1649 error = 0;
1650 }
1651 #endif
1652 if (error == 0) {
1654 if (cs && count == 0)
1655 g_savedCancelState = prevCancelState;
1656 count++;
1657 // if (count > 1)
1658 // printf("Lock count now %u...\n", count);
1659 // LogPrint(0,LOG_SYSTEM,0,"Mutex enter success: '%s' (%d) [%p] - I am %u", errorMsg, error, this, osid);
1660 return true;
1661 }
1662 else if (cs) {
1663 // Timed out / failed without acquiring: undo the cancel-disable so we
1664 // don't leave the caller permanently non-cancellable.
1665 pthread_setcancelstate(prevCancelState, NULL);
1666 }
1667 if (error == EINVAL) {
1668 LogPrint(0,LOG_SYSTEM,0,"Mutex enter error: '%s' (%d) [%u = %llu.%lld]",
1669 errorMsg ? errorMsg : "-", error, timeout, (uint64)(ts.tv_sec), (int64)(ts.tv_nsec));
1670 return false;
1671 }
1672// if (errorMsg)
1673 LogPrint(0,LOG_SYSTEM,0,"Mutex enter timeout %u: '%s' (%d) [%p] - held by %u", timeout, errorMsg ? errorMsg : "-", error, this, osid);
1674 return false;
1675
1676 //if (pthread_mutex_trylock(mutex) == 0)
1677 // return true;
1678
1679 //printf("[w-%s]", errorMsg);
1680 //fflush(stdout);
1682 //uint64 start = GetTimeNow();
1683 //struct timespec ts;
1684 //CalcTimeout(ts, timeout);
1685
1686 //int res = 1;
1687 //do {
1688 // if (sem_timedwait(semaphore, &ts) != 0)
1689 // break;
1690 // res = pthread_mutex_trylock(mutex);
1691 //} while ( !res && (GetTimeAgeMS(start) < (int32)timeout) );
1692
1693 //if (res) {
1694 // printf("s");
1695 // fflush(stdout);
1696 // return true;
1697 //}
1698 //if (errorMsg)
1699 // LogPrint(0,LOG_SYSTEM,0,"Mutex enter timeout: %s", errorMsg);
1700 //return false;
1701 #endif
1702}
1703
1705// uint32 tt;
1706// utils::GetCurrentThreadOSID(tt);
1707// printf("Mutex[%p] leaving by thread: %u\n", this, tt);
1708 #ifdef WINDOWS
1709 uint32 osid2 = osid;
1710 //utils::GetCurrentThreadOSID(osid2);
1711 //else
1712 // return true;
1713 //if (osid != osid2)
1714 // printf("*** [%u]Mutex[%p] unlocked by someone else: %u\n", osid, mutex, osid2);
1715 //if (!count)
1716 // osid = 0;
1717 if (ReleaseMutex(mutex) != 0) {
1718 if (count)
1719 count--;
1720 if (!count)
1721 osid = 0;
1722 //else
1723 // printf("Mutex[%p] double release by thread: %u\n", this, tt);
1724 //osid = 0;
1725 return true;
1726 }
1727 else {
1728 // reinstate values
1729 //count++;
1730 osid = osid2;
1731 return false;
1732 }
1733 #else
1734 // Capture whether this is the outermost release BEFORE unlocking; if it is,
1735 // restore the caller's cancel state AFTER the unlock so any cancel that was
1736 // pending during the (now-complete) critical section can finally land -- but
1737 // only once we no longer hold the lock, so it can never orphan it. State is
1738 // out-of-line (see setCancelSafe): cancel-safe bit in a side map, saved
1739 // cancel state in a thread-local.
1740 bool outermost = (count == 1 && MutexIsCancelSafe(this));
1741 int restoreState = g_savedCancelState;
1742 // Update this object's bookkeeping while we still hold the lock (17 Nov 2026, Isaac). Done after the unlock,
1743 // another thread sharing this object could take the mutex in between, see count == 1 and skip recording
1744 // itself as the owner (v1 of the macOS owner-death recovery then held the mutex with ownerPid 0; psy_extexec_limit
1745 // on macOS: 0/10 -> 8/10 in an A/B). The non-atomic count-- could also race the next holder's count++.
1746 uint32 prevOsid = osid;
1747 osid = 0;
1748 count--;
1749 #ifdef CMSDK_MUTEX_PID_RECOVERY
1750 bool released = name ? SharedLockRelease(mutex) : (pthread_mutex_unlock(mutex) == 0);
1751 #else
1752 bool released = (pthread_mutex_unlock(mutex) == 0);
1753 #endif
1754 if (!released) {
1755 count++;
1756 osid = prevOsid;
1757 return false;
1758 }
1759 if (outermost)
1760 pthread_setcancelstate(restoreState, NULL);
1761 return true;
1762
1763 // Signal semaphore
1764 // return (sem_post(semaphore) == 0);
1765 #endif
1766}
1767
1768//bool Mutex::destroy() {
1769// #ifdef WINDOWS
1770// #else
1771// pthread_mutex_destroy(mutex);
1772// DestroySharedMemorySegment((char*)mutex, MUTEXMEMSIZE);
1773// mutex = NULL;
1774// sem_unlink(name);
1775// #endif
1776// return true;
1777//}
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791#ifdef CMSDK_SEMAPHORE_WORD
1792// ---------------------------------------------------------------------------------------------------------------
1793// macOS named semaphores: a counter word in a shared segment (18 Nov 2026). They were a pthread mutex + condition +
1794// count in the segment. Those mutexes are not robust, so a process that died inside wait() or signal() (an external
1795// component crashing, psy_extexec_limit) left the mutex locked for ever, and the next signal() blocked in
1796// pthread_mutex_lock with no timeout. ProcessMemory::addToQ signals while holding PsycloneProcessMemoryMutex, so a
1797// node thread then held that mutex for ever and the whole node timed out on it (Isaac, macOS 53ecf01, 2 of 119
1798// runs: "held by <node thread>"). Linux's sem_t has no such lock. Now the count is the word itself: wait takes one
1799// with a CAS and otherwise sleeps on the word (os_sync/ulock, futex in the Linux test build, at most 50 ms at a
1800// time); signal adds one and wakes a sleeper. Nothing is ever held, so a process can die anywhere in it.
1801// ---------------------------------------------------------------------------------------------------------------
1802struct SharedSemWord {
1803 volatile uint32_t count;
1804 volatile uint32_t waiters; // sleepers (a dead one only costs a spare wake call)
1805};
1806static_assert(sizeof(SharedSemWord) <= SEMAPHOREMEMSIZE, "SEMAPHOREMEMSIZE too small for the semaphore word");
1807
1808static void* SemWordOpen(const char* name, const void* owner) {
1809 char shmemname[MAXSHMEMNAMELEN];
1810 snprintf(shmemname, sizeof(shmemname), "Semaphore_%s", name);
1811 char* data = OpenSharedMemorySegment(shmemname, SEMAPHOREMEMSIZE);
1812 if (!data) {
1813 data = CreateSharedMemorySegment(shmemname, SEMAPHOREMEMSIZE, true);
1814 if (data) {
1815 SetSemaphoreOwnsName(owner, true);
1816 SharedSemWord* w = (SharedSemWord*)data;
1817 w->waiters = 0;
1818 __atomic_store_n(&w->count, 1, __ATOMIC_SEQ_CST); // POSIX named semaphores here start at 1
1819 }
1820 }
1821 return data;
1822}
1823
1824static void SemWordClose(void* data, const void* owner) {
1825 if (!data) return;
1826 if (!TakeSemaphoreOwnsName(owner))
1827 DisownSharedMemorySegment((char*)data); // opened, or a node-shared one (GetSemaphore)
1829}
1830
1831// timeoutMS ignored when infinite
1832static bool SemWordWait(void* data, uint32 timeoutMS, bool infinite) {
1833 SharedSemWord* w = (SharedSemWord*)data;
1834 if (!w) return false;
1835 uint64 start = 0;
1836 for (;;) {
1837 uint32_t c = __atomic_load_n(&w->count, __ATOMIC_SEQ_CST);
1838 if (c) {
1839 if (__atomic_compare_exchange_n(&w->count, &c, c - 1, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
1840 return true;
1841 continue;
1842 }
1843 uint32_t sleepUS = 50000;
1844 if (!infinite) {
1845 if (!start)
1846 start = GetTimeNow();
1847 int64 leftMS = (int64)timeoutMS - GetTimeAgeMS(start);
1848 if (leftMS <= 0)
1849 return false;
1850 if (leftMS * 1000 < (int64)sleepUS)
1851 sleepUS = (uint32_t)(leftMS * 1000);
1852 }
1853 __atomic_fetch_add(&w->waiters, 1, __ATOMIC_SEQ_CST);
1854 SharedLockWait(&w->count, 0, sleepUS); // returns at once if count is no longer 0
1855 __atomic_fetch_sub(&w->waiters, 1, __ATOMIC_SEQ_CST);
1856 }
1857}
1858
1859static bool SemWordSignal(void* data) {
1860 SharedSemWord* w = (SharedSemWord*)data;
1861 if (!w) return false;
1862 __atomic_fetch_add(&w->count, 1, __ATOMIC_SEQ_CST);
1863 if (__atomic_load_n(&w->waiters, __ATOMIC_SEQ_CST))
1864 SharedLockWakeOne(&w->count);
1865 return true;
1866}
1867
1868// where a named semaphore keeps its segment: semaphore_impl on macOS, the (then unused) sem_t* in the Linux test build
1869#ifdef __APPLE__
1870 #define CMSDK_SEMWORD_SLOT semaphore_impl
1871#else
1872 #define CMSDK_SEMWORD_SLOT (*(void**)&semaphore)
1873#endif
1874#endif // CMSDK_SEMAPHORE_WORD
1875
1876Semaphore::Semaphore(uint32 maxCount) {
1877 name = NULL;
1878 #ifdef WINDOWS
1879 semaphore = CreateSemaphore(
1880 NULL, // no security attributes
1881 0, // initial count
1882 10, // maximum count
1883 NULL); // unnamed semaphore
1884 #else
1885 #ifdef __APPLE__
1886 semaphore_impl = dispatch_semaphore_create(0);
1887 #else
1888 semaphore = new sem_t;
1889 if (sem_init(semaphore, 0, 0) != 0) {
1890 delete(semaphore);
1891 semaphore = NULL;
1892 }
1893 #endif
1894 #endif
1895}
1896
1897Semaphore::Semaphore(const char* name, uint32 maxCount) {
1898 this->name = new char[MAXSHMEMNAMELEN];
1899 #ifdef WINDOWS
1900 //sprintf(this->name, "Global\\Semaphore_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
1901 snprintf(this->name, MAXSHMEMNAMELEN, "%s\\Semaphore_%s", WINSHMEMSPACE, name);
1902 // Creates or gets an existing Semaphore
1903 semaphore = CreateSemaphore(
1904 NULL, // no security attributes
1905 0, // initial count
1906 maxCount, // maximum count
1907 this->name); // unnamed semaphore
1908 #elif defined(CMSDK_SEMAPHORE_WORD)
1909 // macOS (and the Linux test build): a counter word in a shared segment, see SemWordWait
1910 #ifndef __APPLE__
1911 semaphore = NULL;
1912 #endif
1913 CMSDK_SEMWORD_SLOT = SemWordOpen(name, this);
1914 #else
1915 snprintf(this->name, MAXSHMEMNAMELEN, "/Semaphore_%s", name);
1916// sprintf(this->name, "/Semaphore_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
1917 // O_EXCL first, so we know whether we made the name (and so remove it when we go)
1918 semaphore = sem_open(this->name, O_CREAT | O_EXCL, 0666, 1);
1919 if (semaphore != SEM_FAILED)
1920 SetSemaphoreOwnsName(this, true);
1921 else
1922 semaphore = sem_open(this->name, O_CREAT, 0666, 1);
1923 if (semaphore == SEM_FAILED)
1924 semaphore = NULL;
1925 #endif
1926 // Rewrite the original name
1927 utils::strcpyavail(this->name, name, MAXKEYNAMELEN, true);
1928}
1929
1931 #ifdef WINDOWS
1932 if (semaphore) {
1933 CloseHandle(semaphore);
1934 semaphore = NULL;
1935 }
1936 delete [] name;
1937 #else
1938 if (!name) {
1939 #ifdef __APPLE__
1940 if (semaphore_impl)
1941 dispatch_release((dispatch_semaphore_t)semaphore_impl);
1942 semaphore_impl = NULL;
1943 #else
1944 sem_destroy(semaphore);
1945 delete(semaphore);
1946 #endif
1947 }
1948 else {
1949 #ifdef CMSDK_SEMAPHORE_WORD
1950 SemWordClose(CMSDK_SEMWORD_SLOT, this);
1951 CMSDK_SEMWORD_SLOT = NULL;
1952 #else
1953 if (semaphore)
1954 sem_close(semaphore);
1955 // Remove the /dev/shm/sem.Semaphore_<name> entry only if this object created it (ctor rewrote
1956 // this->name back to the bare name, so re-prefix). Removing it from any other process cut the
1957 // name away from the others: the next opener made a new semaphore nobody else signals.
1958 if (TakeSemaphoreOwnsName(this)) {
1959 char semname[MAXSHMEMNAMELEN];
1960 snprintf(semname, sizeof(semname), "/Semaphore_%s", name);
1961 sem_unlink(semname);
1962 }
1963 #endif
1964 delete [] name;
1965 }
1966 #endif
1967}
1968
1970 #ifdef WINDOWS
1971 return (WaitForSingleObject(semaphore, INFINITE) == WAIT_OBJECT_0);
1972 #else
1973 #ifdef CMSDK_SEMAPHORE_WORD
1974 if (name)
1975 return SemWordWait(CMSDK_SEMWORD_SLOT, 0, true);
1976 #endif
1977 #ifdef __APPLE__
1978 return dispatch_semaphore_wait((dispatch_semaphore_t)semaphore_impl, DISPATCH_TIME_FOREVER) == 0;
1979 #else
1980 int r = sem_wait(semaphore);
1981 return r == 0;
1982 #endif
1983 #endif
1984}
1985
1986bool Semaphore::wait(uint32 timeout) {
1987 #ifdef WINDOWS
1988 return (WaitForSingleObject(semaphore, timeout) == WAIT_OBJECT_0);
1989 #else
1990 #ifdef CMSDK_SEMAPHORE_WORD
1991 if (name)
1992 return SemWordWait(CMSDK_SEMWORD_SLOT, timeout, false);
1993 #endif
1994 #ifdef __APPLE__
1995 dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)timeout * 1000000);
1996 return dispatch_semaphore_wait((dispatch_semaphore_t)semaphore_impl, when) == 0;
1997 #else
1998 struct timespec t;
1999 CalcTimeout(t, timeout);
2000 int r = sem_timedwait(semaphore, &t);
2001 return r == 0;
2002 #endif
2003 #endif
2004}
2005
2007 #ifdef WINDOWS
2008 return (ReleaseSemaphore(
2009 semaphore, // handle to semaphore
2010 1, // increase count by one
2011 NULL) != 0); // not interested in previous count
2012 #else
2013 #ifdef CMSDK_SEMAPHORE_WORD
2014 if (name)
2015 return SemWordSignal(CMSDK_SEMWORD_SLOT);
2016 #endif
2017 #ifdef __APPLE__
2018 return dispatch_semaphore_signal((dispatch_semaphore_t)semaphore_impl) != 0;
2019 #else
2020 int r = sem_post(semaphore);
2021 return (r == 0);
2022 #endif
2023 #endif
2024}
2025
2026//bool Semaphore::destroy() {
2027// #ifdef WINDOWS
2028// return true;
2029// #else
2030// if (name)
2031// sem_unlink(name);
2032// return true;
2033// #endif
2034//}
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048#ifndef WINDOWS
2049// ---------------------------------------------------------------------------------------------------------------
2050// POSIX named Events: a generation word in a shared segment (18 Nov 2026). They were a pthread mutex + condition in
2051// the segment, not robust: a process killed while holding that mutex left it locked for ever (every later signal()
2052// and waitNext() blocked with no timeout), and one killed while waiting could leave the condition expecting it. Now
2053// signal() bumps the generation and wakes every sleeper; waitNext() notes the generation and sleeps on the word until
2054// it changes (os_sync/ulock or futex, at most 50 ms at a time). Same meaning as before: a signal wakes whoever waits
2055// at that moment and is not kept for later waiters. Nothing is ever held, so a process can die anywhere in it.
2056// (Anonymous Events stay an in-process pthread condition.)
2057// ---------------------------------------------------------------------------------------------------------------
2059 volatile uint32_t gen; // bumped by every signal
2060 volatile uint32_t waiters; // sleepers (a dead one only costs a spare wake call)
2061};
2062static_assert(sizeof(SharedEventWord) <= EVENTMEMSIZE, "EVENTMEMSIZE too small for the event word");
2063
2064static bool EventWordWait(void* data, uint32 timeoutMS, bool infinite) {
2065 SharedEventWord* w = (SharedEventWord*)data;
2066 if (!w) return false;
2067 uint32_t g = __atomic_load_n(&w->gen, __ATOMIC_SEQ_CST);
2068 uint64 start = infinite ? 0 : GetTimeNow();
2069 for (;;) {
2070 uint32_t sleepUS = 50000;
2071 if (!infinite) {
2072 int64 leftMS = (int64)timeoutMS - GetTimeAgeMS(start);
2073 if (leftMS <= 0)
2074 return false;
2075 if (leftMS * 1000 < (int64)sleepUS)
2076 sleepUS = (uint32_t)(leftMS * 1000);
2077 }
2078 __atomic_fetch_add(&w->waiters, 1, __ATOMIC_SEQ_CST);
2079 if (__atomic_load_n(&w->gen, __ATOMIC_SEQ_CST) == g)
2080 SharedLockWait(&w->gen, g, sleepUS); // returns at once if gen has moved on
2081 __atomic_fetch_sub(&w->waiters, 1, __ATOMIC_SEQ_CST);
2082 if (__atomic_load_n(&w->gen, __ATOMIC_SEQ_CST) != g)
2083 return true;
2084 }
2085}
2086
2087static bool EventWordSignal(void* data) {
2088 SharedEventWord* w = (SharedEventWord*)data;
2089 if (!w) return false;
2090 __atomic_fetch_add(&w->gen, 1, __ATOMIC_SEQ_CST);
2091 if (__atomic_load_n(&w->waiters, __ATOMIC_SEQ_CST))
2093 return true;
2094}
2095#endif
2096
2098 name = NULL;
2099 #ifdef WINDOWS
2100 event = CreateEvent(
2101 NULL, // default security attributes
2102 TRUE, // manual-reset event
2103 FALSE, // initial state is nonsignaled
2104 NULL); // object name
2105 #else
2106 event = new pthread_cond_t;
2107 pthread_cond_init(event, NULL);
2108
2109 mutex = new pthread_mutex_t;
2110 pthread_mutex_init(mutex, NULL);
2111 #endif
2112}
2113
2114Event::Event(const char* name) {
2115 this->name = new char[MAXSHMEMNAMELEN];
2116 #ifdef WINDOWS
2117 //sprintf(this->name, "Global\\Event_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
2118 snprintf(this->name, MAXSHMEMNAMELEN, "%s\\Event_%s", WINSHMEMSPACE, name);
2119 // Creates or gets an existing Event
2120 event = CreateEvent(
2121 NULL, // default security attributes
2122 TRUE, // manual-reset event
2123 FALSE, // initial state is nonsignaled
2124 this->name); // object name
2125 #else
2126 // a generation word in a shared segment (see EventWordWait); 'mutex' holds the segment, 'event' is unused
2127 snprintf(this->name, MAXSHMEMNAMELEN, "Event_%s", name);
2128 event = NULL;
2129 char* data = OpenSharedMemorySegment(this->name, EVENTMEMSIZE);
2130 if (!data) {
2131 if ((data = CreateSharedMemorySegment(this->name, EVENTMEMSIZE, true)) != NULL) {
2132 SharedEventWord* w = (SharedEventWord*)data;
2133 w->waiters = 0;
2134 __atomic_store_n(&w->gen, 0, __ATOMIC_SEQ_CST);
2135 }
2136 }
2137 mutex = (pthread_mutex_t*) data;
2138 #endif
2139}
2140
2142 #ifdef WINDOWS
2143 if (event) {
2144 CloseHandle(event);
2145 event = NULL;
2146 }
2147 delete [] name;
2148 #else
2149 if (!name) {
2150 pthread_cond_destroy(event);
2151 delete(event);
2152 pthread_mutex_destroy(mutex);
2153 delete(mutex);
2154 }
2155 else {
2156 if (mutex)
2157 CloseSharedMemorySegment((char*)mutex, EVENTMEMSIZE); // the creator removes the name
2158 mutex = NULL;
2159 event = NULL;
2160 delete [] name;
2161 }
2162 #endif
2163}
2164
2166 #ifdef WINDOWS
2167 return (WaitForSingleObject(event, INFINITE) == WAIT_OBJECT_0);
2168 #else
2169 if (name)
2170 return EventWordWait(mutex, 0, true);
2171 pthread_mutex_lock(mutex);
2172 int r = pthread_cond_wait(event, mutex);
2173 pthread_mutex_unlock(mutex);
2174 return r == 0;
2175 #endif
2176}
2177
2178bool Event::waitNext(uint32 timeout) {
2179 #ifdef WINDOWS
2180 return (WaitForSingleObject(event, timeout) == WAIT_OBJECT_0);
2181 #else
2182 if (name)
2183 return EventWordWait(mutex, timeout, false);
2184 pthread_mutex_lock(mutex);
2185 struct timespec t;
2186 CalcTimeout(t, timeout);
2187 int r = pthread_cond_timedwait(event, mutex, &t);
2188 pthread_mutex_unlock(mutex);
2189 return r == 0;
2190 #endif
2191}
2192
2194 #ifdef WINDOWS
2195 if (!SetEvent(event))
2196 return false;
2197// Sleep(1);
2198 ResetEvent(event);
2199 return true;
2200 #else
2201 if (name)
2202 return EventWordSignal(mutex);
2203 pthread_mutex_lock(mutex);
2204 int r = pthread_cond_broadcast(event);
2205 pthread_mutex_unlock(mutex);
2206 return (r == 0);
2207 #endif
2208}
2209
2210//bool Event::destroy() {
2211// #ifdef WINDOWS
2212// return true;
2213// #else
2214// if (name)
2215// sem_unlink(name);
2216// return true;
2217// #endif
2218//}
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233std::map<uint32, Timer*>* Timer::timers = NULL;
2234
2236 if (!timers)
2237 timers = new std::map<uint32, Timer*>;
2238 globalID = 0;
2239 while (timers->find(globalID) != timers->end())
2240 globalID++;
2241 (*timers)[globalID] = this;
2242}
2243
2245 if (!timers)
2246 return;
2247 timers->erase(globalID);
2248 mutex.enter();
2249 std::map<uint32, TimerSchedule*>::iterator it = schedules.begin();
2250 std::map<uint32, TimerSchedule*>::iterator itEnd = schedules.end();
2251 while (it != itEnd)
2252 removeTimer((it++)->first);
2253
2254 // Now delete the remaining old schedules that were kept
2255 // in case a timer returned the same time as it was removed
2256 std::list<TimerSchedule*>::iterator it2 = oldSchedules.begin();
2257 std::list<TimerSchedule*>::iterator it2End = oldSchedules.end();
2258 while (it2 != it2End)
2259 delete(*it2++);
2260 oldSchedules.clear();
2261
2262 mutex.leave();
2263}
2264
2265bool Timer::addTimer(uint32 id, uint32 interval, uint64 start, uint64 end) {
2266 mutex.enter();
2267 if (schedules[id]) {
2268 mutex.leave();
2269 return false;
2270 }
2271
2272 TimerSchedule* schedule = new TimerSchedule;
2273 schedule->globalID = globalID;
2274 schedule->id = id;
2275 schedule->handle = 0;
2276 schedule->start = start;
2277 schedule->end = end;
2278 schedule->interval = interval;
2279 schedules[id] = schedule;
2280
2281 uint64 now = GetTimeNow();
2282 uint32 firstDelay = 0;
2283 if (start && (start > now))
2284 firstDelay = (uint32)(start - now)/1000;
2285
2286 // Create and set timer
2287 #ifdef WINDOWS
2288 if (!CreateTimerQueueTimer(&schedule->handle, NULL, TimerCallback, schedule, firstDelay, interval, WT_EXECUTEINTIMERTHREAD)) {
2289 schedules[id] = NULL;
2290 delete(schedule);
2291 mutex.leave();
2292 return false;
2293 }
2294 #else
2295 #ifdef __APPLE__
2296 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
2297 dispatch_source_t timer_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
2298 if (!timer_source) {
2299 schedules[id] = NULL;
2300 delete(schedule);
2301 mutex.leave();
2302 return false;
2303 }
2304 schedule->handle = timer_source;
2305 uint64 firstDelayNs = (uint64)firstDelay * 1000000;
2306 uint64 intervalNs = (uint64)interval * 1000000;
2307 dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (int64_t)firstDelayNs), intervalNs, 0);
2308 dispatch_source_set_event_handler(timer_source, ^{
2309 if (!Timer::timers)
2310 return;
2311 TimerSchedule* sched = schedule;
2312 if (!sched)
2313 return;
2314 Timer* timer = (*Timer::timers)[sched->globalID];
2315 if (timer)
2316 timer->triggerTimer(sched->id);
2317 });
2318 dispatch_resume(timer_source);
2319 #else
2320 struct sigaction sa;
2321 struct sigevent timer_event;
2322
2323 sigemptyset(&sa.sa_mask);
2324 sa.sa_flags = SA_SIGINFO; /* Real-Time signal */
2325 sa.sa_sigaction = TimerCallback;
2326 sigaction(SIGRTMIN, &sa, NULL);
2327
2328 timer_event.sigev_notify = SIGEV_SIGNAL;
2329 timer_event.sigev_signo = SIGRTMIN;
2330 timer_event.sigev_value.sival_ptr = (void *)schedule;
2331 if (timer_create(CLOCK_REALTIME, &timer_event, &schedule->handle) != 0) {
2332 schedules[id] = NULL;
2333 delete(schedule);
2334 mutex.leave();
2335 return false;
2336 }
2337
2338 struct itimerspec newtv;
2339 sigset_t allsigs;
2340
2341 uint64 period = interval * 1000;
2342 newtv.it_value.tv_sec = firstDelay / 1000000;
2343 newtv.it_value.tv_nsec = (firstDelay % 1000000)*1000;
2344 newtv.it_interval.tv_sec = period / 1000000;
2345 newtv.it_interval.tv_nsec = (period % 1000000)*1000;
2346
2347 if (timer_settime(schedule->handle, 0, &newtv, NULL) != 0) {
2348 timer_delete(schedule->handle);
2349 schedules[id] = NULL;
2350 delete(schedule);
2351 mutex.leave();
2352 return false;
2353 }
2354 sigemptyset(&allsigs);
2355 #endif
2356 #endif
2357
2358 mutex.leave();
2359 return true;
2360}
2361
2362bool Timer::removeTimer(uint32 id) {
2363 mutex.enter();
2364
2365 TimerSchedule* schedule = schedules[id];
2366 if (!schedule) {
2367 mutex.leave();
2368 return true;
2369 }
2370
2371 schedules[id] = NULL;
2372
2373 #ifdef WINDOWS
2374 DeleteTimerQueueTimer(NULL, schedule->handle, NULL);
2375 #else
2376 #ifdef __APPLE__
2377 dispatch_source_cancel(schedule->handle);
2378 dispatch_release(schedule->handle);
2379 #else
2380 timer_delete(schedule->handle);
2381 #endif
2382 #endif
2383
2384 oldSchedules.push_back(schedule);
2385 mutex.leave();
2386 return true;
2387}
2388
2389bool Timer::triggerTimer(uint32 id) {
2390 mutex.enter();
2391 TimerSchedule* schedule = schedules[id];
2392 if (!schedule) {
2393 mutex.leave();
2394 return false;
2395 }
2396
2397 TimerTrigger* trigger = new TimerTrigger;
2398 trigger->id = schedule->id;
2399 trigger->time = GetTimeNow();
2400
2401 triggers.push(trigger);
2402 semaphore.signal();
2403
2404 if ( schedule->end && ((int32)(schedule->end - trigger->time) < (int32)schedule->interval))
2405 removeTimer(schedule->id);
2406
2407 mutex.leave();
2408 return true;
2409}
2410
2411bool Timer::waitForTimer(uint32 timeout, uint32& id, uint64& time) {
2412 TimerTrigger* trigger;
2413 uint64 start = GetTimeNow();
2414 int64 timeleft;
2415
2416 mutex.enter();
2417 while (!triggers.size()) {
2418 mutex.leave();
2419 if ( (timeleft = (int32)timeout - GetTimeAgeMS(start)) <= 0)
2420 return false;
2421 semaphore.wait((uint32)timeleft);
2422 mutex.enter();
2423 }
2424
2425 trigger = triggers.front();
2426 triggers.pop();
2427 id = trigger->id;
2428 time = trigger->time;
2429 delete(trigger);
2430 mutex.leave();
2431 return true;
2432}
2433
2434#ifdef WINDOWS
2435 void CALLBACK TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired) {
2436 if (!Timer::timers)
2437 return;
2438 TimerSchedule* schedule = (TimerSchedule*)arg;
2439 if (!schedule)
2440 return;
2441 Timer* timer = (*Timer::timers)[schedule->globalID];
2442 if (timer)
2443 timer->triggerTimer(schedule->id);
2444 }
2445#else
2446 #ifndef __APPLE__
2447 void TimerCallback(int sig, siginfo_t *siginfo, void *context) {
2448 if (!Timer::timers)
2449 return;
2450 TimerSchedule* schedule = (TimerSchedule*) siginfo->si_value.sival_ptr;
2451 if (!schedule)
2452 return;
2453 Timer* timer = (*Timer::timers)[schedule->globalID];
2454 if (timer)
2455 timer->triggerTimer(schedule->id);
2456 }
2457 #endif
2458#endif
2459
2461 unittest::progress(5, "create timer");
2462 uint32 id;
2463 uint64 time, now = GetTimeNow();
2464
2465 Timer* timer = new Timer();
2466 if (!timer) {
2467 unittest::fail("Timer test: failed to create Timer");
2468 return false;
2469 }
2470
2471 unittest::progress(20, "schedule timers");
2472 if (!timer->addTimer(1, 1000, now+50000, now+10000000)) {
2473 unittest::fail("Timer test: addTimer 1 failed");
2474 delete(timer);
2475 return false;
2476 }
2477 if (!timer->addTimer(2, 2000, now+55000, now+15000000)) {
2478 unittest::fail("Timer test: addTimer 2 failed");
2479 delete(timer);
2480 return false;
2481 }
2482 if (!timer->addTimer(3, 3000, now+60000, now+20000000)) {
2483 unittest::fail("Timer test: addTimer 3 failed");
2484 delete(timer);
2485 return false;
2486 }
2487
2488 unittest::progress(40, "wait for triggers");
2489 uint32 triggers = 0;
2490 double totalLatencyUs = 0;
2491 uint64 t0 = GetTimeNow();
2492 // Bounded loop: timers fire every 1-3ms after ~50ms, so this returns quickly.
2493 // Stop once we have collected a stable sample or the wall-clock budget elapses.
2494 for (uint32 n = 0; n < 60; n++) {
2495 if (timer->waitForTimer(100, id, time)) {
2496 now = GetTimeNow();
2497 triggers++;
2498 totalLatencyUs += (double)(now - time);
2499 unittest::detail("Timer %u triggered %.3f ms ago", id, (now - time) / 1000.0);
2500 }
2501 else {
2502 unittest::detail("(Timeout)");
2503 }
2504 // Keep the test well under a second of wall time.
2505 if ((GetTimeNow() - t0) > 2000000ULL)
2506 break;
2507 }
2508
2509 unittest::progress(85, "verify triggers");
2510 if (triggers == 0) {
2511 unittest::fail("Timer test: no timer triggers received");
2512 delete(timer);
2513 return false;
2514 }
2515
2516 unittest::metric("timer_triggers", (double)triggers, "count", true);
2517 unittest::metric("avg_trigger_latency", totalLatencyUs / (double)triggers, "us", false);
2518
2519 delete(timer);
2520 unittest::progress(100, "done");
2521 return true;
2522}
2523
2524// utils_probe_wait (2.7b-i): ProbeProcessWait detects a child blocked reading stdin
2525// and reports growing CPU time for a busy child. POSIX only; trivially passes on
2526// Windows (Windows probe is a stub until 2.7c).
2528#if defined(WINDOWS)
2529 unittest::progress(100, "Windows stub (full detection in 2.7c)");
2530 return true;
2531#else
2532 unittest::progress(10, "spawn stdin-blocked child: sh -c 'read x' on a pipe");
2533 int inPipe[2];
2534 if (pipe(inPipe) != 0) { unittest::fail("pipe() failed"); return false; }
2535 pid_t child = fork();
2536 if (child < 0) { unittest::fail("fork() failed"); close(inPipe[0]); close(inPipe[1]); return false; }
2537 if (child == 0) {
2538 dup2(inPipe[0], STDIN_FILENO);
2539 close(inPipe[0]); close(inPipe[1]);
2540 execl("/bin/sh", "sh", "-c", "read x", (char*)NULL);
2541 _exit(127);
2542 }
2543 close(inPipe[0]); // keep write end open so the child's read(0) blocks
2544 uint32 pid = (uint32)child;
2545 ProcessWaitInfo info; info.alive = false; info.waitingStdin = false; info.waitExact = false; info.cpuTimeMs = 0;
2546 bool detected = false;
2547 for (int i = 0; i < 40 && !detected; i++) { // up to 2s
2548 if (!ProbeProcessWait(pid, info)) { unittest::fail("ProbeProcessWait returned false"); kill(child, SIGKILL); close(inPipe[1]); waitpid(child, NULL, 0); return false; }
2549 if (info.alive && info.waitingStdin) detected = true;
2550 else Sleep(50);
2551 }
2552 if (!detected) {
2553 unittest::fail("stdin-blocked child not detected (alive=%d waitingStdin=%d waitExact=%d)",
2554 (int)info.alive, (int)info.waitingStdin, (int)info.waitExact);
2555 kill(child, SIGKILL); close(inPipe[1]); waitpid(child, NULL, 0); return false;
2556 }
2557#if defined(__linux__)
2558 if (!info.waitExact) { unittest::fail("Linux should report waitExact"); kill(child, SIGKILL); close(inPipe[1]); waitpid(child, NULL, 0); return false; }
2559#endif
2560 kill(child, SIGKILL);
2561 close(inPipe[1]);
2562 waitpid(child, NULL, 0);
2563 int rc;
2564 unittest::progress(55, "spawn CPU-busy child, expect no stdin-wait + growing cpuTimeMs");
2565 uint32 pid2 = NewProcessEx("i=0; while [ $i -lt 100000000 ]; do i=$((i+1)); done",
2566 NULL, NULL, NULL, true, false, true, SIGKILL, true);
2567 if (!pid2) { unittest::fail("NewProcessEx(busy loop) failed"); return false; }
2568 Sleep(200);
2569 ProcessWaitInfo a, b;
2570 if (!ProbeProcessWait(pid2, a) || !a.alive) { unittest::fail("busy child probe 1 failed"); EndProcess(pid2); return false; }
2571 Sleep(400);
2572 if (!ProbeProcessWait(pid2, b) || !b.alive) { unittest::fail("busy child probe 2 failed"); EndProcess(pid2); return false; }
2573 bool busyFlagged = a.waitingStdin || b.waitingStdin;
2574 EndProcess(pid2);
2575 WaitForProcess(pid2, 2000, rc);
2576 if (busyFlagged) { unittest::fail("busy child wrongly flagged waitingStdin"); return false; }
2577 if (b.cpuTimeMs <= a.cpuTimeMs) { unittest::fail("cpuTimeMs did not grow (%llu -> %llu)",
2578 (unsigned long long)a.cpuTimeMs, (unsigned long long)b.cpuTimeMs); return false; }
2579 unittest::detail("cpu delta %llu ms over 400 ms window", (unsigned long long)(b.cpuTimeMs - a.cpuTimeMs));
2580 return true;
2581#endif
2582}
2583
2584// utils_child_sigmask (17 Nov 2026): a child launched while the launcher has the shutdown signals blocked (Psyclone
2585// blocks them at the top of main, BlockShutdownSignals) must still stop on SIGTERM. The mask survives fork+exec, so
2586// without ResetChildSignalMask() every <executable> ignored ExternalExec's graceful stop and was SIGKILLed later.
2587// Both launch paths: inline fork, and the persistent launcher thread used for die-with-parent children.
2589#if defined(WINDOWS)
2590 unittest::progress(100, "POSIX only");
2591 return true;
2592#else
2593 sigset_t before;
2594 pthread_sigmask(SIG_SETMASK, NULL, &before);
2596 bool ok = true;
2597 const char* paths[] = { "inline fork", "die-with-parent launcher", NULL };
2598 for (int m = 0; paths[m] && ok; m++) {
2599 unittest::progress(10 + m * 45, utils::StringFormat("SIGTERM reaches a child launched via the %s", paths[m]).c_str());
2600 uint32 pid = NewProcessEx("sleep 30", NULL, NULL, NULL, false, true, true, m ? SIGKILL : 0, false);
2601 if (!pid) { unittest::fail("NewProcessEx(sleep 30) failed (%s)", paths[m]); ok = false; break; }
2602 Sleep(200);
2603 kill((pid_t)pid, SIGTERM);
2604 int rc = 0;
2605 if (WaitForProcess(pid, 2000, rc) != PROC_TERMINATED) {
2606 unittest::fail("child launched via the %s ignored SIGTERM (it inherited the launcher's blocked signal mask)", paths[m]);
2607 kill((pid_t)pid, SIGKILL);
2608 WaitForProcess(pid, 2000, rc);
2609 ok = false;
2610 }
2611 }
2612 pthread_sigmask(SIG_SETMASK, &before, NULL);
2613 return ok;
2614#endif
2615}
2616
2617// utils_mutex_ownerdeath (17 Nov 2026): a named mutex whose owner died holding it must not block everyone else for
2618// ever. A crashed external component holding PsycloneProcessMemoryMutex_<port> stalled the whole node
2619// (psy_extexec_limit on macOS, about one run in two). Cases: the owner process is gone (and reaped) before we ask; it
2620// dies while we wait; it has exited but is not reaped yet (a zombie - kill(pid, 0) still succeeds for those); and
2621// (not with the macOS pid scheme, which tracks processes) a thread that ends holding it.
2622// v1 deleted the child's handle after each case. On POSIX, closing a named segment unlinks its name (see
2623// CloseSharedMemorySegment), so the next case's child created a NEW mutex of the same name and the parent never
2624// waited at all ("while we wait: got the mutex after 0 ms", Isaac on macOS; the same on Linux). Now one child handle
2625// serves every case, the parent waits from a fresh thread, and "while we wait" must really wait.
2627 bool ok = true;
2628#if !defined(WINDOWS)
2629 std::string name = utils::StringFormat("UTOwnerDeath_%u", (uint32)getpid());
2630 Mutex* m = new Mutex(name.c_str(), true);
2631 Mutex* cm = new Mutex(name.c_str()); // the children's handle, opened before fork (no allocation after it)
2632 const char* cases[] = { "gone before we ask", "dies while we wait", "exited, not reaped yet", NULL };
2633 for (int c = 0; cases[c] && ok; c++) {
2634 const char* what = cases[c];
2635 unittest::progress(10 + c * 20, utils::StringFormat("owner process holding the mutex: %s", what).c_str());
2636 int fds[2];
2637 if (pipe(fds) != 0) { unittest::fail("pipe() failed"); ok = false; break; }
2638 pid_t pid = fork();
2639 if (pid == 0) {
2640 close(fds[0]);
2641 bool got = cm->enter(2000, "ownerdeath child");
2642 char b = got ? 'L' : 'F';
2643 if (write(fds[1], &b, 1) != 1) _exit(2);
2644 if (c == 1) usleep(400000);
2645 _exit(got ? 0 : 1); // ends holding the mutex
2646 }
2647 close(fds[1]);
2648 char b = 0;
2649 if (pid < 0 || read(fds[0], &b, 1) != 1 || b != 'L') {
2650 unittest::fail("child could not take the mutex (%c)", b ? b : '-');
2651 ok = false;
2652 }
2653 close(fds[0]);
2654 int st = 0;
2655 if (ok && c == 0) waitpid(pid, &st, 0);
2656 if (ok && c == 2) usleep(200000); // let it exit; it stays a zombie until the waitpid below
2657 uint64 t0 = GetTimeNow();
2658 bool got = false, again = false;
2659 if (ok) {
2660 std::thread waiter([&]() {
2661 got = m->enter(5000, "ownerdeath parent");
2662 if (got) {
2663 m->leave();
2664 again = m->enter(1000, "ownerdeath again");
2665 if (again) m->leave();
2666 }
2667 });
2668 waiter.join();
2669 }
2670 double tookMS = GetTimeAge(t0) / 1000.0;
2671 if (ok && !got) {
2672 unittest::fail("mutex not available %.0f ms after its owner process ended (%s)", tookMS, what);
2673 ok = false;
2674 }
2675 else if (ok && !again) {
2676 unittest::fail("mutex not usable after recovery (%s)", what);
2677 ok = false;
2678 }
2679 else if (ok && c == 1 && tookMS < 200) {
2680 unittest::fail("got the mutex after %.0f ms while its owner still held it (%s): no mutual exclusion", tookMS, what);
2681 ok = false;
2682 }
2683 else if (ok)
2684 unittest::detail("%s: got the mutex after %.0f ms", what, tookMS);
2685 if (pid > 0 && c != 0) waitpid(pid, &st, 0);
2686 }
2687 delete cm;
2688 delete m;
2689#endif
2690#if !defined(CMSDK_MUTEX_PID_RECOVERY)
2691 if (ok) {
2692 // a thread that ends holding the mutex (Windows: WAIT_ABANDONED; Linux: robust mutex)
2693 unittest::progress(80, "owner thread ends holding the mutex");
2694 std::string tname = utils::StringFormat("UTOwnerDeathT_%u", (uint32)
2695#if defined(WINDOWS)
2696 GetCurrentProcessId()
2697#else
2698 getpid()
2699#endif
2700 );
2701 Mutex* tm = new Mutex(tname.c_str(), true);
2702 Mutex* om = new Mutex(tname.c_str());
2703 std::thread th([om]() { om->enter(2000, "ownerdeath thread"); });
2704 th.join();
2705 uint64 t0 = GetTimeNow();
2706 if (!tm->enter(5000, "ownerdeath after thread")) {
2707 unittest::fail("mutex not available after its owner thread ended (%s)", PrintTimeDifString(GetTimeAge(t0)).c_str());
2708 ok = false;
2709 }
2710 else {
2711 unittest::detail("thread case: got the mutex after %.0f ms", GetTimeAge(t0) / 1000.0);
2712 tm->leave();
2713 }
2714 delete om;
2715 delete tm;
2716 }
2717#endif
2718 unittest::progress(100, "done");
2719 return ok;
2720}
2721
2722// utils_shared_names (18 Nov 2026): a named segment, Mutex, Semaphore or Event that one user closes must stay the
2723// same object for everyone else, and for whoever opens the name next. On POSIX every close (and every Semaphore
2724// delete) used to remove the name, so the next opener made a NEW object: a Mutex that no longer excluded against the
2725// node, a Semaphore or Event nobody signalled. Users here are separate handles in one process (the name is all that
2726// counts), plus a forked child that closes a segment its parent created.
2727static void SharedNamesWait(volatile bool* flag, uint32 ms) {
2728 uint64 t0 = GetTimeNow();
2729 while (!*flag && GetTimeAgeMS(t0) < (int64)ms)
2730 utils::Sleep(5);
2731}
2732
2734 uint32 me =
2735#if defined(WINDOWS)
2736 (uint32)GetCurrentProcessId();
2737#else
2738 (uint32)getpid();
2739#endif
2740 const uint32 MAGIC = 0x5eed1e55;
2741
2742 // 1. segment: another user opens and closes it -> the name still leads to the same memory
2743 unittest::progress(5, "segment: a non-creator's close keeps the name");
2744 std::string sname = utils::StringFormat("UTShNames_seg_%u", me);
2745 char* s = CreateSharedMemorySegment(sname.c_str(), 4096, true);
2746 if (!s) { unittest::fail("could not create segment %s", sname.c_str()); return false; }
2747 *(uint32*)s = MAGIC;
2748 char* b = OpenSharedMemorySegment(sname.c_str(), 4096);
2749 if (!b) { unittest::fail("could not open segment %s", sname.c_str()); CloseSharedMemorySegment(s, 4096); return false; }
2750 CloseSharedMemorySegment(b, 4096);
2751 char* c = OpenSharedMemorySegment(sname.c_str(), 4096);
2752 if (!c || *(uint32*)c != MAGIC) {
2753 unittest::fail("segment name gone after another user closed it (%s)", c ? "different memory" : "open failed");
2754 if (c) CloseSharedMemorySegment(c, 4096);
2755 CloseSharedMemorySegment(s, 4096);
2756 return false;
2757 }
2758 CloseSharedMemorySegment(c, 4096);
2759
2760#if !defined(WINDOWS)
2761 // 2. a forked child of the creator inherits its mappings, not its ownership
2762 unittest::progress(20, "segment: a forked child's close keeps the name");
2763 pid_t pid = fork();
2764 if (pid == 0) {
2765 CloseSharedMemorySegment(s, 4096);
2766 _exit(0);
2767 }
2768 int st = 0;
2769 if (pid > 0) waitpid(pid, &st, 0);
2770 c = OpenSharedMemorySegment(sname.c_str(), 4096);
2771 if (!c || *(uint32*)c != MAGIC) {
2772 unittest::fail("segment name gone after a forked child closed it");
2773 if (c) CloseSharedMemorySegment(c, 4096);
2774 CloseSharedMemorySegment(s, 4096);
2775 return false;
2776 }
2777 CloseSharedMemorySegment(c, 4096);
2778#endif
2779
2780 // 3. the creator's close removes it (Windows: the last handle's close)
2781 unittest::progress(30, "segment: the creator's close removes the name");
2782 CloseSharedMemorySegment(s, 4096);
2783 c = OpenSharedMemorySegment(sname.c_str(), 4096);
2784 if (c) {
2785 unittest::fail("segment name still there after its creator (the last user) closed it");
2786 CloseSharedMemorySegment(c, 4096);
2787 return false;
2788 }
2789
2790 // 4. named Mutex: a second handle opened and deleted; a third handle must still exclude against the first
2791 unittest::progress(45, "mutex: still the same lock after another user deleted its handle");
2792 std::string mname = utils::StringFormat("UTShNames_mx_%u", me);
2793 Mutex* m = new Mutex(mname.c_str(), true);
2794 Mutex* h = new Mutex(mname.c_str());
2795 delete h;
2796 Mutex* h2 = new Mutex(mname.c_str());
2797 bool ok = true;
2798 if (!m->enter(1000, "sharednames")) { unittest::fail("could not take the mutex"); ok = false; }
2799 else {
2800 bool got = true;
2801 std::thread th([&]() { got = h2->enter(300, "sharednames other"); if (got) h2->leave(); });
2802 th.join();
2803 m->leave();
2804 if (got) {
2805 unittest::fail("another handle got the mutex while it was held: the name led to a NEW mutex");
2806 ok = false;
2807 }
2808 else {
2809 std::thread th2([&]() { got = h2->enter(1000, "sharednames other 2"); if (got) h2->leave(); });
2810 th2.join();
2811 if (!got) { unittest::fail("the other handle could not take the mutex once it was free"); ok = false; }
2812 }
2813 }
2814 delete h2;
2815 delete m;
2816 if (!ok) return false;
2817
2818 // 5. named Semaphore: a second object made and deleted; a signal through a third must reach the first
2819 unittest::progress(60, "semaphore: still the same semaphore after another user deleted its object");
2820 std::string semname = utils::StringFormat("UTShNames_sem_%u", me);
2821 Semaphore* sa = new Semaphore(semname.c_str());
2822 Semaphore* sb = new Semaphore(semname.c_str());
2823 delete sb;
2824 Semaphore* sc = new Semaphore(semname.c_str());
2825 for (int i = 0; i < 10 && sa->wait(10); i++) {} // drain the initial count (POSIX starts at 1)
2826 sc->signal();
2827 bool woke = sa->wait(1000);
2828 delete sc;
2829 delete sa;
2830 if (!woke) {
2831 unittest::fail("a signal through a new object did not reach the first: the name led to a NEW semaphore");
2832 return false;
2833 }
2834
2835 // 6. named Event: same, and the deleted object must not have destroyed the shared condition
2836 unittest::progress(75, "event: still the same event after another user deleted its object");
2837 std::string ename = utils::StringFormat("UTShNames_ev_%u", me);
2838 Event* ea = new Event(ename.c_str());
2839 Event* eb = new Event(ename.c_str());
2840 delete eb;
2841 Event* ec = new Event(ename.c_str());
2842 volatile bool waiting = false;
2843 bool signalled = false;
2844 std::thread tw([&]() { waiting = true; signalled = ea->waitNext(2000); });
2845 SharedNamesWait(&waiting, 1000);
2846 utils::Sleep(100);
2847 ec->signal();
2848 tw.join();
2849 delete ec;
2850 delete ea;
2851 if (!signalled) {
2852 unittest::fail("a signal through a new object did not reach the first: the name led to a NEW event");
2853 return false;
2854 }
2855
2856#if !defined(WINDOWS) && !defined(UT_SHAREDNAMES_OLD)
2857 // 7. disown (a node-owned segment made by any process) and unlink (a superseded segment)
2858 unittest::progress(90, "segment: disown keeps the name past its creator, unlink removes it");
2859 std::string dname = utils::StringFormat("UTShNames_dis_%u", me);
2860 s = CreateSharedMemorySegment(dname.c_str(), 4096, true);
2861 if (!s) { unittest::fail("could not create segment %s", dname.c_str()); return false; }
2862 *(uint32*)s = MAGIC;
2864 CloseSharedMemorySegment(s, 4096);
2865 c = OpenSharedMemorySegment(dname.c_str(), 4096);
2866 if (!c || *(uint32*)c != MAGIC) {
2867 unittest::fail("a disowned segment's name went with its creator's close");
2868 if (c) CloseSharedMemorySegment(c, 4096);
2869 return false;
2870 }
2872 char* d = OpenSharedMemorySegment(dname.c_str(), 4096);
2873 if (d) {
2874 unittest::fail("segment name still there after UnlinkSharedMemorySegment");
2875 CloseSharedMemorySegment(d, 4096);
2876 CloseSharedMemorySegment(c, 4096);
2877 return false;
2878 }
2879 if (*(uint32*)c != MAGIC) { unittest::fail("an unlinked segment's mapping changed"); CloseSharedMemorySegment(c, 4096); return false; }
2880 CloseSharedMemorySegment(c, 4096);
2881#endif
2882 unittest::progress(100, "done");
2883 return true;
2884}
2885
2886// utils_semaphore_userdeath (18 Nov 2026): a process killed while inside a named Semaphore's wait() or signal() must
2887// not wedge it for everyone else. On macOS the named Semaphore was a pthread mutex + condition + count in a shared
2888// segment; a user killed while holding that mutex left it locked for ever, and the node's next signal() (made while
2889// holding PsycloneProcessMemoryMutex) never returned (Isaac, macOS psy_extexec_limit). A child hammers signal/wait
2890// and is SIGKILLed at a random moment; then the parent must still signal and take the semaphore within a bound.
2892#if defined(WINDOWS)
2893 unittest::progress(100, "Windows semaphores are kernel objects: nothing to wedge");
2894 return true;
2895#else
2896 std::string name = utils::StringFormat("UTSemDeath_%u", (uint32)getpid());
2897 Semaphore* s = new Semaphore(name.c_str()); // the child uses this object too (forked: same mapping/handle)
2898 srand((unsigned)GetTimeNow());
2899 const int ITER = 40;
2900 for (int i = 0; i < ITER; i++) {
2901 if (i % 5 == 0)
2902 unittest::progress(5 + (i * 90) / ITER, utils::StringFormat("kill %d of %d", i + 1, ITER).c_str());
2903 pid_t pid = fork();
2904 if (pid == 0) {
2905 for (;;) { s->signal(); s->wait(1); }
2906 }
2907 if (pid < 0) { unittest::fail("fork failed"); delete s; return false; }
2908 usleep(2000 + rand() % 8000);
2909 kill(pid, SIGKILL);
2910 int st = 0;
2911 waitpid(pid, &st, 0);
2912 std::atomic<int> state(0); // 1 = signalled, 2 = took one
2913 std::thread th([s, &state]() {
2914 s->signal();
2915 state = 1;
2916 bool got = s->wait(500);
2917 for (int k = 0; k < 64 && s->wait(0); k++) {} // drain what the child left
2918 state = got ? 2 : 3;
2919 });
2920 th.detach(); // if it wedges, it must not wedge the test runner too
2921 uint64 t0 = GetTimeNow();
2922 while (state < 2 && GetTimeAgeMS(t0) < 3000)
2923 utils::Sleep(5);
2924 if (state < 2) {
2925 unittest::fail("named semaphore wedged after a user process died inside it (kill %d: %s after 3 s)", i + 1,
2926 state == 0 ? "signal() never returned" : "wait() never returned");
2927 return false; // s deliberately not deleted: the detached thread may still use it
2928 }
2929 if (state == 3) {
2930 unittest::fail("named semaphore lost a signal after a user process died inside it (kill %d)", i + 1);
2931 delete s;
2932 return false;
2933 }
2934 }
2935 delete s;
2936 unittest::progress(100, "done");
2937 return true;
2938#endif
2939}
2940
2941// utils_event_userdeath (18 Nov 2026): a process killed while inside a named Event's waitNext() or signal() must not
2942// wedge it for everyone else. On Linux and macOS the named Event was a pthread mutex + condition in a shared segment
2943// (not robust): a user killed while holding that mutex left it locked for ever, and one killed while waiting could
2944// leave the condition waiting for it. A child hammers signal/waitNext and is SIGKILLed at a random moment; then a
2945// waiter in the parent must still be woken by a signal within a bound.
2947#if defined(WINDOWS)
2948 unittest::progress(100, "Windows events are kernel objects: nothing to wedge");
2949 return true;
2950#else
2951 std::string name = utils::StringFormat("UTEvDeath_%u", (uint32)getpid());
2952 Event* e = new Event(name.c_str()); // the child uses this object too (forked: same mapping)
2953 {
2954 // meaning first: one signal wakes every waiter (here through other handles), and is not kept for later
2955 unittest::progress(2, "one signal wakes all waiters; a signal with no waiter is not kept");
2956 Event* e1 = new Event(name.c_str());
2957 Event* e2 = new Event(name.c_str());
2958 std::atomic<int> w1(0), w2(0), up(0);
2959 std::thread t1([&]() { up++; w1 = e1->waitNext(2000) ? 1 : 2; });
2960 std::thread t2([&]() { up++; w2 = e2->waitNext(2000) ? 1 : 2; });
2961 while (up < 2) utils::Sleep(1);
2962 utils::Sleep(100);
2963 e->signal();
2964 t1.join(); t2.join();
2965 bool kept = e1->waitNext(100);
2966 delete e2; delete e1;
2967 if (w1 != 1 || w2 != 1) { unittest::fail("one signal did not wake both waiters (%d %d)", (int)w1, (int)w2); delete e; return false; }
2968 if (kept) { unittest::fail("a signal with no waiter was kept for a later waitNext()"); delete e; return false; }
2969 }
2970 srand((unsigned)GetTimeNow());
2971 const int ITER = 40;
2972 for (int i = 0; i < ITER; i++) {
2973 if (i % 5 == 0)
2974 unittest::progress(5 + (i * 90) / ITER, utils::StringFormat("kill %d of %d", i + 1, ITER).c_str());
2975 pid_t pid = fork();
2976 if (pid == 0) {
2977 for (;;) { e->signal(); e->waitNext(1); }
2978 }
2979 if (pid < 0) { unittest::fail("fork failed"); delete e; return false; }
2980 usleep(2000 + rand() % 8000);
2981 kill(pid, SIGKILL);
2982 int st = 0;
2983 waitpid(pid, &st, 0);
2984 std::atomic<int> woke(0); // 1 = woken by a signal, 2 = timed out
2985 std::thread tw([e, &woke]() { woke = e->waitNext(2000) ? 1 : 2; });
2986 tw.detach(); // if it wedges, it must not wedge the test runner too
2987 std::atomic<bool> signalled(false);
2988 std::thread ts([e, &woke, &signalled]() {
2989 utils::Sleep(20);
2990 while (!woke) { e->signal(); signalled = true; utils::Sleep(20); }
2991 });
2992 ts.detach();
2993 uint64 t0 = GetTimeNow();
2994 while (!woke && GetTimeAgeMS(t0) < 3000)
2995 utils::Sleep(5);
2996 if (woke != 1) {
2997 unittest::fail("named event wedged after a user process died inside it (kill %d: %s)", i + 1,
2998 !woke ? (signalled ? "waitNext() never returned" : "signal() never returned") : "a waiter was not woken by signals");
2999 return false; // e deliberately not deleted: the detached threads may still use it
3000 }
3001 uint64 t1 = GetTimeNow();
3002 while (!signalled && GetTimeAgeMS(t1) < 1000) // let the signaller see woke and stop
3003 utils::Sleep(5);
3004 utils::Sleep(40);
3005 }
3006 delete e;
3007 unittest::progress(100, "done");
3008 return true;
3009#endif
3010}
3011
3013 unittest::progress(5, "allocate bitfield");
3014
3015 uint32 slotCount = 350;
3016 uint32 bitFieldSize = Calc32BitFieldSize(slotCount);
3017 char* bitField = new char[bitFieldSize];
3018 uint32 loc;
3019
3020 // First set the full new bitfield to unoccupied
3021 Reset32BitField(bitField, bitFieldSize);
3022 unittest::detail("%s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3023
3024 unittest::progress(15, "empty bitfield queries");
3025 if (GetLastOccupiedBitLoc(bitField, bitFieldSize, loc)) {
3026 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: false", loc);
3027 delete[] bitField;
3028 return false;
3029 }
3030
3031 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 0)) {
3032 unittest::fail("GetFirstFreeBitLoc failed: %u, expected: 0", loc);
3033 delete[] bitField;
3034 return false;
3035 }
3036 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 0)) {
3037 unittest::fail("GetFirstFreeBitLocN failed: %u, expected: 0", loc);
3038 delete[] bitField;
3039 return false;
3040 }
3041
3042 unittest::progress(30, "single SetBit");
3043 if (!SetBit(10, BITOCCUPIED, bitField, bitFieldSize)) {
3044 unittest::fail("SetBit failed");
3045 delete[] bitField;
3046 return false;
3047 }
3048 unittest::detail("Bitfield: %s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3049
3050 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 0)) {
3051 unittest::fail("GetFirstFreeBitLoc 2 failed: %u, expected: 0", loc);
3052 delete[] bitField;
3053 return false;
3054 }
3055 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 0)) {
3056 unittest::fail("GetFirstFreeBitLocN 2 failed: %u, expected: 0", loc);
3057 delete[] bitField;
3058 return false;
3059 }
3060
3061 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 11, loc) || (loc != 11)) {
3062 unittest::detail("Bitfield: %s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3063 unittest::fail("GetFirstFreeBitLocN 3 failed: %u, expected: 11", loc);
3064 delete[] bitField;
3065 return false;
3066 }
3067 if (!GetLastOccupiedBitLoc(bitField, bitFieldSize, loc) || (loc != 10)) {
3068 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: 10", loc);
3069 delete[] bitField;
3070 return false;
3071 }
3072
3073 unittest::progress(50, "SetBitN occupied ranges");
3074 if (!SetBit(0, BITOCCUPIED, bitField, bitFieldSize)) {
3075 unittest::fail("SetBit 2 failed");
3076 delete[] bitField;
3077 return false;
3078 }
3079 if (!SetBitN(100, 50, BITOCCUPIED, bitField, bitFieldSize)) {
3080 unittest::fail("SetBitN 100 failed");
3081 delete[] bitField;
3082 return false;
3083 }
3084 unittest::detail("%s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3085
3086 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 1)) {
3087 unittest::fail("GetFirstFreeBitLoc 4 failed: %u, expected: 1", loc);
3088 delete[] bitField;
3089 return false;
3090 }
3091 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 11)) {
3092 unittest::fail("GetFirstFreeBitLocN 5 failed: %u, expected: 11", loc);
3093 delete[] bitField;
3094 return false;
3095 }
3096 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 11, loc) || (loc != 11)) {
3097 unittest::fail("GetFirstFreeBitLocN 6 failed: %u, expected: 11", loc);
3098 delete[] bitField;
3099 return false;
3100 }
3101 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 100, loc) || (loc != 150)) {
3102 unittest::fail("GetFirstFreeBitLocN 7 failed: %u, expected: 150", loc);
3103 delete[] bitField;
3104 return false;
3105 }
3106 if (!GetLastOccupiedBitLoc(bitField, bitFieldSize, loc) || (loc != 149)) {
3107 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: 149", loc);
3108 delete[] bitField;
3109 return false;
3110 }
3111
3112 if (!SetBitN(200, 50, BITOCCUPIED, bitField, bitFieldSize)) {
3113 unittest::fail("SetBitN 200 failed");
3114 delete[] bitField;
3115 return false;
3116 }
3117 unittest::detail("%s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3118
3119 unittest::progress(70, "free-loc searches");
3120 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 1)) {
3121 unittest::fail("GetFirstFreeBitLoc 8 failed: %u, expected: 1", loc);
3122 delete[] bitField;
3123 return false;
3124 }
3125 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 11)) {
3126 unittest::fail("GetFirstFreeBitLocN 9 failed: %u, expected: 11", loc);
3127 delete[] bitField;
3128 return false;
3129 }
3130 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 11, loc) || (loc != 11)) {
3131 unittest::fail("GetFirstFreeBitLocN 10 failed: %u, expected: 11", loc);
3132 delete[] bitField;
3133 return false;
3134 }
3135 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 100, loc) || (loc != 250)) {
3136 unittest::fail("GetFirstFreeBitLocN 11 failed: %u, expected: 250", loc);
3137 delete[] bitField;
3138 return false;
3139 }
3140 if (GetFirstFreeBitLocN(bitField, bitFieldSize, 200, loc)) {
3141 unittest::fail("GetFirstFreeBitLocN 12 failed: %u, expected: false", loc);
3142 delete[] bitField;
3143 return false;
3144 }
3145
3146 if (!GetLastOccupiedBitLoc(bitField, bitFieldSize, loc) || (loc != 249)) {
3147 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3148 delete[] bitField;
3149 return false;
3150 }
3151
3152 unittest::progress(85, "clear range and re-search");
3153 if (!SetBitN(210, 30, BITFREE, bitField, bitFieldSize)) {
3154 unittest::fail("SetBitN 210 failed");
3155 delete[] bitField;
3156 return false;
3157 }
3158 unittest::detail("%s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3159
3160 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 1)) {
3161 unittest::fail("GetFirstFreeBitLoc 13 failed: %u, expected: 1", loc);
3162 delete[] bitField;
3163 return false;
3164 }
3165 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 11)) {
3166 unittest::fail("GetFirstFreeBitLocN 14 failed: %u, expected: 11", loc);
3167 delete[] bitField;
3168 return false;
3169 }
3170 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 11, loc) || (loc != 11)) {
3171 unittest::fail("GetFirstFreeBitLocN 15 failed: %u, expected: 11", loc);
3172 delete[] bitField;
3173 return false;
3174 }
3175 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 52, loc) || (loc != 11)) {
3176 unittest::fail("GetFirstFreeBitLocN 16 failed: %u, expected: 11", loc);
3177 delete[] bitField;
3178 return false;
3179 }
3180 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 100, loc) || (loc != 250)) {
3181 unittest::fail("GetFirstFreeBitLocN 17 failed: %u, expected: 250", loc);
3182 delete[] bitField;
3183 return false;
3184 }
3185 if (!GetLastOccupiedBitLoc(bitField, bitFieldSize, loc) || (loc != 249)) {
3186 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3187 delete[] bitField;
3188 return false;
3189 }
3190
3191 if (!SetBitN(50, 30, BITOCCUPIED, bitField, bitFieldSize)) {
3192 unittest::fail("SetBitN 50 failed");
3193 delete[] bitField;
3194 return false;
3195 }
3196 unittest::detail("%s", PrintBitFieldString(bitField, bitFieldSize, slotCount, "").c_str());
3197
3198 if (!GetFirstFreeBitLoc(bitField, bitFieldSize, loc) || (loc != 1)) {
3199 unittest::fail("GetFirstFreeBitLoc 18 failed: %u, expected: 1", loc);
3200 delete[] bitField;
3201 return false;
3202 }
3203 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 10, loc) || (loc != 11)) {
3204 unittest::fail("GetFirstFreeBitLocN 19 failed: %u, expected: 11", loc);
3205 delete[] bitField;
3206 return false;
3207 }
3208 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 11, loc) || (loc != 11)) {
3209 unittest::fail("GetFirstFreeBitLocN 20 failed: %u, expected: 11", loc);
3210 delete[] bitField;
3211 return false;
3212 }
3213 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 52, loc) || (loc != 250)) {
3214 unittest::fail("GetFirstFreeBitLocN 21 failed: %u, expected: 250", loc);
3215 delete[] bitField;
3216 return false;
3217 }
3218 if (!GetFirstFreeBitLocN(bitField, bitFieldSize, 100, loc) || (loc != 250)) {
3219 unittest::fail("GetFirstFreeBitLocN 22 failed: %u, expected: 250", loc);
3220 delete[] bitField;
3221 return false;
3222 }
3223 if (GetFirstFreeBitLocN(bitField, bitFieldSize, 200, loc)) {
3224 unittest::fail("GetFirstFreeBitLocN 23 failed: %u, expected: false", loc);
3225 delete[] bitField;
3226 return false;
3227 }
3228 if (!GetLastOccupiedBitLoc(bitField, bitFieldSize, loc) || (loc != 249)) {
3229 unittest::fail("GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3230 delete[] bitField;
3231 return false;
3232 }
3233
3234 delete[] bitField;
3235 unittest::progress(100, "done");
3236 return true;
3237}
3238
3239
3240
3241
3242
3243
3244
3245
3246// Create named shared memory segment
3247char* CreateSharedMemorySegment(const char* name, uint64 size, bool force) {
3248
3249 char* memname = new char[MAXSHMEMNAMELEN];
3250 #ifdef WINDOWS
3251 //sprintf(memname, "Global\\Shmem_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
3252 snprintf(memname, MAXSHMEMNAMELEN, "%s\\Shmem_%s", WINSHMEMSPACE, name);
3253 HANDLE hMapFile;
3254 char* pBuf;
3255
3256 hMapFile = CreateFileMapping(
3257 INVALID_HANDLE_VALUE, // use paging file
3258 NULL, // default security
3259 PAGE_READWRITE, // read/write access
3260 (uint32)((size >> 32) & 0xffffffff), // maximum object size (high-order DWORD)
3261 (uint32)(size & 0xffffffff), // maximum object size (low-order DWORD)
3262 memname); // name of mapping object
3263
3264 // Capture immediately: CreateFileMapping succeeds for an already-existing
3265 // named mapping and sets ERROR_ALREADY_EXISTS. On Windows a named mapping
3266 // lives until the last handle closes, so a segment left behind by a prior
3267 // in-process user (e.g. a previous unit test reusing system id 0) is handed
3268 // back with its OLD contents rather than fresh zeroed memory. Unlike the
3269 // POSIX/macOS branches - which honour `force` by unlinking and recreating -
3270 // this branch previously ignored `force`, so a forced create silently
3271 // reused stale state. Record whether it pre-existed so we can re-init below.
3272 bool alreadyExisted = (GetLastError() == ERROR_ALREADY_EXISTS);
3273
3274 if (hMapFile == NULL) {
3275 LogPrint(0,LOG_SYSTEM,0, "Could not create shared memory '%s': %s", memname, GetLastOSErrorMessage().c_str());
3276 delete [] memname;
3277 return NULL;
3278 }
3279 delete [] memname;
3280 pBuf = (char*) MapViewOfFile(hMapFile, // handle to map object
3281 FILE_MAP_ALL_ACCESS, // read/write permission
3282 0, 0, 0); // from beginning to end
3283
3284 if (pBuf == NULL) {
3285 int error = GetLastError();
3286 CloseHandle(hMapFile);
3287 return NULL;
3288 }
3289
3290 // When the caller asked for a fresh segment (force) but Windows returned an
3291 // existing named mapping, zero the view so the caller gets clean memory -
3292 // matching the force semantics on POSIX/macOS. Without this, a forced
3293 // create over a leaked segment inherits stale occupancy/state, which is
3294 // exactly what made the CMSDK ProcessMemory tests fail on every other run.
3295 if (force && alreadyExisted)
3296 memset(pBuf, 0, (size_t)size);
3297
3300 // Save the handle so we can close it later
3301 (*SharedMemoryFileHandleMap)[pBuf] = hMapFile;
3302
3303 return pBuf;
3304 #else
3305 #ifdef __APPLE__
3306 /* macOS: use file-based shared memory (shm_open is unreliable, errno 63) */
3307 snprintf(memname, MAXSHMEMNAMELEN, "/tmp/Psyclone_Shmem_%s", name);
3308 if (force)
3309 unlink(memname);
3310 // O_EXCL first, so we know whether we made the name (only its creator removes it, on close)
3311 bool created = true;
3312 int fd = open(memname, O_CREAT | O_EXCL | O_RDWR, 0666);
3313 if (fd == -1 && errno == EEXIST) {
3314 fd = open(memname, O_CREAT | O_RDWR, 0666);
3315 created = false; // someone made it between our open and create: we joined theirs
3316 }
3317 if (fd == -1) {
3318 LogPrint(0,LOG_SYSTEM,0,"Couldn't create shared memory: '%s' (err: %d)...", memname, errno);
3319 delete [] memname;
3320 return NULL;
3321 }
3322 if (ftruncate(fd, size) == -1) {
3323 LogPrint(0,LOG_SYSTEM,0,"Couldn't truncate shared memory: '%s' size: %u (%d) (err: %d)...", memname, size, fd, errno);
3324 delete [] memname;
3325 close(fd);
3326 return NULL;
3327 }
3328 char* pBuf = (char*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3329 if (pBuf == MAP_FAILED) {
3330 LogPrint(0,LOG_SYSTEM,0,"Couldn't map created shared memory: '%s' (err: %d)...", memname, errno);
3331 delete [] memname;
3332 close(fd);
3333 return NULL;
3334 }
3335 RegisterSharedSegment(pBuf, memname, size, created);
3336 close(fd);
3337 delete [] memname;
3338 return pBuf;
3339 #else
3340 /* Linux: POSIX shm_open */
3341 snprintf(memname, MAXSHMEMNAMELEN, "/Shmem_%s", name);
3342 // A forced create starts a new object, as on macOS: anyone still mapping the old one keeps it, nobody joins it
3343 // any more (it used to join the existing object here, while macOS made a new one; Isaac, 18 Nov 2026).
3344 if (force)
3345 shm_unlink(memname);
3346 // O_EXCL first, so we know whether we made the name (only its creator removes it, on close)
3347 bool created = true;
3348 int fd = shm_open(memname, O_CREAT | O_EXCL | O_RDWR, 0666);
3349 if (fd == -1 && errno == EEXIST) {
3350 fd = shm_open(memname, O_CREAT | O_RDWR, 0666);
3351 created = false; // someone made it between our unlink/open and create: we joined theirs
3352 }
3353 if (fd == -1) {
3354 LogPrint(0,LOG_SYSTEM,0,"Couldn't create shared memory: '%s' (err: %d)...", memname, errno);
3355 delete [] memname;
3356 return NULL;
3357 }
3358 if (ftruncate(fd, size) == -1) {
3359 LogPrint(0,LOG_SYSTEM,0,"Couldn't truncate shared memory: '%s' size: %u (%d) (err: %d)...", memname, size, fd, errno);
3360 delete [] memname;
3361 close(fd);
3362 return NULL;
3363 }
3364 char* pBuf = (char*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3365 if (pBuf == MAP_FAILED) {
3366 LogPrint(0,LOG_SYSTEM,0,"Couldn't map created shared memory: '%s' (err: %d)...", memname, errno);
3367 delete [] memname;
3368 close(fd);
3369 return NULL;
3370 }
3371 RegisterSharedSegment(pBuf, memname, size, created);
3372 close(fd);
3373 delete [] memname;
3374 return pBuf;
3375 #endif
3376 #endif
3377}
3378
3379// Get named shared memory segment, size = 0 means autodetect size
3380char* OpenSharedMemorySegment(const char* name, uint64 size) {
3381
3382 char* memname = new char[MAXSHMEMNAMELEN];
3383 #ifdef WINDOWS
3384 // sprintf(memname, "Global\\Shmem_%s_%u_%s", SharedSystemName, SharedSystemInstance, name);
3385 snprintf(memname, MAXSHMEMNAMELEN, "%s\\Shmem_%s", WINSHMEMSPACE, name);
3386 HANDLE hMapFile;
3387 char* pBuf;
3388
3389 hMapFile = OpenFileMapping(
3390 FILE_MAP_ALL_ACCESS, // read/write access
3391 FALSE, // do not inherit the name
3392 memname); // name of mapping object
3393
3394 if (hMapFile == NULL) {
3395 // LogPrint(0,LOG_SYSTEM,0, "Could not open shared memory '%s': %s", memname, GetLastOSErrorMessage().c_str());
3396 delete [] memname;
3397 return NULL;
3398 }
3399
3400 pBuf = (char*) MapViewOfFile(hMapFile, // handle to map object
3401 FILE_MAP_ALL_ACCESS, // read/write permission
3402 0, 0, 0); // from beginning to end
3403
3404 if (pBuf == NULL) {
3405 LogPrint(0,LOG_SYSTEM,0, "Could not map shared memory '%s': %s", memname, GetLastOSErrorMessage().c_str());
3406 delete [] memname;
3407 GetLastError();
3408 CloseHandle(hMapFile);
3409 return NULL;
3410 }
3411 delete [] memname;
3412
3413 // Save the handle so we can close it later
3416 (*SharedMemoryFileHandleMap)[pBuf] = hMapFile;
3417
3418 return pBuf;
3419 #else
3420 #ifdef __APPLE__
3421 /* macOS: open file-based shared memory */
3422 snprintf(memname, MAXSHMEMNAMELEN, "/tmp/Psyclone_Shmem_%s", name);
3423 int fd = open(memname, O_RDWR);
3424 if (fd == -1) {
3425 delete [] memname;
3426 return NULL;
3427 }
3428 char* pBuf;
3429 uint64 memSize = size;
3430 if (!size) {
3431 /* Autodetect: the segment file was ftruncate'd to its full size at
3432 creation, so the on-disk file size IS the segment size. (Reading a
3433 size prefix from offset 0 is wrong - callers store their own header
3434 there, e.g. RequestServerHeader.) */
3435 struct stat st;
3436 if (fstat(fd, &st) == -1 || st.st_size <= 0) {
3437 delete [] memname;
3438 close(fd);
3439 return NULL;
3440 }
3441 memSize = (uint64) st.st_size;
3442 }
3443 pBuf = (char*)mmap(NULL, memSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3444 if (pBuf == MAP_FAILED) {
3445 delete [] memname;
3446 close(fd);
3447 return NULL;
3448 }
3449 RegisterSharedSegment(pBuf, memname, memSize, false);
3450 close(fd);
3451 delete [] memname;
3452 return pBuf;
3453 #else
3454 /* Linux: POSIX shm_open */
3455 snprintf(memname, MAXSHMEMNAMELEN, "/Shmem_%s", name);
3456 int fd = shm_open(memname, O_RDWR, 0666);
3457 if (fd == -1) {
3458 delete [] memname;
3459 return NULL;
3460 }
3461 char* pBuf;
3462 uint64 memSize = size;
3463 if (!size) {
3464 /* Autodetect from the actual segment size (ftruncate'd at creation),
3465 not from a size prefix at offset 0 - callers store their own header
3466 there. */
3467 struct stat st;
3468 if (fstat(fd, &st) == -1 || st.st_size <= 0) {
3469 LogPrint(0,LOG_SYSTEM,0,"Couldn't stat opened shared memory: '%s' (err: %d)...", memname, errno);
3470 delete [] memname;
3471 close(fd);
3472 return NULL;
3473 }
3474 memSize = (uint64) st.st_size;
3475 }
3476 pBuf = (char*)mmap(NULL, memSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3477 if (pBuf == MAP_FAILED) {
3478 delete [] memname;
3479 close(fd);
3480 return NULL;
3481 }
3482 RegisterSharedSegment(pBuf, memname, memSize, false);
3483 close(fd);
3484 delete [] memname;
3485 return pBuf;
3486 #endif
3487 #endif
3488}
3489
3490// Close named shared memory segment
3491bool CloseSharedMemorySegment(char* data, uint64 size) {
3492 if (!data || !size)
3493 return true;
3494 #ifdef WINDOWS
3495 UnmapViewOfFile(data);
3496 CloseHandle((*SharedMemoryFileHandleMap)[data]);
3497 SharedMemoryFileHandleMap->erase(data);
3498 return true;
3499 #else
3500 // Remove the name only if this process created it (see SharedSegmentInfo): others still use it, and
3501 // whoever opens it next must find the same object.
3502 std::string path;
3503 bool owned = false;
3504 uint64 mapped = size;
3505 pthread_mutex_lock(&SharedSegmentLock);
3506 if (SharedSegments) {
3507 std::map<void*, SharedSegmentInfo>::iterator i = SharedSegments->find(data);
3508 if (i != SharedSegments->end()) {
3509 path = i->second.path;
3510 owned = i->second.creator && (i->second.creator == getpid());
3511 if (i->second.size)
3512 mapped = i->second.size;
3513 SharedSegments->erase(i);
3514 }
3515 }
3516 pthread_mutex_unlock(&SharedSegmentLock);
3517 munmap(data, mapped);
3518 if (owned && path.length()) {
3519 #ifdef __APPLE__
3520 unlink(path.c_str());
3521 #else
3522 shm_unlink(path.c_str());
3523 #endif
3524 }
3525 return true;
3526 #endif
3527}
3528
3530 #ifdef WINDOWS
3531 (void)data;
3532 return true;
3533 #else
3534 bool found = false;
3535 pthread_mutex_lock(&SharedSegmentLock);
3536 if (SharedSegments) {
3537 std::map<void*, SharedSegmentInfo>::iterator i = SharedSegments->find(data);
3538 if (i != SharedSegments->end()) {
3539 i->second.creator = 0;
3540 found = true;
3541 }
3542 }
3543 pthread_mutex_unlock(&SharedSegmentLock);
3544 return found;
3545 #endif
3546}
3547
3549 #ifdef WINDOWS
3550 (void)data;
3551 return true;
3552 #else
3553 std::string path;
3554 pthread_mutex_lock(&SharedSegmentLock);
3555 if (SharedSegments) {
3556 std::map<void*, SharedSegmentInfo>::iterator i = SharedSegments->find(data);
3557 if (i != SharedSegments->end()) {
3558 path = i->second.path;
3559 i->second.creator = 0;
3560 }
3561 }
3562 pthread_mutex_unlock(&SharedSegmentLock);
3563 if (!path.length())
3564 return false;
3565 #ifdef __APPLE__
3566 unlink(path.c_str());
3567 #else
3568 shm_unlink(path.c_str());
3569 #endif
3570 return true;
3571 #endif
3572}
3573
3574// Destroy named shared memory segment
3575//bool DestroySharedMemorySegment(char* data, uint32 size) {
3576// #ifdef WINDOWS
3577// UnmapViewOfFile(data);
3578// CloseHandle(SharedMemoryFileHandleMap[data]);
3579// SharedMemoryFileHandleMap[data] = NULL;
3580// return true;
3581// #else
3582// munmap(data, size);
3583// close(SharedMemoryFileHandleMap[data]);
3584// SharedMemoryFileHandleMap[data] = NULL;
3585// return (shm_unlink(data) == 0);
3586// #endif
3587//}
3588
3589#ifndef WINDOWS
3590// True if 'name' contains the port digits as a delimited token:
3591// preceding char non-digit, following char non-digit or end.
3592// Prevents port 10000 matching 100001 or 10001.
3593static bool ContainsPortToken(const char* name, const char* portstr, size_t plen) {
3594 const char* p = name;
3595 while ((p = strstr(p, portstr)) != NULL) {
3596 bool leftOK = (p == name) || !isdigit((unsigned char)*(p - 1));
3597 char after = *(p + plen);
3598 bool rightOK = (after == '\0') || !isdigit((unsigned char)after);
3599 if (leftOK && rightOK)
3600 return true;
3601 p++;
3602 }
3603 return false;
3604}
3605
3606static uint32 ClearSegmentsIn(const char* dir, const char* prefix, const char* portstr, size_t plen) {
3607 uint32 count = 0;
3608 DIR* d = opendir(dir);
3609 if (!d) return 0;
3610 size_t preflen = strlen(prefix);
3611 struct dirent* e;
3612 while ((e = readdir(d)) != NULL) {
3613 if (strncmp(e->d_name, prefix, preflen) != 0)
3614 continue;
3615 if (!ContainsPortToken(e->d_name, portstr, plen))
3616 continue;
3617 std::string path = std::string(dir) + "/" + e->d_name;
3618 if (unlink(path.c_str()) == 0)
3619 count++;
3620 }
3621 closedir(d);
3622 return count;
3623}
3624#endif
3625
3626// Remove every shared-memory/semaphore name for this port. Windows sections auto-clean: no-op.
3627uint32 RemovePortSharedSegments(uint16 port) {
3628 #ifdef WINDOWS
3629 (void)port;
3630 return 0;
3631 #else
3632 char portstr[8];
3633 snprintf(portstr, sizeof(portstr), "%u", port);
3634 size_t plen = strlen(portstr);
3635 uint32 count = 0;
3636 #ifdef __APPLE__
3637 count += ClearSegmentsIn("/tmp", "Psyclone_Shmem_", portstr, plen);
3638 #else
3639 count += ClearSegmentsIn("/dev/shm", "Shmem_", portstr, plen);
3640 count += ClearSegmentsIn("/dev/shm", "sem.Semaphore_", portstr, plen);
3641 #endif
3642 return count;
3643 #endif
3644}
3645
3646// Remove stale shared-memory/semaphore objects for this port (caller must have
3647// verified no live node on the port).
3648void ClearStaleSharedSegments(uint16 port) {
3649 uint32 count = RemovePortSharedSegments(port);
3650 if (count)
3651 LogPrint(0, LOG_SYSTEM, 1, "Cleared %u stale shared segment(s) for port %u...", count, port);
3652}
3653
3654
3655
3656
3657
3658
3659uint64 ntoh64(const uint64 *input) {
3660 uint64 rval;
3661 uint8 *data = (uint8*)&rval;
3662 data[0] = (uint8)(*input >> 56);
3663 data[1] = (uint8)(*input >> 48);
3664 data[2] = (uint8)(*input >> 40);
3665 data[3] = (uint8)(*input >> 32);
3666 data[4] = (uint8)(*input >> 24);
3667 data[5] = (uint8)(*input >> 16);
3668 data[6] = (uint8)(*input >> 8);
3669 data[7] = (uint8)(*input >> 0);
3670 return rval;
3671}
3672
3673uint64 hton64(const uint64 *input) {
3674 return (ntoh64(input));
3675}
3676
3677
3678
3679
3680uint32 Calc32BitFieldSize(uint32 bitsize) {
3681 return ((bitsize + 31) >> 5) << 2;
3682}
3683
3684bool Reset32BitField(char* bitfield, uint32 bytesize) {
3685 memset(bitfield, 255, bytesize);
3686 return true;
3687}
3688
3689// Get first zero bit in field of size bits, starting from data loc
3690bool GetFirstFreeBitLoc(const char* bitfield, uint32 bytesize, uint32& loc) {
3691 uint32* data = (uint32*)bitfield;
3692 uint32* src = (uint32*)data;
3693 int32 index;
3694
3695 // Bound in WORDS, and check BEFORE dereferencing. The original loop compared
3696 // a word delta (src - data) against a BYTE count and only tested after having
3697 // already read *src, so a fully-occupied field (all-zero words) over-read by
3698 // ~4x the buffer - up to ~384 bytes past a 128-byte bitfield. It only ever
3699 // looked harmless because callers allocate the bitfield with the payload
3700 // (ThreadStats / map entries / bin blocks) immediately behind it, so the wild
3701 // read landed in owned memory and returned a garbage loc that downstream
3702 // range guards happened to reject. In a shared-memory segment whose bitfield
3703 // sits near the tail of the mapping that is a SIGSEGV/SIGBUS instead.
3704 const int32 words = (int32)(bytesize >> 2);
3705 while (src - data < words && *src == 0)
3706 src++;
3707 if (src - data >= words)
3708 return false; // field is fully occupied
3709 #if defined WINDOWS
3710 _BitScanForward((DWORD*)&index, *src);
3711 #elif defined LINUX
3712 index = ffsl(*src) - 1;
3713 #elif defined OSX
3714 index = ffsl(*src) - 1;
3715 #endif
3716
3717 loc = ((uint32)(src-data)*32) + index;
3718 return true;
3719}
3720
3721// Get first block of num zero bit in field of size bits, starting from data loc
3722bool GetFirstFreeBitLocN(const char* bitfield, uint32 bytesize, uint32 num, uint32& loc) {
3723 uint32* data = (uint32*)bitfield;
3724 uint32* src = (uint32*)data;
3725 int32 index;
3726
3727 uint32 l;
3728 bit val;
3729
3730 uint32 foundBlock = 0;
3731 // Bound in WORDS (see GetFirstFreeBitLoc): the original compared a word delta
3732 // against a byte count and tested only after dereferencing.
3733 const int32 words = (int32)(bytesize >> 2);
3734 while (true) {
3735 while (src - data < words && *src == 0)
3736 src++;
3737 if (src - data >= words)
3738 return false; // no free bit left at all
3739 #if defined WINDOWS
3740 _BitScanForward((DWORD*)&index, *src);
3741 #elif defined LINUX
3742 index = ffsl(*src) - 1;
3743 #elif defined OSX
3744 index = ffsl(*src) - 1;
3745 #endif
3746 loc = ((uint32)(src - data) * 32) + index;
3747 l = loc + 1;
3748 foundBlock = 1;
3749 // Check that bit `l` is inside the buffer -- in WORDS, because the read below
3750 // dereferences a whole uint32 at (l >> 5). The old guard tested the BYTE
3751 // containing bit l ((l + 7) >> 3 > bytesize), which passes for any bit in the
3752 // final 1-3 bytes of a bitfield whose size is not a multiple of 4 and then
3753 // reads up to 3 bytes past the end. ASan caught this as a 4-byte
3754 // heap-buffer-overflow READ against a 44-byte bitfield; it is NOT test-only --
3755 // TemporalMemory::addMessage (TemporalMemory.cpp:327,342) calls this on a bin
3756 // bitfield inside a shared-memory segment, laid out header|bitfield|blockdata,
3757 // so the over-read silently mixes message payload into the free-block
3758 // decision, and for the last bin in a mapping it can run off the mapping.
3759 if ((l >> 5) >= (bytesize >> 2))
3760 return false;
3761 {
3762 uint32* word = (uint32*)bitfield + (l >> 5);
3763 uint32 n = l & 31;
3764 #if defined WINDOWS
3765 val = (_bittest((long*)word, n) != 0);
3766 #elif defined LINUX
3767 val = (bit)((*word & (static_cast<uint32>(1) << n)) != 0);
3768 #elif defined OSX
3769 val = (bit)((*word & (static_cast<uint32>(1) << n)) != 0);
3770 #endif
3771 }
3772 while (true) {
3773 l++;
3774 index++;
3775 if (val == BITFREE) {
3776 foundBlock++;
3777 if (foundBlock >= num)
3778 return true;
3779 if (index % 32 == 0) {
3780 // Fast-forward whole free words. This run had NO bound at all: with a
3781 // large `num` and a long tail of all-free words it walked src past
3782 // the end of the bitfield reading MAXVALUINT32 out of whatever
3783 // followed. Bound every step in words.
3784 while ((num - foundBlock > 31) && (src - data < words) && (*src == MAXVALUINT32)) {
3785 foundBlock += 32;
3786 l += 32;
3787 src++;
3788 }
3789 if (src - data >= words)
3790 return false;
3791 if ((num - foundBlock > 15) && (*(uint16*)src == MAXVALUINT16)) {
3792 foundBlock += 16;
3793 l += 16;
3794 index += 16;
3795 if ((num - foundBlock > 7) && (*((unsigned char*)src+2) == 255)) {
3796 foundBlock += 8;
3797 l += 8;
3798 index += 8;
3799 }
3800 }
3801 else if ((num - foundBlock > 7) && (*(unsigned char*)src == 255)) {
3802 foundBlock += 8;
3803 l += 8;
3804 index += 8;
3805 }
3806 }
3807 if (foundBlock >= num)
3808 return true;
3809 }
3810 else {
3811 foundBlock = 0;
3812 loc = l;
3813 // are we on a boundary
3814 if (index % 32 == 0)
3815 break;
3816 }
3817 // Same word-granular bound as the first inline read above: this
3818 // dereferences a full uint32 at (l >> 5), so a byte-granular guard lets it
3819 // read past the end of a bitfield whose size is not a multiple of 4.
3820 if ((l >> 5) >= (bytesize >> 2))
3821 return false;
3822 {
3823 uint32* word = (uint32*)bitfield + (l >> 5);
3824 uint32 n = l & 31;
3825 #if defined WINDOWS
3826 val = (_bittest((long*)word, n) != 0);
3827 #elif defined LINUX
3828 val = (bit)((*word & (static_cast<uint32>(1) << n)) != 0);
3829 #elif defined OSX
3830 val = (bit)((*word & (static_cast<uint32>(1) << n)) != 0);
3831 #endif
3832 }
3833 }
3834 // we are now on a boundary, jump back and use the bitscan search
3835 src += (uint32)(index / 32);
3836 if (src - data >= words)
3837 return false; // walked off the end looking for a big enough block
3838 index = 0;
3839 // if we get here, the block found wasn't big enough, continue
3840 }
3841 return true;
3842}
3843
3844// Set the nth bit to value in field of size bits, starting from data loc
3845bool SetBit(uint32 loc, bit value, char* bitfield, uint32 bytesize) {
3846 if ((loc + 7) >> 3 > bytesize)
3847 return false;
3848 uint32* data = (uint32*)bitfield;
3849 uint32* src = (uint32*)data;
3850 uint32 n = loc;
3851 while (n > 31) {
3852 n -= 32;
3853 src++;
3854 }
3855
3856 #if defined WINDOWS
3857 if (value != 0)
3858 _bittestandset((long*)src, n);
3859 else
3860 _bittestandreset((long*)src, n);
3861 #elif defined LINUX
3862 if (value != 0)
3863 *src |= 1<<n;
3864 else
3865 *src &= ~(1<<n);
3866 //*src &= ((1<<n)^0xFFFFFFFF);
3867 #elif defined OSX
3868 if (value != 0)
3869 *src |= 1<<n;
3870 else
3871 *src &= ~(1<<n);
3872 #endif
3873 return true;
3874}
3875
3876// Set the block of num bits starting with nth bit to value in field of size bits, starting from data loc
3877bool SetBitN(uint32 loc, uint32 num, bit value, char* bitfield, uint32 bytesize) {
3878 if ((loc + 7) >> 3 > bytesize)
3879 return false;
3880 uint32* data = (uint32*)bitfield;
3881 uint32* src = (uint32*)data;
3882 uint32 n = loc;
3883 while (n > 31) {
3884 n -= 32;
3885 src++;
3886 }
3887
3888 for (uint32 i = 0; i < num; i++) {
3889 if (!n) {
3890 while (num - i > 31) {
3891 *src = (value ? MAXVALUINT32 : 0);
3892 i += 32;
3893 src++;
3894 }
3895 if (num - i > 15) {
3896 *(uint16*)src = (value ? MAXVALUINT16 : 0);
3897 i += 16;
3898 n += 16;
3899 if (num - i > 7) {
3900 *((unsigned char*)src + 2) = (value ? 255 : 0);
3901 i += 8;
3902 n += 8;
3903 }
3904 }
3905 else if (num - i > 7) {
3906 *(unsigned char*)src = (value ? 255 : 0);
3907 i += 8;
3908 n += 8;
3909 }
3910 if (i == num)
3911 return true;
3912 }
3913 #if defined WINDOWS
3914 if (value != 0)
3915 _bittestandset((long*)src, n);
3916 else
3917 _bittestandreset((long*)src, n);
3918 #elif defined LINUX
3919 if (value != 0)
3920 *src |= 1 << n;
3921 else
3922 *src &= ~(1 << n);
3923 //*src &= ((1<<n)^0xFFFFFFFF);
3924 #elif defined OSX
3925 if (value != 0)
3926 *src |= 1 << n;
3927 else
3928 *src &= ~(1 << n);
3929 #endif
3930 n++;
3931 if (n > 31) {
3932 n = 0;
3933 src++;
3934 }
3935 }
3936 return true;
3937}
3938
3939// Get the nth bit in field of size bits, starting from data loc
3940bool GetBit(uint32 loc, const char* bitfield, uint32 bytesize, bit& val) {
3941 if ((loc + 7) >> 3 > bytesize)
3942 return false;
3943 uint32* data = (uint32*)bitfield;
3944 uint32* src = (uint32*)data;
3945 uint32 n = loc;
3946 while (n > 31) {
3947 n -= 32;
3948 src++;
3949 }
3950
3951 #if defined WINDOWS
3952 val = (_bittest((long*)src, n) != 0);
3953 #elif defined LINUX
3954 uint32 mask = static_cast<uint32>( 1 << n ) ;
3955 val = (bit)(mask & *src);
3956 #elif defined OSX
3957 uint32 mask = static_cast<uint32>(1 << n);
3958 val = (bit)(mask & *src);
3959 #endif
3960// printf("GetBit returned %u...\n", val);
3961 return true;
3962}
3963
3964// Get location of last bit in use, starting from data loc
3965bool GetLastOccupiedBitLoc(const char* bitfield, uint32 bytesize, uint32& loc) {
3966 uint32* data = (uint32*)bitfield;
3967 uint32* src = (uint32*)(bitfield + bytesize - 4);
3968 int32 index;
3969
3970 loc = 0;
3971 while ((*src == 0xFFFFFFFF)) {
3972 if (src <= data)
3973 return false;
3974 src--;
3975 }
3976
3977 #if defined WINDOWS
3978 _BitScanReverse((DWORD*)&index, ~(*src));
3979 #elif defined LINUX
3980 index = 31 - __builtin_clz(~(*src));
3981 #elif defined OSX
3982 index = 31 - __builtin_clz(~(*src));
3983 #endif
3984 loc = ((uint32)(src - data) * 32) + index;
3985 return true;
3986}
3987
3988
3989// Return string representing the bitfield
3990std::string GetBitFieldAsString(const char* bitfield, uint32 bytesize, uint32 size) {
3991 std::string str;
3992 str.reserve(bytesize * 9);
3993
3994 uint32 i,j,n=0;
3995 for(i = 0; i < bytesize; i++) {
3996 for(j = 0; j < 8; j++) {
3997 if (++n <= size)
3998 str.push_back((bitfield[i] & (1 << j)) ? '_' : '0');
3999 else
4000 str.push_back('*');
4001 }
4002 str.push_back(' ');
4003 };
4004 return str;
4005}
4006
4007
4008// Print string representing the bitfield
4009std::string PrintBitFieldString(const char* bitfield, uint32 bytesize, uint32 size, const char* title) {
4010 std::string str = GetBitFieldAsString(bitfield, bytesize, size);
4011 uint32 strSize = (uint32)str.size();
4012 if (!strSize)
4013 return "";
4014 if (strSize < 73) {
4015 if (title != NULL)
4016 return StringFormat("%s [%u]: %s\n", title, size, str.c_str());
4017 else
4018 return StringFormat("%s\n", str.c_str());
4019 }
4020 else {
4021 std::string str2;
4022 if (title != NULL)
4023 str2 = StringFormat("%s [%u]:\n", title, size);
4024 uint32 loc = 0;
4025 while (loc < strSize-1) {
4026 str2 += str.substr(loc, 36) + "\n";
4027 loc += 36;
4028 }
4029 if (loc < strSize)
4030 str2 += str.substr(loc) + "\n";
4031 return str2;
4032 }
4033}
4034
4035
4036
4037
4038int32 AtomicIncrement32(int32 volatile &v) {
4039 #if defined WINDOWS
4040 return InterlockedIncrement((LONG*)&v);
4041 // #elif defined LINUX
4042 #else
4043 __sync_add_and_fetch(&v, 1);
4044 return v;
4045 #endif
4046};
4047
4048int64 AtomicIncrement64(int64 volatile &v) {
4049 #if defined WINDOWS
4050 return InterlockedIncrement64((LONGLONG*)&v);
4051 // #elif defined LINUX
4052 #else
4053 __sync_add_and_fetch(&v, 1);
4054 return v;
4055 #endif
4056};
4057
4058int32 AtomicDecrement32(int32 volatile &v) {
4059 #if defined WINDOWS
4060 return InterlockedDecrement((LONG*)&v);
4061 // #elif defined LINUX
4062 #else
4063 __sync_add_and_fetch(&v, -1);
4064 return v;
4065 #endif
4066};
4067
4068int64 AtomicDecrement64(int64 volatile &v) {
4069 #if defined WINDOWS
4070 return InterlockedDecrement64((LONGLONG*)&v);
4071 // #elif defined LINUX
4072 #else
4073 __sync_add_and_fetch(&v, -1);
4074 return v;
4075 #endif
4076};
4077
4078bool Sleep(uint32 ms) {
4079 #if defined WINDOWS
4080 // we are actually being passed millisecond, so multiply up
4081 ::Sleep((uint32)ms);
4082 #else
4083 usleep(ms*1000);
4084 #endif
4085 return true;
4086}
4087
4088std::string PrintProgramTrace(uint32 startLine, uint32 endLine) {
4089 std::string tracePrint;
4090 std::list<std::string> trace = GetProgramTrace();
4091
4092 std::list<std::string>::iterator i = trace.begin(), e = trace.end();
4093
4094 uint32 line = 0;
4095 while (i != e) {
4096 if ((++line > startLine) && (!endLine || (line <= endLine)))
4097 tracePrint += " -" + (*i) + "\n";
4098 i++;
4099 }
4100 return tracePrint;
4101}
4102
4103std::list<std::string> GetProgramTrace() {
4104 std::list<std::string> trace;
4105 #ifdef WINDOWS
4106 // this needs Dbghelp.h included and link with Dbghelp.lib
4107 //unsigned int i;
4108 //void * stack[ 100 ];
4109 //unsigned short frames;
4110 //SYMBOL_INFO * symbol;
4111 //HANDLE process;
4112
4113 //process = GetCurrentProcess();
4114
4115 //SymInitialize( process, NULL, TRUE );
4116
4117 //frames = CaptureStackBackTrace( 0, 100, stack, NULL );
4118 //symbol = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );
4119 //symbol->MaxNameLen = 255;
4120 //symbol->SizeOfStruct = sizeof( SYMBOL_INFO );
4121
4122 //for( i = 0; i < frames; i++ ) {
4123 // SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol );
4124 // trace.push_back(StringFormat("%i: %s (0x%0X)", frames - i - 1, symbol->Name, symbol->Address));
4125 //}
4126 //free( symbol );
4127 #else
4128 #ifdef _DEBUG
4129 void *array[200];
4130 size_t size;
4131 char **strings;
4132 size_t i;
4133 size = backtrace(array, 200);
4134 strings = backtrace_symbols(array, size);
4135 for (i = 0; i < size; i++)
4136 trace.push_back(strings[i]);
4137 free (strings);
4138 #endif // _DEBUG
4139 #endif
4140 return trace;
4141}
4142
4143
4144bool CreateThread(THREAD_FUNCTION func, void* args, ThreadHandle& thread, uint32 &osID) {
4145
4146 #if defined WINDOWS
4147 DWORD dwThreadId;
4148 thread = ::CreateThread(
4149 NULL, // no security attributes
4150 0, // use default stack size
4151 (LPTHREAD_START_ROUTINE) func, // thread function
4152 args, // argument to thread function
4153 0, // use default creation flags
4154 &dwThreadId); // returns the thread identifier
4155
4156 if (thread != NULL) {
4157 osID = ::GetThreadId(thread);
4158 Sleep(0);
4159 return true;
4160 }
4161 else
4162 return false;
4163 #else
4164 pthread_attr_t attr;
4165 pthread_attr_init(&attr); /* initialize attr with default attributes */
4166 // pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
4167 pthread_attr_setschedpolicy(&attr, SCHED_RR);
4168 pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
4169 // pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
4170
4171 int res;
4172 if ((res=pthread_create(&thread, &attr, func, args)) != 0)
4173 return false;
4174 int oldstate;
4175 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
4176 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
4177 #ifdef __APPLE__
4178 uint64 tid;
4179 pthread_threadid_np(thread, &tid);
4180 osID = (uint32)tid;
4181 #else
4182 osID = (uint32) thread;
4183 #endif
4184 // printf("create hThread: %u\n", thread);
4185 Sleep(0);
4186 return true;
4187 #endif
4188}
4189
4191 #if defined WINDOWS
4192 int res = WaitForSingleObject(hThread, 0);
4193 if (res != WAIT_OBJECT_0)
4194 return false;
4195 return true;
4196 //return (CloseHandle(hThread) != 0);
4197 #else
4198 #ifdef __APPLE__
4199 // Non-destructive probe -- see IsThreadRunning. Must not pthread_join here,
4200 // or the later authoritative join double-joins a reaped thread and corrupts
4201 // the heap. pthread_kill(h, 0): ESRCH (non-zero) => thread has finished.
4202 // A null handle (empty slot) is "finished"; guard it since pthread_kill,
4203 // unlike pthread_join, dereferences the handle and would crash on null.
4204 if (!hThread)
4205 return true;
4206 return (pthread_kill(hThread, 0) != 0);
4207 #else
4208 // Non-destructive liveness probe (same rationale as the __APPLE__ branch).
4209 // The previous pthread_tryjoin_np() REAPS the thread on success, so any
4210 // second probe of the same handle (e.g. ThreadManager::shutdown()'s wait
4211 // loop followed by terminateThread()'s grace loop) operated on an
4212 // already-joined pthread_t -- undefined behaviour that segfaulted inside
4213 // pthread_tryjoin_np (SIGSEGV in the CMSDK threadmanager/network tests).
4214 // pthread_kill(h, 0) sends no signal: 0 => alive, ESRCH => finished.
4215 // A null handle (empty/reaped slot) counts as finished. Reaping is done
4216 // exactly once via utils::ReapThread / WaitForThreadToFinish / TerminateThread.
4217 if (!hThread)
4218 return true;
4219 return (pthread_kill(hThread, 0) != 0);
4220 #endif
4221 #endif
4222}
4223
4224bool ReapThread(ThreadHandle& hThread) {
4225 // Release the OS resources of a thread that has ALREADY finished, exactly
4226 // once, and zero the handle so no later probe/join can touch it again.
4227 // POSIX: a joinable thread that exited keeps its stack until pthread_join.
4228 // Windows: the thread object lives until its handle is closed.
4229 if (!hThread)
4230 return true;
4231 #if defined WINDOWS
4232 CloseHandle(hThread);
4233 #else
4234 pthread_join(hThread, NULL);
4235 #endif
4236 hThread = 0;
4237 return true;
4238}
4239
4241 // Atomic probe-and-reap: returns true iff the thread has finished, and in
4242 // that case releases its OS resources exactly once and ZEROES the handle so
4243 // no later probe, join or cancel can ever touch a dead pthread_t again
4244 // (double pthread_tryjoin_np/pthread_join on one handle is undefined
4245 // behaviour and segfaulted the CMSDK threadmanager/network tests on Linux).
4246 // Note: pthread_kill(h, 0) cannot be used as the probe on glibc >= 2.34 --
4247 // it returns 0 ("alive") for a thread that exited but was not yet joined.
4248 if (!hThread)
4249 return true;
4250 #if defined WINDOWS
4251 if (WaitForSingleObject(hThread, 0) != WAIT_OBJECT_0)
4252 return false;
4253 CloseHandle(hThread);
4254 #elif defined __APPLE__
4255 if (pthread_kill(hThread, 0) == 0)
4256 return false; // still alive
4257 pthread_join(hThread, NULL);
4258 #else
4259 if (pthread_tryjoin_np(hThread, NULL) != 0)
4260 return false; // still alive (EBUSY)
4261 #endif
4262 hThread = 0;
4263 return true;
4264}
4265
4266bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS) {
4267 // Sadly, the Linux implementation of join doesn't allow a timeout, so to be compatible
4268 // we cannot allow the Windows to have this either, although it could (and should) have
4269 #if defined WINDOWS
4270 int res = WaitForSingleObject(hThread, timeoutMS ? timeoutMS : INFINITE);
4271 if(res != WAIT_OBJECT_0)
4272 return false;
4273 return true;
4274 //return (CloseHandle(hThread) != 0);
4275 #else
4276 #ifdef __APPLE__
4277 if (!hThread)
4278 return true; // nothing to wait for
4279 // macOS has no pthread_timedjoin_np. A timeout==0 means "block until done".
4280 if (timeoutMS == 0)
4281 return (pthread_join(hThread, NULL) == 0);
4282 // For a bounded wait, poll liveness non-destructively (pthread_kill, no
4283 // signal) until the thread exits or the deadline passes, then perform a
4284 // single authoritative join to reap it. This avoids spawning a detached
4285 // joiner thread that would race a later join on the same handle (the
4286 // previous approach could leave two pthread_join calls on one target --
4287 // undefined behaviour that corrupted the heap).
4288 uint32 waited = 0;
4289 while (pthread_kill(hThread, 0) == 0) {
4290 if (waited >= timeoutMS)
4291 return false; // still running at deadline; do NOT reap
4292 Sleep(2);
4293 waited += 2;
4294 }
4295 // Thread has exited but is still joinable; reap it exactly once.
4296 pthread_join(hThread, NULL);
4297 return true;
4298 #else
4299 struct timespec ts;
4300 CalcTimeout(ts, timeoutMS);
4301 if (timeoutMS) {
4302 if (pthread_timedjoin_np(hThread, NULL, &ts) != 0)
4303 return false;
4304 else
4305 return true;
4306 }
4307 else {
4308 if (pthread_join(hThread, NULL) != 0)
4309 return false;
4310 }
4311 return true;
4312 #endif
4313 #endif
4314}
4315
4317 if (!hThread)
4318 return true;
4319 #if defined WINDOWS
4320 // printf("cancel hThread: %u\n", hThread);
4321 bool res = false;
4322 try {
4323 res = (::TerminateThread(hThread, 0) != 0);
4324 if (!res) {
4325 char* msg = new char[2048];
4326 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
4327 NULL, GetLastError(), 0, msg, sizeof(msg), NULL);
4328 msg[length] = '\0';
4329 LogPrint(0, LOG_SYSTEM, 0, "Error terminating thread: %s", msg);
4330 delete[] msg;
4331 }
4332 else
4333 CloseHandle(hThread);
4334 }
4335 catch (...) {}
4336 return res;
4337 #else
4338 // printf("cancel hThread: %u\n", hThread);
4339 pthread_cancel(hThread);
4340 if (pthread_join(hThread, NULL) != 0)
4341 return false;
4342 return true;
4343 #endif
4344}
4345
4346// ------------------------------------------------------------------
4347// Graceful-shutdown signal handling: block the shutdown signals on all
4348// threads and dequeue them SYNCHRONOUSLY on one dedicated thread via
4349// sigwait(). This keeps signal handling out of async-signal context and
4350// off arbitrary worker threads, so a signal can never drive exit()/teardown
4351// on a random thread and deadlock against the main thread's own teardown.
4352// ------------------------------------------------------------------
4353#ifndef WINDOWS
4354// The set of signals treated as "please shut down gracefully". SIGUSR2 is
4355// added purely as the wakeup used by StopSignalThread() to unblock sigwait().
4356static void SignalShutdownSigset(sigset_t* set) {
4357 sigemptyset(set);
4358 sigaddset(set, SIGINT);
4359 sigaddset(set, SIGTERM);
4360 sigaddset(set, SIGHUP);
4361 sigaddset(set, SIGUSR2); // internal wakeup only (see StopSignalThread)
4362}
4363
4364static pthread_t g_signalThread;
4365static bool g_signalThreadRunning = false;
4366static volatile sig_atomic_t g_signalThreadStop = 0;
4368static uint32 g_shutdownSignalCount = 0;
4369
4371 sigset_t set;
4373 int sig = 0;
4374 for (;;) {
4375 if (sigwait(&set, &sig) != 0)
4376 continue; // interrupted; wait again
4377 // SIGUSR2 is ONLY ever sent by StopSignalThread() as the stop wakeup, so
4378 // treating it as an unconditional break is race-free (no dependence on the
4379 // visibility ordering of g_signalThreadStop).
4380 if (sig == SIGUSR2 || g_signalThreadStop)
4381 break;
4385 }
4386 thread_ret_val(0);
4387}
4388#endif
4389
4391 #if defined WINDOWS
4392 return true; // no-op: Windows uses SetConsoleCtrlHandler / signal()
4393 #else
4394 sigset_t set;
4396 // Block on the calling (main) thread BEFORE any worker is spawned, so the
4397 // mask is inherited by every thread created afterwards.
4398 return (pthread_sigmask(SIG_BLOCK, &set, NULL) == 0);
4399 #endif
4400}
4401
4403 #if defined WINDOWS
4404 (void)cb;
4405 return true; // no-op on Windows
4406 #else
4408 return true; // idempotent
4409 g_shutdownCallback = cb;
4412 // Ensure the shutdown signals are blocked on THIS thread too, so if the
4413 // creator forgot BlockShutdownSignals() the new thread still inherits a
4414 // blocked mask and sigwait() works deterministically.
4415 sigset_t set;
4417 pthread_sigmask(SIG_BLOCK, &set, NULL);
4418 if (pthread_create(&g_signalThread, NULL, SignalThreadMain, NULL) != 0)
4419 return false;
4420 g_signalThreadRunning = true;
4421 return true;
4422 #endif
4423}
4424
4426 #if defined WINDOWS
4427 return true;
4428 #else
4430 return true;
4432 // Wake the sigwait() with the dedicated internal signal, then join.
4433 pthread_kill(g_signalThread, SIGUSR2);
4434 pthread_join(g_signalThread, NULL);
4435 g_signalThreadRunning = false;
4436 g_shutdownCallback = NULL;
4437 return true;
4438 #endif
4439}
4440
4442 #if defined WINDOWS
4443 return (SuspendThread(hThread) >= 0);
4444 #else
4445 return (pthread_kill(hThread, SIGSTOP) == 0);
4446 #endif
4447 return false;
4448}
4449
4451 #if defined WINDOWS
4452 DWORD count;
4453 while ( (count = ResumeThread(hThread)) > 1);
4454 return (count == 1);
4455 #else
4456 return (pthread_kill(hThread, SIGCONT) == 0);
4457 #endif
4458 return false;
4459}
4460
4461bool GetCurrentThreadUniqueID(uint32 &tid) {
4462 // This function returns an ID unique to the thread on a given OS
4463 // On Windows this is the Thread OS ID
4464 // On Linux we cannot read other thread OS IDs so it has to be the
4465 // thread handle converted to a 32bit uint.
4466 #if defined WINDOWS
4467 tid = ::GetCurrentThreadId();
4468 return true;
4469 #else
4470 #ifdef __APPLE__
4471 uint64 id;
4472 pthread_threadid_np(pthread_self(), &id);
4473 tid = (uint32)id;
4474 #else
4475 tid = (uint32) pthread_self();
4476 #endif
4477 return true;
4478 #endif
4479}
4480
4481bool GetCurrentThreadOSID(uint32 &tid) {
4482 #if defined WINDOWS
4483 tid = ::GetCurrentThreadId();
4484 return true;
4485 #else
4486 #ifdef __APPLE__
4487 uint64 id;
4488 if (pthread_threadid_np(pthread_self(), &id) != 0)
4489 return false;
4490 tid = (uint32)id;
4491 #else
4492 int id = syscall(SYS_gettid);
4493 if (id <= 0)
4494 return false;
4495 tid = (uint32)id;
4496 #endif
4497 return true;
4498 #endif
4499}
4500
4502 #if defined WINDOWS
4503 thread = ::GetCurrentThread();
4504 return true;
4505 #else
4506 thread = pthread_self();
4507 return true;
4508 #endif
4509}
4510
4512 #if defined WINDOWS
4513 DWORD code;
4514 if (!GetExitCodeThread(hThread, &code))
4515 return false;
4516 return (code == STILL_ACTIVE);
4517 #else
4518 #ifdef __APPLE__
4519 // Non-destructive liveness probe. macOS has no pthread_tryjoin_np, and we
4520 // must NOT use pthread_join here: this is polled repeatedly (e.g. by the
4521 // ThreadManager monitoring loop) and a join reaps the thread, after which
4522 // the authoritative TerminateThread/WaitForThreadToFinish join would operate
4523 // on an already-joined pthread_t -- undefined behaviour that corrupts the
4524 // heap. pthread_kill(h, 0) sends no signal and just reports existence:
4525 // 0 => still alive, ESRCH => already terminated. Unlike pthread_join, it
4526 // dereferences the handle, so a null handle (empty slot) must be guarded.
4527 if (!hThread)
4528 return false;
4529 return (pthread_kill(hThread, 0) == 0);
4530 #else
4531 // Non-destructive probe -- see CheckForThreadFinished/__APPLE__ comments.
4532 // pthread_tryjoin_np reaped the thread on success, making any later join
4533 // or probe of the same handle undefined behaviour (heap corruption/SIGSEGV).
4534 if (!hThread)
4535 return false;
4536 return (pthread_kill(hThread, 0) == 0);
4537 #endif
4538 #endif
4539}
4540
4542 #if defined WINDOWS
4543 return THREAD_STATS_AUTO;
4544 #else
4545 #if defined RUSAGE_THREAD
4546 return THREAD_STATS_ADHOC;
4547 #else
4548 return THREAD_STATS_OFF;
4549 #endif
4550 #endif
4551}
4552
4553bool GetCPUTicks(ThreadHandle hThread, uint64& ticks) {
4554 ticks = 0;
4555
4556 #if defined WINDOWS
4557 // if (!QueryThreadCycleTime(hThread, &ticks))
4558 // return false;
4559 uint64 cpuTicks = 0;
4560 LARGE_INTEGER perfFreq;
4561 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4562 return false;
4563 if (!QueryThreadCycleTime(hThread, &cpuTicks))
4564 return false;
4565 ticks = cpuTicks / (perfFreq.QuadPart / 1000000); // cpu ticks / (number of ticks per us)
4566 //FILETIME creationTime;
4567 //FILETIME exitTime;
4568 //FILETIME kernelTime;
4569 //FILETIME userTime;
4570 //if (!GetThreadTimes(hThread, &creationTime, &exitTime, &kernelTime, &userTime))
4571 // return false;
4572 //userCPU = ((uint64)userTime.dwLowDateTime | (((uint64)userTime.dwHighDateTime) << 32)) / 10;
4573 //kernelCPU = ((uint64)kernelTime.dwLowDateTime | (((uint64)kernelTime.dwHighDateTime) << 32)) / 10;
4574 return true;
4575 #else
4576 #ifdef __APPLE__
4577 // macOS: use Mach thread_info to get per-thread CPU time
4578 mach_port_t machThread = pthread_mach_thread_np(hThread);
4579 if (machThread == MACH_PORT_NULL)
4580 return false;
4581 thread_basic_info_data_t info;
4582 mach_msg_type_number_t infoCount = THREAD_BASIC_INFO_COUNT;
4583 if (thread_info(machThread, THREAD_BASIC_INFO, (thread_info_t)&info, &infoCount) != KERN_SUCCESS)
4584 return false;
4585 ticks = (uint64)info.user_time.seconds * 1000000 + info.user_time.microseconds
4586 + (uint64)info.system_time.seconds * 1000000 + info.system_time.microseconds;
4587 return true;
4588 #else
4589 clockid_t cid;
4590 if (pthread_getcpuclockid(hThread, &cid) != 0)
4591 return false;
4592 timespec ts;
4593 if (clock_gettime(cid, &ts) != -1 ) {
4594 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4595 return true;
4596 }
4597 else
4598 return false;
4599 #endif
4600 #endif
4601 return true;
4602}
4603
4604bool GetCPUTicks(uint64& ticks) {
4605 ticks = 0;
4606
4607 #if defined WINDOWS
4608 // #### QueryPerformanceFrequency
4609 uint64 cpuTicks = 0;
4610 LARGE_INTEGER perfFreq;
4611 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4612 return false;
4613 if (!QueryThreadCycleTime(::GetCurrentThread(), &cpuTicks))
4614 return false;
4615 ticks = cpuTicks / (perfFreq.QuadPart / 1000000); // cpu ticks / (number of ticks per us)
4616 //FILETIME creationTime;
4617 //FILETIME exitTime;
4618 //FILETIME kernelTime;
4619 //FILETIME userTime;
4620 //if (!GetThreadTimes(::GetCurrentThread(), &creationTime, &exitTime, &kernelTime, &userTime))
4621 // return false;
4622 //userCPU = ((uint64)userTime.dwLowDateTime | (((uint64)userTime.dwHighDateTime) << 32)) / 10;
4623 //kernelCPU = ((uint64)kernelTime.dwLowDateTime | (((uint64)kernelTime.dwHighDateTime) << 32)) / 10;
4624 return true;
4625 #else
4626 timespec ts;
4627 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) != -1 ) {
4628 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4629 return true;
4630 }
4631 else
4632 return false;
4633 //#if defined RUSAGE_THREAD
4634 // struct rusage us;
4635 // if (getrusage(RUSAGE_THREAD, &us) == 0) { // RUSAGE_THREAD // accumulate_thread_rusage
4636 // userCPU = (us.ru_utime.tv_sec * 1000000) + us.ru_utime.tv_usec;
4637 // kernelCPU = (us.ru_stime.tv_sec * 1000000) + us.ru_stime.tv_usec;
4638 // }
4639 // else
4640 // return false;
4641 //#else
4642 // return false;
4643 //#endif
4644 #endif
4645}
4646
4647bool GetProcessCPUTicks(uint32 osProcID, uint64& ticks) {
4648 ticks = 0;
4649
4650 #if defined WINDOWS
4651 HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, osProcID);
4652 if (!hProcess)
4653 return false;
4654 // if (!QueryProcessCycleTime(hProcess, &ticks))
4655 // return false;
4656
4657 uint64 cpuTicks = 0;
4658 LARGE_INTEGER perfFreq;
4659 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4660 return false;
4661 if (!QueryProcessCycleTime(hProcess, &cpuTicks))
4662 return false;
4663 ticks = cpuTicks / (perfFreq.QuadPart / 1000000); // cpu ticks / (number of ticks per us)
4664
4665 //FILETIME creationTime;
4666 //FILETIME exitTime;
4667 //FILETIME kernelTime;
4668 //FILETIME userTime;
4669 //if (!GetProcessTimes(::GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime))
4670 // return false;
4671 //userCPU = ((uint64)userTime.dwLowDateTime | (((uint64)userTime.dwHighDateTime) << 32)) / 10;
4672 //kernelCPU = ((uint64)kernelTime.dwLowDateTime | (((uint64)kernelTime.dwHighDateTime) << 32)) / 10;
4673 return true;
4674 #else
4675 #ifdef __APPLE__
4676 if ((pid_t)osProcID != getpid())
4677 return false;
4678 struct rusage ru;
4679 if (getrusage(RUSAGE_SELF, &ru) != 0)
4680 return false;
4681 ticks = ((uint64)ru.ru_utime.tv_sec * 1000000) + (uint64)ru.ru_utime.tv_usec
4682 + ((uint64)ru.ru_stime.tv_sec * 1000000) + (uint64)ru.ru_stime.tv_usec;
4683 return true;
4684 #else
4685 clockid_t clockid;
4686 if (clock_getcpuclockid(osProcID, &clockid) != 0)
4687 return false;
4688 timespec ts;
4689 if (clock_gettime(clockid, &ts) != -1 ) {
4690 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4691 return true;
4692 }
4693 else
4694 return false;
4695 //#if defined RUSAGE_THREAD
4696 // struct rusage us;
4697 // if (getrusage(RUSAGE_SELF, &us) == 0) { // RUSAGE_THREAD // accumulate_thread_rusage
4698 // userCPU = (us.ru_utime.tv_sec * 1000000) + us.ru_utime.tv_usec;
4699 // kernelCPU = (us.ru_stime.tv_sec * 1000000) + us.ru_stime.tv_usec;
4700 // }
4701 // else
4702 // return false;
4703 //#else
4704 // return false;
4705 //#endif
4706 #endif
4707 #endif
4708 return true;
4709}
4710
4711bool GetProcessCPUTicks(uint64& ticks) {
4712 ticks = 0;
4713
4714 #if defined WINDOWS
4715 // if (!QueryProcessCycleTime(::GetCurrentProcess(), &ticks))
4716 // return false;
4717
4718 uint64 cpuTicks = 0;
4719 LARGE_INTEGER perfFreq;
4720 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4721 return false;
4722 if (!QueryProcessCycleTime(::GetCurrentProcess(), &cpuTicks))
4723 return false;
4724 ticks = cpuTicks / (perfFreq.QuadPart / 1000000); // cpu ticks / (number of ticks per us)
4725
4726 //FILETIME creationTime;
4727 //FILETIME exitTime;
4728 //FILETIME kernelTime;
4729 //FILETIME userTime;
4730 //if (!GetProcessTimes(::GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime))
4731 // return false;
4732 //userCPU = ((uint64)userTime.dwLowDateTime | (((uint64)userTime.dwHighDateTime) << 32)) / 10;
4733 //kernelCPU = ((uint64)kernelTime.dwLowDateTime | (((uint64)kernelTime.dwHighDateTime) << 32)) / 10;
4734 return true;
4735 #else
4736 timespec ts;
4737 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) != -1 ) {
4738 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4739 return true;
4740 }
4741 else
4742 return false;
4743 //#if defined RUSAGE_THREAD
4744 // struct rusage us;
4745 // if (getrusage(RUSAGE_SELF, &us) == 0) { // RUSAGE_THREAD // accumulate_thread_rusage
4746 // userCPU = (us.ru_utime.tv_sec * 1000000) + us.ru_utime.tv_usec;
4747 // kernelCPU = (us.ru_stime.tv_sec * 1000000) + us.ru_stime.tv_usec;
4748 // }
4749 // else
4750 // return false;
4751 //#else
4752 // return false;
4753 //#endif
4754 #endif
4755 return true;
4756}
4757
4758bool GetProcAndOSCPUUsage(double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks) {
4759 #if defined WINDOWS
4760 return GetProcAndOSCPUUsage(0, procPercentUse, osPercentUse, prevOSTicks, prevOSIdleTicks, prevProcTicks);
4761 #else
4762 return GetProcAndOSCPUUsage(getpid(), procPercentUse, osPercentUse, prevOSTicks, prevOSIdleTicks, prevProcTicks);
4763 #endif
4764 return true;
4765}
4766
4767bool GetProcAndOSCPUUsage(uint32 osProcID, double& procPercentUse, double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks) {
4768 procPercentUse = osPercentUse = 0;
4769
4770 uint64 totalTicks, kernelTicks, userTicks, idleTicks, procTotalTicks, procUserTicks, procKernelTicks;
4771
4772 #if defined WINDOWS
4773 FILETIME idleTime, kernelTime, userTime;
4774 if (!GetSystemTimes(&idleTime, &kernelTime, &userTime))
4775 return false;
4776
4777 idleTicks = FileTimeToUint64(idleTime);
4778 kernelTicks = FileTimeToUint64(kernelTime);
4779 userTicks = FileTimeToUint64(userTime);
4780 totalTicks = kernelTicks + userTicks;
4781
4782 FILETIME procCreationTime, procExitTime, procKernelTime, procUserTime;
4783
4784 if (!osProcID) {
4785 if (!GetProcessTimes(GetCurrentProcess(), &procCreationTime, &procExitTime, &procKernelTime, &procUserTime))
4786 return false;
4787 }
4788 else {
4789 HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, osProcID);
4790 if (!hProcess)
4791 return false;
4792
4793 if (!GetProcessTimes(hProcess, &procCreationTime, &procExitTime, &procKernelTime, &procUserTime))
4794 return false;
4795 }
4796
4797 procKernelTicks = FileTimeToUint64(procKernelTime);
4798 procUserTicks = FileTimeToUint64(procUserTime);
4799 procTotalTicks = procKernelTicks + procUserTicks;
4800
4801 // printf("Proc User: %llu Kernel: %llu\n", procUserTicks, procKernelTicks);
4802
4803 #elif defined OSX
4804 host_cpu_load_info_data_t cpuInfo;
4805 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
4806 if (host_statistics64(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info64_t)&cpuInfo, &count) != KERN_SUCCESS)
4807 return false;
4808 // cpu_ticks are in Mach clock ticks (typically 100/s via CLK_TCK)
4809 // Convert to microseconds to match procTotalTicks units
4810 long ticksPerSec = sysconf(_SC_CLK_TCK);
4811 uint64 usPerTick = (ticksPerSec > 0) ? (1000000 / ticksPerSec) : 10000;
4812 totalTicks = ((uint64)cpuInfo.cpu_ticks[CPU_STATE_USER] + cpuInfo.cpu_ticks[CPU_STATE_SYSTEM] + cpuInfo.cpu_ticks[CPU_STATE_IDLE] + cpuInfo.cpu_ticks[CPU_STATE_NICE]) * usPerTick;
4813 idleTicks = (uint64)cpuInfo.cpu_ticks[CPU_STATE_IDLE] * usPerTick;
4814 if (osProcID == 0 || osProcID == (uint32)getpid()) {
4815 task_thread_times_info_data_t threadTimes;
4816 count = TASK_THREAD_TIMES_INFO_COUNT;
4817 if (task_info(mach_task_self(), TASK_THREAD_TIMES_INFO, (task_info_t)&threadTimes, &count) == KERN_SUCCESS)
4818 procTotalTicks = (uint64)threadTimes.user_time.seconds * 1000000 + threadTimes.user_time.microseconds + (uint64)threadTimes.system_time.seconds * 1000000 + threadTimes.system_time.microseconds;
4819 else
4820 procTotalTicks = 0;
4821 } else {
4822 return false;
4823 }
4824
4825 #else
4826 std::string statLine, procStatLine;
4827 std::ifstream statFile ("/proc/stat");
4828 std::ifstream procStatFile (StringFormat("/proc/%d/stat", osProcID).c_str());
4829 if (statFile.is_open())
4830 getline (statFile, statLine);
4831 else
4832 return false;
4833
4834 if (procStatFile.is_open())
4835 getline (procStatFile, procStatLine);
4836 else
4837 return false;
4838
4839 if (!statLine.length() || !procStatLine.length())
4840 return false;
4841
4842 //cpu 56344 20038 65629 5095979 55549 9083 10717 0 0 0
4843 uint64 fields[10];
4844 int retval = sscanf(statLine.c_str(), "cpu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu",
4845 &fields[0], &fields[1], &fields[2], &fields[3], &fields[4],
4846 &fields[5], &fields[6], &fields[7], &fields[8], &fields[9]);
4847 totalTicks = 0;
4848 for (int i=0; i<10; i++)
4849 totalTicks += fields[i];
4850 idleTicks = fields[3];
4851
4852 uint64 utime_ticks, stime_ticks, cutime_ticks, cstime_ticks;
4853 retval = sscanf(procStatLine.c_str(), "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu %llu %llu",
4854 &utime_ticks, &stime_ticks, &cutime_ticks, &cstime_ticks);
4855
4856 procTotalTicks = utime_ticks + stime_ticks + cutime_ticks + cstime_ticks;
4857 #endif
4858
4859 uint64 totalTicksSinceLastTime = totalTicks - prevOSTicks;
4860 uint64 idleTicksSinceLastTime = idleTicks - prevOSIdleTicks;
4861 uint64 procTicksSinceLastTime = procTotalTicks - prevProcTicks;
4862
4863 osPercentUse = 1.0f-((totalTicksSinceLastTime > 0) ? ((double)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4864 procPercentUse = ((totalTicksSinceLastTime > 0) ? ((double)procTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4865
4866// printf("Idle: %llu Total: %llu %.2f%%\n",
4867// idleTicksSinceLastTime, totalTicksSinceLastTime, percentUse*100);
4868
4869 prevOSTicks = totalTicks;
4870 prevOSIdleTicks = idleTicks;
4871 prevProcTicks = procTotalTicks;
4872
4873 return true;
4874}
4875
4876bool GetOSCPUUsage(double& percentUse) {
4877 percentUse = 0;
4878
4879 static uint64 PreviousTotalTicks = 0;
4880 static uint64 PreviousIdleTicks = 0;
4881
4882 uint64 totalTicks, kernelTicks, userTicks, idleTicks;
4883
4884 #if defined WINDOWS
4885
4886 FILETIME idleTime, kernelTime, userTime;
4887 if (!GetSystemTimes(&idleTime, &kernelTime, &userTime))
4888 return false;
4889
4890 idleTicks = FileTimeToUint64(idleTime);
4891 kernelTicks = FileTimeToUint64(kernelTime);
4892 userTicks = FileTimeToUint64(userTime);
4893 totalTicks = kernelTicks + userTicks;
4894
4895 #elif defined OSX
4896 host_cpu_load_info_data_t cpuInfo;
4897 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
4898 if (host_statistics64(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info64_t)&cpuInfo, &count) != KERN_SUCCESS)
4899 return false;
4900 totalTicks = (uint64)cpuInfo.cpu_ticks[CPU_STATE_USER] + cpuInfo.cpu_ticks[CPU_STATE_SYSTEM] + cpuInfo.cpu_ticks[CPU_STATE_IDLE] + cpuInfo.cpu_ticks[CPU_STATE_NICE];
4901 idleTicks = (uint64)cpuInfo.cpu_ticks[CPU_STATE_IDLE];
4902 #else
4903 std::string statLine;
4904 std::ifstream statFile("/proc/stat");
4905 if (!statFile.is_open() || !getline(statFile, statLine) || !statLine.length())
4906 return false;
4907
4908 uint64 fields[10];
4909 if (sscanf(statLine.c_str(), "cpu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu",
4910 &fields[0], &fields[1], &fields[2], &fields[3], &fields[4],
4911 &fields[5], &fields[6], &fields[7], &fields[8], &fields[9]) < 10)
4912 return false;
4913 totalTicks = 0;
4914 for (int i = 0; i < 10; i++)
4915 totalTicks += fields[i];
4916 idleTicks = fields[3];
4917 #endif
4918
4919 uint64 totalTicksSinceLastTime = totalTicks - PreviousTotalTicks;
4920 uint64 idleTicksSinceLastTime = idleTicks - PreviousIdleTicks;
4921
4922 percentUse = 1.0f-((totalTicksSinceLastTime > 0) ? ((double)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4923
4924// printf("Idle: %llu Total: %llu %.2f%%\n",
4925// idleTicksSinceLastTime, totalTicksSinceLastTime, percentUse*100);
4926
4927 PreviousTotalTicks = totalTicks;
4928 PreviousIdleTicks = idleTicks;
4929
4930 return true;
4931}
4932
4933bool GetThreadPriority(ThreadHandle hThread, uint16 priority) {
4934
4935 #if defined WINDOWS
4936 uint16 prio = ::GetThreadPriority(hThread);
4937 priority = FromOSPriority(prio);
4938 #else
4939 struct sched_param sched;
4940 int policy;
4941 #ifdef __APPLE__
4942 policy = SCHED_OTHER;
4943 #else
4944 policy = sched_getscheduler(0);
4945 if(policy < 0)
4946 return false;
4947 #endif
4948 if (pthread_getschedparam(hThread, &policy, &sched) != 0)
4949 return false;
4950
4951 priority = FromOSPriority(sched.sched_priority);
4952 #endif
4953 return true;
4954}
4955
4956bool SetThreadPriority(ThreadHandle hThread, uint16 priority) {
4957 #if defined WINDOWS
4958 return (::SetThreadPriority(hThread, ToOSPriority(priority)) != 0);
4959 #else
4960 int policy;
4961 struct sched_param sched;
4962 memset(&sched, 0, sizeof(struct sched_param));
4963
4964 policy = SCHED_FIFO;
4965 // policy = SCHED_RR;
4966 sched.sched_priority = ToOSPriority(priority);
4967
4968 int res = pthread_setschedparam(hThread, policy, &sched);
4969 if (res != 0)
4970 return false;
4971 #endif
4972 return true;
4973}
4974
4975int ToOSPriority(int pri) {
4976 int val;
4977
4978 #if defined WINDOWS
4979 if (pri == 0)
4980 val = THREAD_PRIORITY_NORMAL;
4981 else if (pri >= 90)
4982 val = THREAD_PRIORITY_TIME_CRITICAL;
4983 else if (pri >= 80)
4984 val = THREAD_PRIORITY_HIGHEST;
4985 else if (pri >= 70)
4986 val = THREAD_PRIORITY_ABOVE_NORMAL;
4987 else if (pri >= 60)
4988 val = THREAD_PRIORITY_NORMAL;
4989 else if (pri >= 50)
4990 val = THREAD_PRIORITY_BELOW_NORMAL;
4991 else if (pri >= 40)
4992 val = THREAD_PRIORITY_LOWEST;
4993 else
4994 val = THREAD_PRIORITY_IDLE;
4995 #else
4996 if (pri == 0)
4997 val = 40;
4998 else if (pri >= 90)
4999 val = 60;
5000 else if (pri >= 80)
5001 val = 55;
5002 else if (pri >= 70)
5003 val = 40;
5004 else if (pri >= 60)
5005 val = 35;
5006 else if (pri >= 50)
5007 val = 30;
5008 else if (pri >= 40)
5009 val = 25;
5010 else if (pri >= 30)
5011 val = 20;
5012 else if (pri >= 20)
5013 val = 15;
5014 else if (pri >= 10)
5015 val = 10;
5016 else
5017 val = 5;
5018 #endif
5019
5020 return val;
5021}
5022
5023int FromOSPriority(int pri) {
5024
5025 #if defined WINDOWS
5026 switch (pri) {
5027 case THREAD_PRIORITY_TIME_CRITICAL:
5028 return 80;
5029 case THREAD_PRIORITY_HIGHEST:
5030 return 60;
5031 case THREAD_PRIORITY_ABOVE_NORMAL:
5032 return 55;
5033 case THREAD_PRIORITY_NORMAL:
5034 return 50;
5035 case THREAD_PRIORITY_BELOW_NORMAL:
5036 return 40;
5037 case THREAD_PRIORITY_LOWEST:
5038 return 30;
5039 default:
5040 return 20;
5041 }
5042 #else
5043 return pri;
5044 #endif
5045}
5046
5047bool SignalThread(ThreadHandle hThread, int32 signal) {
5048 #if defined WINDOWS
5049 // ######################################
5050 #else
5051 // ######################################
5052 #endif
5053 return false;
5054}
5055
5056
5057
5058
5060// Desktop //
5062
5063bool GetDesktopSize(uint32& width, uint32& height) {
5064 width = height = 0;
5065 #if defined WINDOWS
5066 RECT desktop;
5067 // Get a handle to the desktop window
5068 const HWND hDesktop = GetDesktopWindow();
5069 // Get the size of screen to the variable desktop
5070 if (!GetWindowRect(hDesktop, &desktop))
5071 return false;
5072 // The top left corner will have coordinates (0,0)
5073 // and the bottom right corner will have coordinates
5074 // (horizontal, vertical)
5075 width = (uint32)desktop.right;
5076 height = (uint32)desktop.bottom;
5077 return true;
5078 #else
5079 return false;
5080 #endif
5081}
5082
5083bool RenameConsoleWindow(const char* name, bool prepend) {
5084 #if defined WINDOWS
5085 if (prepend) {
5086 uint32 size;
5087 char* oldName = new char[1024];
5088 if (!GetConsoleTitle(oldName, 1024)) {
5089 delete [] oldName;
5090 return false;
5091 }
5092 char* newName = StringFormat(size, "%s - %s", name, oldName);
5093 bool res = (SetConsoleTitle(name) != 0);
5094 delete [] newName;
5095 delete [] oldName;
5096 return res;
5097 }
5098 else
5099 return (SetConsoleTitle(name) != 0);
5100 #else
5101 return false;
5102 #endif
5103}
5104
5105bool MoveConsoleWindow(int32 x, int32 y, int32 w, int32 h) {
5106 #if defined WINDOWS
5107 char* consoleName = new char[1024];
5108 if (!GetConsoleTitle(consoleName, 1024)) {
5109 delete [] consoleName;
5110 return false;
5111 }
5112 HWND handle = FindWindow(NULL, consoleName);
5113 if (!handle) {
5114 delete [] consoleName;
5115 return false;
5116 }
5117 RECT wRect;
5118 if (!GetWindowRect(handle, &wRect)) {
5119 delete [] consoleName;
5120 return false;
5121 }
5122
5123 int conX = (x<0) ? wRect.left : x;
5124 int conY = (y<0) ? wRect.top : y;
5125 int conW = (w<0) ? wRect.right - wRect.left : w;
5126 int conH = (h<0) ? wRect.bottom - wRect.top : h;
5127
5128 bool res = (MoveWindow(handle, conX, conY, conW, conH, true) != 0);
5129 delete [] consoleName;
5130 return res;
5131
5132 #else
5133 return false;
5134 #endif
5135}
5136
5137
5139// Processes //
5141
5143 #if defined WINDOWS
5144 return (uint32)GetCurrentProcessId();
5145 #else
5146 return (uint32)getpid();
5147 #endif
5148}
5149
5150
5151int RunOSCommand(const char* cmdline, const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString) {
5152 if (!cmdline || !strlen(cmdline))
5153 return -1;
5154
5155 #if defined WINDOWS
5156 HANDLE g_hChildStd_OUT_Rd = NULL;
5157 HANDLE g_hChildStd_OUT_Wr = NULL;
5158 HANDLE g_hChildStd_ERR_Rd = NULL;
5159 HANDLE g_hChildStd_ERR_Wr = NULL;
5160
5161 SECURITY_ATTRIBUTES sa;
5162 // Set the bInheritHandle flag so pipe handles are inherited.
5163 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5164 sa.bInheritHandle = TRUE;
5165 sa.lpSecurityDescriptor = NULL;
5166 // Create a pipe for the child process's STDERR.
5167 if ( ! CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &sa, 0) ) {
5168 return -1;
5169 }
5170 // Ensure the read handle to the pipe for STDERR is not inherited.
5171 if ( ! SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0) ){
5172 return -1;
5173 }
5174 // Create a pipe for the child process's STDOUT.
5175 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0) ) {
5176 return -1;
5177 }
5178 // Ensure the read handle to the pipe for STDOUT is not inherited
5179 if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ){
5180 return -1;
5181 }
5182 PROCESS_INFORMATION piProcInfo;
5183 STARTUPINFO siStartInfo;
5184 bool bSuccess = FALSE;
5185
5186 // Set up members of the PROCESS_INFORMATION structure.
5187 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
5188
5189 // Set up members of the STARTUPINFO structure.
5190 // This structure specifies the STDERR and STDOUT handles for redirection.
5191 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
5192 siStartInfo.cb = sizeof(STARTUPINFO);
5193 siStartInfo.hStdError = g_hChildStd_ERR_Wr;
5194 siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
5195 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
5196
5197 uint32 size = 0;
5198 char* cmd = utils::StringFormat(size, cmdline);
5199
5200 // Create the child process.
5201 bSuccess = (CreateProcess(NULL,
5202 cmd, // command line
5203 NULL, // process security attributes
5204 NULL, // primary thread security attributes
5205 TRUE, // handles are inherited
5206 0, // creation flags
5207 NULL, // use parent's environment
5208 initdir, // use parent's current directory
5209 &siStartInfo, // STARTUPINFO pointer
5210 &piProcInfo) != 0); // receives PROCESS_INFORMATION
5211 CloseHandle(g_hChildStd_ERR_Wr);
5212 CloseHandle(g_hChildStd_OUT_Wr);
5213 // If an error occurs, exit the application.
5214 if ( ! bSuccess ) {
5215 return -1;
5216 }
5217
5218 uint64 startTime = GetTimeNow();
5219
5220 DWORD dwRead;
5221 char* chBuf = new char[PROCBUFSIZE];
5222 bSuccess = FALSE;
5223 for (;;) {
5224 bSuccess=(ReadFile( g_hChildStd_OUT_Rd, chBuf, PROCBUFSIZE, &dwRead, NULL) != 0);
5225 if( ! bSuccess || dwRead == 0 ) break;
5226 std::string s(chBuf, dwRead);
5227 stdoutString += s;
5228 if(GetTimeAgeMS(startTime) > (int32)timeout) break;
5229 }
5230 dwRead = 0;
5231 for (;;) {
5232 bSuccess=(ReadFile( g_hChildStd_ERR_Rd, chBuf, PROCBUFSIZE, &dwRead, NULL) != 0);
5233 if( ! bSuccess || dwRead == 0 ) break;
5234 std::string s(chBuf, dwRead);
5235 stderrString += s;
5236 if(GetTimeAgeMS(startTime) > (int32)timeout) break;
5237 }
5238 delete [] chBuf;
5239
5240 DWORD exitcode;
5241 if (GetExitCodeProcess(piProcInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
5242 TerminateProcess(piProcInfo.hProcess, 1);
5243 }
5244 CloseHandle(g_hChildStd_ERR_Rd);
5245 CloseHandle(g_hChildStd_OUT_Rd);
5246 CloseHandle(piProcInfo.hProcess);
5247 CloseHandle(piProcInfo.hThread);
5248 return exitcode;
5249 #else
5250 fflush(stdin);
5251 fflush(stdout);
5252 FILE* runfile = popen(cmdline, "r");
5253 if (runfile == NULL)
5254 return -1;
5255
5256 int exitcode = -1;
5257 int status;
5258 int res;
5259 int size = 4096;
5260 char* buffer = new char[size+1];
5261
5262 res = fread(buffer, 1, size, runfile);
5263 if (res <= 0) {
5264 status = pclose(runfile);
5265 exitcode = WEXITSTATUS(status);
5266 delete [] buffer;
5267 return exitcode;
5268 }
5269 do {
5270 buffer[res] = 0;
5271 stdoutString += buffer;
5272 } while (res = fread(buffer, 1, size, runfile));
5273
5274 status = pclose(runfile);
5275 exitcode = WEXITSTATUS(status);
5276 delete [] buffer;
5277 return exitcode;
5278
5279 //
5280 //int size = 1024;
5281 // char name[1024];
5282 // if (!RunOSTextCommand("uname -n", name, size))
5283 // return "";
5284 //
5285 //
5286 //int argc = 0;
5287 // char **argv=SplitCommandline(cmdline, argc);
5288 // if (!argc || !argv)
5289 // return -1;
5290
5291 // /* since pipes are unidirectional, we need two pipes.
5292 // one for data to flow from parent's stdout to child's
5293 // stdin and the other for child's stdout to flow to
5294 // parent's stdin */
5295
5296 // int* pipes = new int[NUM_PIPES][2];
5297 // int outfd[2];
5298 // int infd[2];
5299
5300 // // pipes for parent to write and read
5301 // pipe((*pipes)[PARENT_READ_PIPE]);
5302 // pipe((*pipes)[PARENT_WRITE_PIPE]);
5303
5304 // if(!fork()) {
5305
5306 // dup2(CHILD_READ_FD, STDIN_FILENO);
5307 // dup2(CHILD_WRITE_FD, STDOUT_FILENO);
5308
5309 // /* Close fds not required by child. Also, we don't
5310 // want the exec'ed program to know these existed */
5311 // close(CHILD_READ_FD);
5312 // close(CHILD_WRITE_FD);
5313 // close(PARENT_READ_FD);
5314 // close(PARENT_WRITE_FD);
5315
5316 // execv(argv[0], argv);
5317 // } else {
5318 // char buffer[100];
5319 // int count;
5320
5321 // /* close fds not required by parent */
5322 // close(CHILD_READ_FD);
5323 // close(CHILD_WRITE_FD);
5324
5325 // // Write to child�s stdin
5326 // //write(PARENT_WRITE_FD, "2^32\n", 5);
5327
5328 // // Read from child�s stdout
5329 // count = read(PARENT_READ_FD, buffer, sizeof(buffer)-1);
5330 // if (count >= 0) {
5331 // buffer[count] = 0;
5332 // printf("%s", buffer);
5333 // } else {
5334 // printf("IO Error\n");
5335 // }
5336 // // ################
5337 // // Not yet complete!!!
5338 // }
5339 #endif
5340
5341}
5342
5343#ifndef WINDOWS
5344// Call in a forked child just before exec. The signal mask survives fork+exec, and Psyclone blocks SIGINT, SIGTERM,
5345// SIGHUP and SIGUSR2 on every thread (BlockShutdownSignals at the top of main, handled by the sigwait thread), so a
5346// child launched from any node thread started with SIGTERM blocked: ExternalExec's graceful stop never reached it and
5347// every <executable> stop ended in SIGKILL after stopTimeout (psy_triggergroup_* timeouts on macOS, 17 Nov 2026).
5348// sigprocmask is async-signal-safe and, after fork, the child has just this one thread.
5350 sigset_t none;
5351 sigemptyset(&none);
5352 sigprocmask(SIG_SETMASK, &none, NULL);
5353}
5354#endif
5355
5356uint32 NewProcess(const char* cmdline, const char* initdir, const char* title, int16 x, int16 y, int16 w, int16 h) {
5357
5358 if (!cmdline || !strlen(cmdline))
5359 return 0;
5360
5361 #if defined WINDOWS
5362
5363 if (!ProcessInformationMap) {
5364 ProcessInformationMap = new std::map<uint32, ProcessData*>;
5365 ghJob = CreateJobObject(NULL, NULL); // GLOBAL
5366 if (ghJob) {
5367 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
5368 // Configure all child processes associated with the job to terminate when the
5369 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
5370 SetInformationJobObject(ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
5371 }
5372 }
5373
5374 ProcessData* pData = new ProcessData;
5375
5376 ZeroMemory(&(pData->procInfo), sizeof(pData->procInfo));
5377 ZeroMemory(&(pData->si), sizeof(pData->si));
5378 pData->si.cb = sizeof(pData->si);
5379 pData->si.wShowWindow = SW_SHOWNOACTIVATE; //SW_SHOW; // SW_HIDE;
5380
5381 if ( (x>=0) && (y>=0) && (w>=0) && (h>=0) ) {
5382 pData->si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USEPOSITION | STARTF_USESIZE;
5383 pData->si.dwX = x;
5384 pData->si.dwY = y;
5385 pData->si.dwXSize = w;
5386 pData->si.dwYSize = h;
5387 }
5388 else {
5389 pData->si.dwFlags = STARTF_USESHOWWINDOW;
5390 }
5391
5392 // cmdline/title are plain strings, not printf formats: copy verbatim into
5393 // mutable new[] buffers (see NewProcessEx note re: '%' fast-fail).
5394 char* titleCopy = NULL;
5395 if (title) {
5396 size_t tlen = strlen(title);
5397 titleCopy = new char[tlen + 1];
5398 memcpy(titleCopy, title, tlen + 1);
5399 pData->si.lpTitle = titleCopy;
5400 }
5401
5402 size_t clen = strlen(cmdline);
5403 char* cmd = new char[clen + 1];
5404 memcpy(cmd, cmdline, clen + 1);
5405 //utils::strcpyavail(cmd, cmdline, (uint32)strlen(cmdline)+1, true);
5406
5407 // DETACHED_PROCESS
5408 int res = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, initdir, &pData->si, &pData->procInfo);
5409 delete [] titleCopy;
5410 delete [] cmd;
5411 if (res == 0) {
5412 char* msg = new char[2048];
5413 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
5414 NULL, GetLastError(), 0, msg, sizeof(msg), NULL);
5415 msg[length] = '\0';
5416 LogPrint(0, LOG_SYSTEM, 0, "Error creating new process: %s\n%s", msg, cmd);
5417 delete [] msg;
5418 delete pData;
5419 return 0;
5420 }
5421
5422 if (ghJob)
5423 AssignProcessToJobObject(ghJob, pData->procInfo.hProcess);
5424
5425 ProcessInformationMap->insert(Proc_Pair((uint32)pData->procInfo.dwProcessId, pData));
5426 return pData->procInfo.dwProcessId;
5427
5428 #else
5429
5430 //std::vector<std::string> args = utils::TextListSplit(cmdline, " ");
5431 //int argc = args.size();
5433 //char** argv = new char*[argc+1];
5434 //int len;
5435 //for (int n=0; n<argc; n++) {
5436 // argv[n] = new char[args[n].size() + 1];
5437 // utils::strcpyavail(argv[n], args[n].c_str(), args[n].size()+1, true);
5438 //}
5439 //argv[argc] = NULL;
5440
5441 int argc = 0;
5442 char** argv = SplitCommandline(cmdline, argc);
5443 if (!argc)
5444 return -1;
5445
5446 pid_t ppid_before_fork = getpid();
5447 int pid = fork();
5448
5449 if (pid < 0) {
5450 DeleteCommandline(argv, argc);
5451 return 0;
5452 }
5453 // We are the child process
5454 else if (pid == 0) {
5455
5456 if ( initdir && (chdir(initdir) != 0) ) {
5457 LogPrint(0,LOG_SYSTEM,0,"Could not run process '%s' from starup dir '%s'\n", cmdline, initdir);
5458 exit(0);
5459 }
5460
5461 #ifndef __APPLE__
5462 int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
5463 if (r == -1) { perror(0); exit(1); }
5464 // test in case the original parent exited just
5465 // before the prctl() call
5466 if (getppid() != ppid_before_fork)
5467 exit(1);
5468 #endif
5469
5471 execvp(argv[0],argv);
5472 // here we exit the program, if we continue the call failed...
5473
5474 int res = errno;
5475 // If program didn't take over the exec call failed.
5476 LogPrint(0,LOG_SYSTEM,0,"Could not create new process: %s (%d)!\n", cmdline, res);
5477 exit(0);
5478
5479 }
5480 // we are in the calling process
5481 else {
5482 DeleteCommandline(argv, argc);
5483 return pid;
5484 }
5485
5486 #endif
5487}
5488
5489uint8 GetProcessStatus(uint32 proc, int &returncode) {
5490 returncode = 0;
5491 #if defined WINDOWS
5492 DWORD exitcode;
5493 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
5494 if (i != ProcessInformationMap->end()) {
5495 ProcessData* pData = i->second;
5496 if (GetExitCodeProcess(pData->procInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
5497 return PROC_RUNNING;
5498 }
5499 else {
5500 ProcessInformationMap->erase(i);
5501 CloseHandle(pData->procInfo.hProcess);
5502 CloseHandle(pData->procInfo.hThread);
5503 if (pData->hOutRead) CloseHandle(pData->hOutRead);
5504 if (pData->hErrRead) CloseHandle(pData->hErrRead);
5505 if (pData->hInWrite) CloseHandle(pData->hInWrite); // 2.7c stdin pipe
5506 if (pData->hJob) CloseHandle(pData->hJob); // 2.7c per-child job
5507 delete pData;
5508 returncode = exitcode;
5509 return PROC_TERMINATED;
5510 }
5511 }
5512 else {
5513 // We didn't create this process, look it up by id
5514 HANDLE hproc = OpenProcess(NULL, false, (DWORD)proc);
5515 if (!hproc)
5516 return PROC_ERROR;
5517 if (GetExitCodeProcess(hproc, &exitcode) && (exitcode == STILL_ACTIVE)) {
5518 CloseHandle(hproc);
5519 return PROC_RUNNING;
5520 }
5521 else {
5522 CloseHandle(hproc);
5523 return PROC_TERMINATED;
5524 }
5525 }
5526 #else
5527 int status;
5528 int res = waitpid(proc, &status, WNOHANG);
5529
5530 if (res == proc) {
5531 //if (WIFEXITED(status)) {
5532 // printf("exited, status=%d\n", WEXITSTATUS(status));
5533 // } else if (WIFSIGNALED(status)) {
5534 // printf("killed by signal %d\n", WTERMSIG(status));
5535 // } else if (WIFSTOPPED(status)) {
5536 // printf("stopped by signal %d\n", WSTOPSIG(status));
5537 // } else if (WIFCONTINUED(status)) {
5538 // printf("continued\n");
5539 // }
5540 returncode = WEXITSTATUS(status);
5541 //printf("Return code: %d\n", returncode);
5542 return PROC_TERMINATED;
5543 }
5544 else if (res == 0) {
5545 return PROC_RUNNING;
5546 }
5547 return PROC_TERMINATED;
5548 #endif
5549}
5550
5551#if !defined(WINDOWS)
5552// POSIX: release any capture pipe read-fds recorded for this pid by NewProcessEx.
5553// Safe to call for pids that were not captured (no-op). Does NOT reap/kill.
5554void ReleaseProcessCapture(uint32 proc) {
5555 if (!ProcessInformationMap) return;
5556 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
5557 if (i == ProcessInformationMap->end()) return;
5558 ProcessData* pData = i->second;
5559 if (pData->outFD >= 0) close(pData->outFD);
5560 if (pData->errFD >= 0) close(pData->errFD);
5561 ProcessInformationMap->erase(i);
5562 delete pData;
5563}
5564#else
5565// Windows: capture pipes are Win32 HANDLEs owned by the ProcessData entry and are
5566// closed by EndProcess; there is no separate read-fd to release here. Provided so
5567// the symbol resolves for the SWIG language bindings, which wrap it unconditionally.
5568void ReleaseProcessCapture(uint32 proc) {
5569}
5570#endif
5571
5572bool EndProcess(uint32 proc) {
5573 #if defined WINDOWS
5575 return true;
5576 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
5577 if (i != ProcessInformationMap->end()) {
5578 ProcessData* pData = i->second;
5579 TerminateProcess(pData->procInfo.hProcess, 1);
5580 CloseHandle(pData->procInfo.hProcess);
5581 CloseHandle(pData->procInfo.hThread);
5582 if (pData->hOutRead) CloseHandle(pData->hOutRead);
5583 if (pData->hErrRead) CloseHandle(pData->hErrRead);
5584 if (pData->hInWrite) CloseHandle(pData->hInWrite); // 2.7c stdin pipe
5585 if (pData->hJob) CloseHandle(pData->hJob); // 2.7c per-child job
5586 ProcessInformationMap->erase(i);
5587 delete pData;
5588 return true;
5589 }
5590 else {
5591 HANDLE hproc = OpenProcess(NULL, NULL, (DWORD)proc);
5592 if (!hproc)
5593 return true;
5594 if (TerminateProcess(hproc, 1) == 0) {
5595 CloseHandle(hproc);
5596 return false;
5597 }
5598 else {
5599 CloseHandle(hproc);
5600 return true;
5601 }
5602 }
5603 #else
5604 bool ok = (kill(proc, SIGKILL) == 0);
5605 ReleaseProcessCapture(proc); // close+erase any capture pipes for this pid
5606 return ok;
5607 #endif
5608}
5609
5610// ---- ProbeProcessWait (step 2.7b-i): stall-on-stdin probe primitive ----
5611#if defined(WINDOWS)
5612// Windows (step 2.7c): composite heuristic, NEVER exact.
5613//
5614// Windows cannot name the syscall a thread is blocked in, and Thor accepted the
5615// consequence explicitly ("Input detection - well, I think that's the best we
5616// have", 2026-08-05). Every alternative was rejected on inspection:
5617// - no public "blocked in ReadFile on handle X" API exists;
5618// - NtQueryInformationThread(ThreadLastSystemCall) is undocumented and unstable
5619// across builds;
5620// - GetThreadContext yields the instruction pointer, not the wait target;
5621// - NtQuerySystemInformation(SystemProcessInformation) gives wait REASONS but
5622// not the waited-on handle;
5623// - PeekNamedPipe answers the opposite question (is there unread child OUTPUT);
5624// - writing a probe byte to see whether it is consumed is destructive.
5625// So waitExact is hard-wired false here and waitingStdin is a composite:
5626// (1) the process is alive, AND
5627// (2) every thread is in a wait state (GetThreadWaitReason via the toolhelp
5628// snapshot is unavailable, so we use the job's active-process count plus
5629// thread wait counters we CAN read - see below), AND
5630// (3) the whole child TREE has burned ~no CPU since the previous sample.
5631// The CALLER (CLISession::probeStall) additionally requires a quiet output window
5632// before grading "likely", so a slow-but-working step is not flagged.
5633//
5634// ⚠️ Documented false positives, preserved deliberately: a socket/network wait or
5635// a plain `sleep` is indistinguishable from an stdin block - both are quiet and
5636// idle. The signal means "probably awaiting input or otherwise idle-blocked"; the
5637// decision to terminate stays with the sender.
5638//
5639// CPU accounting uses the PER-CHILD job object (ProcessData::hJob) so a
5640// GRANDCHILD's CPU counts: the real reader is usually a grandchild (`python` under
5641// `cmd.exe`), and per-process GetProcessTimes would report ~0 for the shell and
5642// mis-flag a busy tree as idle. Falls back to GetProcessTimes when the job is
5643// unavailable (pre-Win8 nested-job failure, or a pid we did not start).
5644bool ProbeProcessWait(uint32 pid, ProcessWaitInfo& out) {
5645 out.alive = false; out.waitExact = false; out.waitingStdin = false; out.cpuTimeMs = 0;
5646 if (!pid) return false;
5647 HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)pid);
5648 if (!h) return true; // gone (or inaccessible): degraded but valid probe
5649 DWORD code = 0;
5650 if (GetExitCodeProcess(h, &code) && code == STILL_ACTIVE)
5651 out.alive = true;
5652
5653 // --- (3) whole-tree CPU, job first, per-process as a fallback ---------------
5654 bool haveTreeCpu = false;
5655 ProcessData* pd = NULL;
5657 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(pid);
5658 if (i != ProcessInformationMap->end()) pd = i->second;
5659 }
5660 if (pd && pd->hJob) {
5661 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION jbai;
5662 ZeroMemory(&jbai, sizeof(jbai));
5663 DWORD retLen = 0;
5664 if (QueryInformationJobObject(pd->hJob, JobObjectBasicAccountingInformation,
5665 &jbai, sizeof(jbai), &retLen)) {
5666 // TotalUserTime/TotalKernelTime are LARGE_INTEGER in 100ns units and
5667 // accumulate over the job's whole lifetime, including exited members -
5668 // which is what we want: a monotonic tree-wide counter the caller diffs.
5669 out.cpuTimeMs = (uint64)((jbai.TotalUserTime.QuadPart +
5670 jbai.TotalKernelTime.QuadPart) / 10000ULL);
5671 haveTreeCpu = true;
5672 }
5673 }
5674 if (!haveTreeCpu) {
5675 FILETIME ct, et, kt, ut;
5676 if (GetProcessTimes(h, &ct, &et, &kt, &ut)) {
5677 ULARGE_INTEGER k, u;
5678 k.LowPart = kt.dwLowDateTime; k.HighPart = kt.dwHighDateTime;
5679 u.LowPart = ut.dwLowDateTime; u.HighPart = ut.dwHighDateTime;
5680 out.cpuTimeMs = (uint64)((k.QuadPart + u.QuadPart) / 10000ULL); // 100ns -> ms
5681 }
5682 }
5683
5684 // --- (2) is the tree quiescent? --------------------------------------------
5685 // A child blocked on stdin has no thread making progress. Windows will not tell
5686 // us WHICH handle a thread waits on, but it will tell us how much CPU each
5687 // thread has consumed, and a thread parked in a blocking read consumes none.
5688 // So sample the tree's CPU twice a short interval apart: zero delta across the
5689 // whole tree means nothing in it is running.
5690 //
5691 // ⚠️ waitingStdin must NOT simply mean "alive". A first draft set it true for
5692 // any live process, which made the composite meaningless - the busy-child test
5693 // would then rest entirely on the caller's CPU-delta term, and one unlucky
5694 // sample under tolerance would mis-flag a working child as awaiting input.
5695 // Distinguishing "parked" from "running but quiet" is the whole job of this
5696 // flag, so it is decided here on its own evidence.
5697 //
5698 // The double-sample is deliberately short (12 ms): long enough that a running
5699 // tree accrues measurable time on any modern scheduler quantum, short enough
5700 // that a caller polling every ~150 ms does not notice the cost.
5701 if (out.alive) {
5702 uint64 firstCpu = out.cpuTimeMs;
5703 Sleep(12);
5704 uint64 secondCpu = firstCpu;
5705 if (pd && pd->hJob) {
5706 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION j2;
5707 ZeroMemory(&j2, sizeof(j2));
5708 DWORD rl = 0;
5709 if (QueryInformationJobObject(pd->hJob, JobObjectBasicAccountingInformation,
5710 &j2, sizeof(j2), &rl))
5711 secondCpu = (uint64)((j2.TotalUserTime.QuadPart +
5712 j2.TotalKernelTime.QuadPart) / 10000ULL);
5713 } else {
5714 FILETIME c2, e2, k2, u2;
5715 if (GetProcessTimes(h, &c2, &e2, &k2, &u2)) {
5716 ULARGE_INTEGER k, u;
5717 k.LowPart = k2.dwLowDateTime; k.HighPart = k2.dwHighDateTime;
5718 u.LowPart = u2.dwLowDateTime; u.HighPart = u2.dwHighDateTime;
5719 secondCpu = (uint64)((k.QuadPart + u.QuadPart) / 10000ULL);
5720 }
5721 }
5722 // Report the LATER sample so the caller's own delta stays monotonic.
5723 out.cpuTimeMs = secondCpu;
5724 // Quiescent candidate: the tree burned no measurable CPU across the window.
5725 // The caller (CLISession::probeStall) still requires a quiet OUTPUT window
5726 // of stallProbeMs and a near-zero delta between ITS samples before grading
5727 // "likely" - so a socket wait or a plain sleep will legitimately look the
5728 // same here, which is the documented and accepted false positive.
5729 out.waitingStdin = (secondCpu == firstCpu);
5730 }
5731 CloseHandle(h);
5732 return true;
5733}
5734#elif defined(__APPLE__)
5735// macOS: libproc composite. Cannot name the blocking syscall, so waitExact is
5736// ALWAYS false; waitingStdin = all threads TH_STATE_WAITING and fd 0 is a pipe.
5737// Same-uid children only; no entitlements required.
5738bool ProbeProcessWait(uint32 pid, ProcessWaitInfo& out) {
5739 out.alive = false; out.waitExact = false; out.waitingStdin = false; out.cpuTimeMs = 0;
5740 if (!pid) return false;
5741 if (kill((pid_t)pid, 0) != 0 && errno == ESRCH) return true; // gone
5742 out.alive = true;
5743 struct proc_taskinfo ti;
5744 if (proc_pidinfo((int)pid, PROC_PIDTASKINFO, 0, &ti, sizeof(ti)) == (int)sizeof(ti))
5745 out.cpuTimeMs = (uint64)((ti.pti_total_user + ti.pti_total_system) / 1000000ULL); // ns -> ms
5746 uint64_t tids[256];
5747 int n = proc_pidinfo((int)pid, PROC_PIDLISTTHREADS, 0, tids, sizeof(tids));
5748 if (n <= 0) return true; // degraded: cannot inspect threads
5749 int count = n / (int)sizeof(uint64_t);
5750 bool allWaiting = (count > 0);
5751 for (int i = 0; i < count; i++) {
5752 struct proc_threadinfo th;
5753 if (proc_pidinfo((int)pid, PROC_PIDTHREADINFO, tids[i], &th, sizeof(th)) != (int)sizeof(th)
5754 || th.pth_run_state != TH_STATE_WAITING) {
5755 allWaiting = false; break;
5756 }
5757 }
5758 if (allWaiting) {
5759 struct pipe_fdinfo pfd;
5760 if (proc_pidfdinfo((int)pid, 0, PROC_PIDFDPIPEINFO, &pfd, sizeof(pfd)) == (int)sizeof(pfd))
5761 out.waitingStdin = true; // best-effort composite; never exact on macOS
5762 }
5763 return true;
5764}
5765#else
5766// Linux: /proc-based, exact. State 'S' pre-filter from /proc/<pid>/stat, then
5767// /proc/<pid>/task/*/syscall: blocked in read(2) with arg0==0 => waitingStdin.
5768// Walks the whole process group (the real stdin reader is usually a child of sh).
5769namespace { // ProbeProcessWait internals
5770#if defined(__x86_64__)
5771 static const long PPW_SYS_read = 0;
5772#elif defined(__aarch64__)
5773 static const long PPW_SYS_read = 63;
5774#else
5775 static const long PPW_SYS_read = -1; // unknown arch: degrade to waitExact=false
5776#endif
5777 // Parse /proc/<pid>/stat (or task stat): state char, pgrp, utime+stime in ticks.
5778 static bool ppwReadStat(const char* path, char& state, long& pgrp, uint64& cpuTicks) {
5779 FILE* f = fopen(path, "r");
5780 if (!f) return false;
5781 char buf[1024];
5782 size_t len = fread(buf, 1, sizeof(buf) - 1, f);
5783 fclose(f);
5784 if (!len) return false;
5785 buf[len] = 0;
5786 const char* p = strrchr(buf, ')'); // comm may contain spaces/parens
5787 if (!p) return false;
5788 p++; // now at " S ppid pgrp ..." (fields 3..)
5789 long ppid = 0; unsigned long ut = 0, st = 0;
5790 char st_c = 0;
5791 // fields: 3=state 4=ppid 5=pgrp ... 14=utime 15=stime
5792 if (sscanf(p, " %c %ld %ld %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu",
5793 &st_c, &ppid, &pgrp, &ut, &st) != 5)
5794 return false;
5795 state = st_c;
5796 cpuTicks = (uint64)ut + (uint64)st;
5797 return true;
5798 }
5799 // Check /proc/<pid>[/task/<tid>]/syscall: blocked in read(0,...)?
5800 // Returns: 1 = yes, 0 = no, -1 = unreadable (degrade).
5801 static int ppwSyscallIsStdinRead(const char* path) {
5802 FILE* f = fopen(path, "r");
5803 if (!f) return -1;
5804 char buf[256];
5805 size_t len = fread(buf, 1, sizeof(buf) - 1, f);
5806 fclose(f);
5807 if (!len) return -1;
5808 buf[len] = 0;
5809 long nr = 0; unsigned long arg0 = 0;
5810 if (sscanf(buf, "%ld %lx", &nr, &arg0) < 1)
5811 return -1; // "running" or unparsable
5812 if (PPW_SYS_read < 0) return -1;
5813 return (nr == PPW_SYS_read && arg0 == 0) ? 1 : 0;
5814 }
5815} // anonymous namespace
5816
5817bool ProbeProcessWait(uint32 pid, ProcessWaitInfo& out) {
5818 out.alive = false; out.waitExact = false; out.waitingStdin = false; out.cpuTimeMs = 0;
5819 if (!pid) return false;
5820 char path[64];
5821 snprintf(path, sizeof(path), "/proc/%u/stat", pid);
5822 char state = 0; long pgid = 0; uint64 ticks = 0;
5823 if (!ppwReadStat(path, state, pgid, ticks)) return true; // gone
5824 if (state == 'Z' || state == 'X') return true; // zombie/dead: not alive for wait purposes
5825 out.alive = true;
5826 long tck = sysconf(_SC_CLK_TCK);
5827 if (tck <= 0) tck = 100;
5828 uint64 totalTicks = 0;
5829 bool sawUnreadable = false, sawStdinRead = false;
5830 // Collect the process group: target + any /proc/<p> whose pgrp matches its pgid
5831 // (the real stdin reader is typically a child of /bin/sh, not sh itself).
5832 DIR* proc = opendir("/proc");
5833 if (proc) {
5834 struct dirent* de;
5835 while ((de = readdir(proc)) != NULL) {
5836 if (de->d_name[0] < '0' || de->d_name[0] > '9') continue;
5837 unsigned long p = strtoul(de->d_name, NULL, 10);
5838 char pstate = 0; long ppgrp = 0; uint64 pticks = 0;
5839 snprintf(path, sizeof(path), "/proc/%lu/stat", p);
5840 if (!ppwReadStat(path, pstate, ppgrp, pticks)) continue;
5841 if (ppgrp != pgid && (uint32)p != pid) continue;
5842 totalTicks += pticks;
5843 // Walk this member's threads; only sleeping ones can be blocked in read(0).
5844 char tdir[64];
5845 snprintf(tdir, sizeof(tdir), "/proc/%lu/task", p);
5846 DIR* tasks = opendir(tdir);
5847 if (!tasks) { sawUnreadable = true; continue; }
5848 struct dirent* te;
5849 while ((te = readdir(tasks)) != NULL) {
5850 if (te->d_name[0] < '0' || te->d_name[0] > '9') continue;
5851 char tpath[352]; char tstate = 0; long tpgrp = 0; uint64 tt = 0;
5852 snprintf(tpath, sizeof(tpath), "%s/%s/stat", tdir, te->d_name);
5853 if (ppwReadStat(tpath, tstate, tpgrp, tt) && tstate != 'S')
5854 continue; // cheap pre-filter: only sleeping threads
5855 snprintf(tpath, sizeof(tpath), "%s/%s/syscall", tdir, te->d_name);
5856 int r = ppwSyscallIsStdinRead(tpath);
5857 if (r < 0) sawUnreadable = true;
5858 else if (r == 1) sawStdinRead = true;
5859 }
5860 closedir(tasks);
5861 }
5862 closedir(proc);
5863 } else sawUnreadable = true;
5864 out.cpuTimeMs = totalTicks * 1000ULL / (uint64)tck;
5865 if (sawStdinRead) { out.waitingStdin = true; out.waitExact = true; }
5866 else if (!sawUnreadable) out.waitExact = true; // exact negative
5867 // else: /proc/*/syscall unreadable (perms/kernel config) -> degrade gracefully
5868 return true;
5869}
5870#endif // ProbeProcessWait per-OS
5871
5872#ifndef WINDOWS
5873// --- Persistent POSIX process launcher -------------------------------------
5874// prctl(PR_SET_PDEATHSIG) binds the death signal to the LAUNCHING THREAD, not
5875// the process. If NewProcessEx is called from a transient thread, the child is
5876// killed as soon as that thread exits. Die-with-parent launches are therefore
5877// routed through a single persistent launcher thread (lazy-created, lives for
5878// the process lifetime) so the signal is armed against a long-lived thread.
5879// On macOS the same effect is emulated with a kqueue nanny (see DoPosixForkExec).
5881 // inputs (borrowed pointers, valid for the duration of the call)
5882 const char* cmdline;
5883 const char* initdir;
5884 const std::map<std::string, std::string>* env;
5890 char* const* argv; // pre-split argv (NULL in shell mode)
5891 int outPipe0, outPipe1, errPipe0, errPipe1; // pre-created pipes (or -1s)
5892 // outputs
5893 pid_t pid; // <0 fork failed, else child pid
5894 bool done;
5895};
5896
5897// The fork+child-setup body shared by the direct path and the launcher thread.
5899 pid_t ppid_before_fork = getpid();
5900 (void)ppid_before_fork;
5901 // Shell-mode argv: run "/bin/sh -c <cmdline>" so shell semantics apply.
5902 const char* shArgv[4] = { "sh", "-c", r.cmdline, NULL };
5903 pid_t pid = fork();
5904 if (pid < 0)
5905 return pid;
5906 if (pid == 0) {
5907 // Child
5908 if (r.captureOutput) {
5909 dup2(r.outPipe1, STDOUT_FILENO);
5910 dup2(r.errPipe1, STDERR_FILENO);
5911 close(r.outPipe0); close(r.outPipe1);
5912 close(r.errPipe0); close(r.errPipe1);
5913 }
5914 else if (r.ignoreOutput) {
5915 int devnull = open("/dev/null", O_WRONLY);
5916 if (devnull >= 0) {
5917 dup2(devnull, STDOUT_FILENO);
5918 dup2(devnull, STDERR_FILENO);
5919 close(devnull);
5920 }
5921 }
5922 // else: inherit stdout/stderr as-is (console mode).
5923
5924 if (r.newProcessGroup)
5925 setpgid(0, 0); // child leads its own group (== its pid)
5926
5927 if (r.initdir && chdir(r.initdir) != 0) {
5928 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not run '%s' from startup dir '%s'\n", r.cmdline, r.initdir);
5929 _exit(127);
5930 }
5931
5932 if (r.env) {
5933 std::map<std::string, std::string>::const_iterator ei = r.env->begin();
5934 while (ei != r.env->end()) { setenv(ei->first.c_str(), ei->second.c_str(), 1); ei++; }
5935 }
5936
5937 #ifdef __APPLE__
5938 if (r.posixParentDeathSig) {
5939 // macOS has no PR_SET_PDEATHSIG: emulate with a detached kqueue nanny.
5940 // Force our own process group (even if newProcessGroup was false) so
5941 // the nanny can SIGKILL the whole tree via kill(-pgid).
5942 setpgid(0, 0);
5943 if (getppid() != ppid_before_fork)
5944 _exit(1); // parent already died before we could arm
5945 pid_t self = getpid();
5946 pid_t nanny = fork();
5947 if (nanny == 0) {
5948 // Grandchild nanny: wait for the launching process to exit, then kill the child's whole process group.
5949 // It also watches the child itself and just leaves if the child goes first (17 Nov 2026, Isaac): a
5950 // nanny that only waited for the launcher stayed behind for every crashed or restarted child, until
5951 // the node exited, and then sent kill(-pgid) to a process group id that might have been reused.
5952 // (Like PR_SET_PDEATHSIG on Linux, this no longer covers what an already-ended child left running.)
5953 bool launcherGone = true; // if the watch cannot be set up, keep the old behaviour
5954 int kq = kqueue();
5955 if (kq >= 0) {
5956 struct kevent ev;
5957 EV_SET(&ev, self, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
5958 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1)
5959 _exit(0); // the child has already gone (ESRCH)
5960 EV_SET(&ev, ppid_before_fork, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
5961 if (kevent(kq, &ev, 1, NULL, 0, NULL) != -1) {
5962 struct kevent out;
5963 if ((kevent(kq, NULL, 0, &out, 1, NULL) == 1) && ((pid_t)out.ident == self))
5964 launcherGone = false;
5965 }
5966 }
5967 if (launcherGone)
5968 kill(-self, SIGKILL);
5969 _exit(0);
5970 }
5971 }
5972 #else
5973 if (r.posixParentDeathSig) {
5974 int pres = prctl(PR_SET_PDEATHSIG, r.posixParentDeathSig);
5975 if (pres == -1) { perror(0); _exit(1); }
5976 // Parent may have died between fork() and prctl(): check.
5977 if (getppid() != ppid_before_fork)
5978 _exit(1);
5979 }
5980 #endif
5981
5983 execvp(r.posixUseShell ? "/bin/sh" : r.argv[0],
5984 r.posixUseShell ? (char* const*)shArgv : r.argv);
5985 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not create new process: %s (%d)!\n", r.cmdline, errno);
5986 _exit(127);
5987 }
5988 return pid;
5989}
5990
5991// Single-slot handoff to the persistent launcher thread. Launches are rare, so
5992// callers are serialized under gLaunchSerialMx.
5993// The launcher thread lives for the whole process and is never joined, so the mutex
5994// and condvar it blocks on must never be destroyed either: as plain statics, exit()
5995// ran ~condition_variable while the thread was still waiting on it, and glibc's
5996// pthread_cond_destroy then waits for that waiter forever - any process that had
5997// launched a child hung at exit after main() returned (Examples/psytest.xml: 7/7
5998// SUCCESS, then hung in __run_exit_handlers -> pthread_cond_destroy(gLaunchCv)). Heap
5999// objects that are deliberately leaked have process lifetime, like the thread.
6000static std::mutex& gLaunchMx = *new std::mutex;
6001static std::condition_variable& gLaunchCv = *new std::condition_variable;
6003static bool gLauncherStarted = false;
6004static std::mutex gLaunchSerialMx;
6005
6007 std::unique_lock<std::mutex> lock(gLaunchMx);
6008 for (;;) {
6009 while (!gLaunchReq)
6010 gLaunchCv.wait(lock);
6012 req->pid = DoPosixForkExec(*req);
6013 req->done = true;
6014 gLaunchReq = NULL;
6015 gLaunchCv.notify_all();
6016 }
6017 thread_ret_val(0);
6018}
6019
6021 std::lock_guard<std::mutex> serial(gLaunchSerialMx);
6022 std::unique_lock<std::mutex> lock(gLaunchMx);
6023 if (!gLauncherStarted) {
6024 ThreadHandle th;
6025 uint32 osID = 0;
6026 if (!CreateThread((THREAD_FUNCTION)ProcessLauncherRun, NULL, th, osID))
6027 return DoPosixForkExec(req); // degraded: launch inline (old behavior)
6028 gLauncherStarted = true;
6029 }
6030 req.done = false;
6031 gLaunchReq = &req;
6032 gLaunchCv.notify_all();
6033 while (!req.done)
6034 gLaunchCv.wait(lock);
6035 return req.pid;
6036}
6037#endif // !WINDOWS
6038
6039uint32 NewProcessEx(const char* cmdline, const char* initdir, const char* title,
6040 const std::map<std::string, std::string>* env,
6041 bool captureOutput, bool ignoreOutput, bool newProcessGroup,
6042 int posixParentDeathSig, bool posixUseShell) {
6043 if (!cmdline || !strlen(cmdline))
6044 return 0;
6045
6046 #if defined WINDOWS
6047
6048 (void)posixParentDeathSig; (void)posixUseShell;
6049 if (!ProcessInformationMap) {
6050 ProcessInformationMap = new std::map<uint32, ProcessData*>;
6051 ghJob = CreateJobObject(NULL, NULL); // GLOBAL
6052 if (ghJob) {
6053 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
6054 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
6055 SetInformationJobObject(ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
6056 }
6057 }
6058
6059 ProcessData* pData = new ProcessData;
6060 ZeroMemory(&(pData->procInfo), sizeof(pData->procInfo));
6061 ZeroMemory(&(pData->si), sizeof(pData->si));
6062 pData->si.cb = sizeof(pData->si);
6063 pData->si.wShowWindow = SW_SHOWNOACTIVATE;
6064 pData->si.dwFlags = STARTF_USESHOWWINDOW;
6065
6066 // hInRead is the CHILD's end of the new stdin pipe (2.7c) - inheritable, and
6067 // closed in the parent right after CreateProcess like the other child ends.
6068 HANDLE hOutWrite = NULL, hErrWrite = NULL, hNull = NULL, hInRead = NULL;
6069 SECURITY_ATTRIBUTES sa;
6070 ZeroMemory(&sa, sizeof(sa));
6071 sa.nLength = sizeof(sa);
6072 sa.bInheritHandle = TRUE;
6073 sa.lpSecurityDescriptor = NULL;
6074
6075 if (captureOutput) {
6076 // Create stdout/stderr pipes; make only the WRITE ends inheritable.
6077 if ( !CreatePipe(&pData->hOutRead, &hOutWrite, &sa, 0) ||
6078 !CreatePipe(&pData->hErrRead, &hErrWrite, &sa, 0) ) {
6079 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not create output pipes for '%s'", cmdline);
6080 if (pData->hOutRead) CloseHandle(pData->hOutRead);
6081 if (hOutWrite) CloseHandle(hOutWrite);
6082 if (pData->hErrRead) CloseHandle(pData->hErrRead);
6083 delete pData;
6084 return 0;
6085 }
6086 SetHandleInformation(pData->hOutRead, HANDLE_FLAG_INHERIT, 0);
6087 SetHandleInformation(pData->hErrRead, HANDLE_FLAG_INHERIT, 0);
6088 // T1.1 step 2.7c: give the child its OWN stdin pipe. Previously it
6089 // inherited the parent's STD_INPUT_HANDLE, which has two consequences:
6090 // a child that reads stdin gets whatever the parent's console has (an
6091 // instant EOF when there is no console at all, e.g. under SSH or as a
6092 // service), so it CANNOT block awaiting input - making a stall-on-stdin
6093 // probe impossible to demonstrate; and there was no handle to write to,
6094 // so WriteProcessInput()/CLISession::writeStdin() had nothing to use.
6095 // Only the child's READ end is inheritable; we keep the write end.
6096 if (!CreatePipe(&hInRead, &pData->hInWrite, &sa, 0)) {
6097 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not create stdin pipe for '%s'", cmdline);
6098 CloseHandle(pData->hOutRead); CloseHandle(hOutWrite);
6099 CloseHandle(pData->hErrRead); CloseHandle(hErrWrite);
6100 delete pData;
6101 return 0;
6102 }
6103 SetHandleInformation(pData->hInWrite, HANDLE_FLAG_INHERIT, 0);
6104 pData->si.dwFlags |= STARTF_USESTDHANDLES;
6105 pData->si.hStdOutput = hOutWrite;
6106 pData->si.hStdError = hErrWrite;
6107 pData->si.hStdInput = hInRead;
6108 }
6109 else if (ignoreOutput) {
6110 hNull = CreateFile("NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
6111 &sa, OPEN_EXISTING, 0, NULL);
6112 if (hNull != INVALID_HANDLE_VALUE) {
6113 pData->si.dwFlags |= STARTF_USESTDHANDLES;
6114 pData->si.hStdOutput = hNull;
6115 pData->si.hStdError = hNull;
6116 pData->si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
6117 }
6118 else hNull = NULL;
6119 }
6120
6121 // Build the environment block (parent env + overrides) if any overrides given.
6122 char* envBlock = NULL;
6123 if (env && env->size()) {
6124 std::map<std::string, std::string> merged;
6125 LPCH parentEnv = GetEnvironmentStrings();
6126 if (parentEnv) {
6127 for (LPCH p = parentEnv; *p; ) {
6128 std::string entry = p;
6129 size_t eq = entry.find('=');
6130 if (eq != std::string::npos && eq > 0)
6131 merged[entry.substr(0, eq)] = entry.substr(eq + 1);
6132 p += entry.size() + 1;
6133 }
6134 FreeEnvironmentStrings(parentEnv);
6135 }
6136 std::map<std::string, std::string>::const_iterator ei = env->begin();
6137 while (ei != env->end()) { merged[ei->first] = ei->second; ei++; }
6138 size_t total = 1;
6139 std::map<std::string, std::string>::iterator mi = merged.begin();
6140 while (mi != merged.end()) { total += mi->first.size() + 1 + mi->second.size() + 1; mi++; }
6141 envBlock = new char[total];
6142 size_t off = 0;
6143 for (mi = merged.begin(); mi != merged.end(); mi++) {
6144 std::string kv = mi->first + "=" + mi->second;
6145 memcpy(envBlock + off, kv.c_str(), kv.size() + 1);
6146 off += kv.size() + 1;
6147 }
6148 envBlock[off] = 0;
6149 }
6150
6151 DWORD flags = CREATE_NEW_CONSOLE;
6152 if (newProcessGroup)
6153 flags |= CREATE_NEW_PROCESS_GROUP;
6154
6155 // NOTE: cmdline/title are plain strings, NOT printf formats. Copy them
6156 // verbatim into mutable new[] buffers. (Previously StringFormat(size, x)
6157 // was used, which interpreted any '%' in the command line as a printf
6158 // conversion -> invalid-parameter fast-fail (c0000409) for commands like
6159 // `cmd /c echo %VAR%`, and mismatched the malloc alloc with delete[].)
6160 char* titleCopy = NULL;
6161 if (title) {
6162 size_t tlen = strlen(title);
6163 titleCopy = new char[tlen + 1];
6164 memcpy(titleCopy, title, tlen + 1);
6165 pData->si.lpTitle = titleCopy;
6166 }
6167 size_t clen = strlen(cmdline);
6168 char* cmd = new char[clen + 1];
6169 memcpy(cmd, cmdline, clen + 1);
6170
6171 int res = CreateProcess(NULL, cmd, NULL, NULL, TRUE, flags, envBlock, initdir, &pData->si, &pData->procInfo);
6172
6173 delete [] titleCopy;
6174 delete [] cmd;
6175 if (envBlock) delete [] envBlock;
6176 // Parent closes the child's ends and the null handle; keeps its own ends.
6177 // hInRead MUST be closed here: while the parent holds a copy of the child's
6178 // read end, closing our WRITE end would not deliver EOF to the child, so a
6179 // child waiting on stdin would hang forever instead of seeing our close.
6180 if (hOutWrite) CloseHandle(hOutWrite);
6181 if (hErrWrite) CloseHandle(hErrWrite);
6182 if (hInRead) CloseHandle(hInRead);
6183 if (hNull) CloseHandle(hNull);
6184
6185 if (res == 0) {
6186 char msg[2048];
6187 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, msg, sizeof(msg), NULL);
6188 msg[length] = '\0';
6189 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: error creating process: %s\n%s", msg, cmdline);
6190 if (pData->hOutRead) CloseHandle(pData->hOutRead);
6191 if (pData->hErrRead) CloseHandle(pData->hErrRead);
6192 if (pData->hInWrite) CloseHandle(pData->hInWrite); // 2.7c stdin pipe
6193 // NOTE: hJob is not yet created at this point (it is assigned only after
6194 // a successful CreateProcess below), so there is nothing to close here.
6195 delete pData;
6196 return 0;
6197 }
6198 if (ghJob)
6199 AssignProcessToJobObject(ghJob, pData->procInfo.hProcess);
6200 // T1.1 step 2.7c: additionally place the child in its OWN job, so
6201 // ProbeProcessWait can read whole-TREE CPU for THIS child. ghJob above is
6202 // process-wide (kill-on-close) and aggregates every child we ever started,
6203 // so its accounting cannot answer "is this child's tree idle?".
6204 // Nested jobs require Windows 8+; on failure we simply leave hJob NULL and
6205 // the probe degrades to per-process times rather than refusing to work.
6206 pData->hJob = CreateJobObject(NULL, NULL);
6207 if (pData->hJob) {
6208 if (!AssignProcessToJobObject(pData->hJob, pData->procInfo.hProcess)) {
6209 CloseHandle(pData->hJob);
6210 pData->hJob = NULL; // degraded, not fatal
6211 }
6212 }
6213 ProcessInformationMap->insert(Proc_Pair((uint32)pData->procInfo.dwProcessId, pData));
6214 return pData->procInfo.dwProcessId;
6215
6216 #else
6217 // POSIX: real implementation. Fork/execvp with optional stdout/stderr
6218 // capture pipes, per-child env overrides (merged over the parent's),
6219 // working directory, and (optionally) the child leading its own process
6220 // group so a break signal can be delivered to the whole group via
6221 // SendProcessBreak(). Lifecycle (reap/kill) is via GetProcessStatus() /
6222 // WaitForProcess() / EndProcess(), which operate on the bare pid; the
6223 // only bookkeeping kept here is the capture read-fds for ReadProcessOutput().
6224 (void)title; (void)ignoreOutput;
6225
6227 ProcessInformationMap = new std::map<uint32, ProcessData*>;
6228
6229 int outPipe[2] = { -1, -1 }, errPipe[2] = { -1, -1 };
6230 if (captureOutput) {
6231 if (pipe(outPipe) != 0) {
6232 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not create output pipes for '%s'", cmdline);
6233 return 0;
6234 }
6235 if (pipe(errPipe) != 0) {
6236 LogPrint(0, LOG_SYSTEM, 0, "NewProcessEx: could not create output pipes for '%s'", cmdline);
6237 close(outPipe[0]); close(outPipe[1]);
6238 return 0;
6239 }
6240 }
6241
6242 int argc = 0;
6243 char** argv = NULL;
6244 if (!posixUseShell) {
6245 argv = SplitCommandline(cmdline, argc);
6246 if (!argc) {
6247 if (captureOutput) { close(outPipe[0]); close(outPipe[1]); close(errPipe[0]); close(errPipe[1]); }
6248 if (argv) DeleteCommandline(argv, argc);
6249 return 0;
6250 }
6251 }
6252
6254 req.cmdline = cmdline; req.initdir = initdir; req.env = env;
6255 req.captureOutput = captureOutput; req.ignoreOutput = ignoreOutput;
6256 req.newProcessGroup = newProcessGroup; req.posixUseShell = posixUseShell;
6257 req.posixParentDeathSig = posixParentDeathSig;
6258 req.argv = argv;
6259 req.outPipe0 = outPipe[0]; req.outPipe1 = outPipe[1];
6260 req.errPipe0 = errPipe[0]; req.errPipe1 = errPipe[1];
6261 req.pid = -1; req.done = false;
6262 // Die-with-parent launches go through the persistent launcher thread so
6263 // PR_SET_PDEATHSIG (Linux) is armed against a thread that never exits;
6264 // all other launches fork inline on the caller thread exactly as before.
6265 int pid = (int)(posixParentDeathSig ? SubmitLaunchRequest(req) : DoPosixForkExec(req));
6266 if (pid < 0) {
6267 if (argv) DeleteCommandline(argv, argc);
6268 if (captureOutput) { close(outPipe[0]); close(outPipe[1]); close(errPipe[0]); close(errPipe[1]); }
6269 return 0;
6270 }
6271 // Parent (all child-side setup lives in DoPosixForkExec above)
6272 if (argv) DeleteCommandline(argv, argc);
6273 if (captureOutput) {
6274 close(outPipe[1]);
6275 close(errPipe[1]);
6276 fcntl(outPipe[0], F_SETFL, fcntl(outPipe[0], F_GETFL, 0) | O_NONBLOCK);
6277 fcntl(errPipe[0], F_SETFL, fcntl(errPipe[0], F_GETFL, 0) | O_NONBLOCK);
6278 ProcessData* pData = new ProcessData;
6279 pData->outFD = outPipe[0];
6280 pData->errFD = errPipe[0];
6281 ProcessInformationMap->insert(Proc_Pair((uint32)pid, pData));
6282 }
6283 return (uint32)pid;
6284 #endif
6285}
6286
6287// T1.1 step 2.7c: write to a captured child's stdin. Windows only - see the header.
6288bool WriteProcessInput(uint32 proc, const char* data, uint32 len) {
6289 #if defined WINDOWS
6290 if (!data || !len) return false;
6291 if (!ProcessInformationMap) return false;
6292 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
6293 if (i == ProcessInformationMap->end()) return false;
6294 ProcessData* pData = i->second;
6295 if (!pData->hInWrite) return false; // child inherited our stdin; nothing to write
6296 uint32 written = 0;
6297 while (written < len) {
6298 DWORD n = 0;
6299 if (!WriteFile(pData->hInWrite, data + written, (DWORD)(len - written), &n, NULL) || !n) {
6300 // ERROR_BROKEN_PIPE / ERROR_NO_DATA: the child closed its read end.
6301 // Report failure rather than spinning; callers treat it as "child gone".
6302 return false;
6303 }
6304 written += (uint32)n;
6305 }
6306 return true;
6307 #else
6308 // POSIX: CLISession owns the child's stdin fd directly on the fork/pipe path
6309 // and writes to it there. Routing writes through this map as well would make
6310 // two owners of one descriptor, which is the class of bug that produced the
6311 // flake-1 double-free, so it is deliberately not offered here.
6312 (void)proc; (void)data; (void)len;
6313 return false;
6314 #endif
6315}
6316
6317// T1.1 step 2.7c: close a captured child's stdin, delivering EOF. Idempotent.
6318bool CloseProcessInput(uint32 proc) {
6319 #if defined WINDOWS
6320 if (!ProcessInformationMap) return false;
6321 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
6322 if (i == ProcessInformationMap->end()) return false;
6323 ProcessData* pData = i->second;
6324 if (!pData->hInWrite) return false;
6325 CloseHandle(pData->hInWrite);
6326 pData->hInWrite = NULL; // so the teardown paths do not double-close
6327 return true;
6328 #else
6329 (void)proc;
6330 return false;
6331 #endif
6332}
6333
6334bool ReadProcessOutput(uint32 proc, std::string& out, std::string& err) {
6335 #if defined WINDOWS
6336 if (!ProcessInformationMap) return false;
6337 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
6338 if (i == ProcessInformationMap->end()) return false;
6339 ProcessData* pData = i->second;
6340 HANDLE handles[2] = { pData->hOutRead, pData->hErrRead };
6341 std::string* targets[2] = { &out, &err };
6342 char buf[4096];
6343 for (int n = 0; n < 2; n++) {
6344 if (!handles[n]) continue;
6345 DWORD avail = 0;
6346 // PeekNamedPipe works on anonymous pipes to avoid blocking on ReadFile.
6347 while (PeekNamedPipe(handles[n], NULL, 0, NULL, &avail, NULL) && avail) {
6348 DWORD toRead = avail < sizeof(buf) ? avail : (DWORD)sizeof(buf);
6349 DWORD got = 0;
6350 if (!ReadFile(handles[n], buf, toRead, &got, NULL) || !got) break;
6351 targets[n]->append(buf, got);
6352 }
6353 }
6354 return true;
6355 #else
6356 // POSIX: drain the non-blocking capture pipes recorded by NewProcessEx.
6357 // Appends any newly available bytes (matching the Windows path); returns
6358 // true if this pid was launched with captureOutput.
6359 if (!ProcessInformationMap) return false;
6360 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
6361 if (i == ProcessInformationMap->end()) return false;
6362 ProcessData* pData = i->second;
6363 int fds[2] = { pData->outFD, pData->errFD };
6364 std::string* targets[2] = { &out, &err };
6365 char buf[4096];
6366 for (int n = 0; n < 2; n++) {
6367 if (fds[n] < 0) continue;
6368 ssize_t got;
6369 while ((got = read(fds[n], buf, sizeof(buf))) > 0)
6370 targets[n]->append(buf, (size_t)got);
6371 }
6372 return true;
6373 #endif
6374}
6375
6376// ------------------------------------------------------------------ 2.7d
6377// Terminal-mode child launch (POSIX PTY). See Utils.h for semantics. The
6378// master-fd bookkeeping lives here (file-local), NOT in the header ProcessData
6379// map: terminal children share the pid-based lifecycle helpers but only need
6380// one extra fd, and a separate map avoids touching the capture-path struct.
6381#if !defined(WINDOWS)
6382static std::map<uint32, int>* TerminalMasterMap = NULL;
6383static bool TerminalMasterFind(uint32 proc, int& fd) {
6384 if (!TerminalMasterMap) return false;
6385 std::map<uint32, int>::iterator i = TerminalMasterMap->find(proc);
6386 if (i == TerminalMasterMap->end()) return false;
6387 fd = i->second;
6388 return true;
6389}
6390#endif
6391
6392uint32 NewProcessTerminal(const char* cmdline, const char* initdir,
6393 const std::map<std::string, std::string>* env,
6394 uint16 cols, uint16 rows) {
6395#if defined(WINDOWS)
6396 // Stub until ConPTY lands in step 2.7e.
6397 (void)cmdline; (void)initdir; (void)env; (void)cols; (void)rows;
6398 LogPrint(0, LOG_SYSTEM, 1, "NewProcessTerminal: unsupported until ConPTY (2.7e)");
6399 return 0;
6400#else
6401 if (!cmdline || !*cmdline) return 0;
6402 // posix_openpt (not openpty) so no -lutil link dependency on older glibc.
6403 int master = posix_openpt(O_RDWR | O_NOCTTY);
6404 if (master < 0) {
6405 LogPrint(0, LOG_SYSTEM, 0, "NewProcessTerminal: posix_openpt failed (%d) for '%s'", errno, cmdline);
6406 return 0;
6407 }
6408 if (grantpt(master) != 0 || unlockpt(master) != 0) {
6409 LogPrint(0, LOG_SYSTEM, 0, "NewProcessTerminal: grantpt/unlockpt failed (%d) for '%s'", errno, cmdline);
6410 close(master);
6411 return 0;
6412 }
6413 char slaveName[256];
6414 #if defined(__APPLE__)
6415 const char* sn = ptsname(master);
6416 if (!sn) { close(master); return 0; }
6417 strncpy(slaveName, sn, sizeof(slaveName) - 1);
6418 slaveName[sizeof(slaveName) - 1] = 0;
6419 #else
6420 if (ptsname_r(master, slaveName, sizeof(slaveName)) != 0) { close(master); return 0; }
6421 #endif
6422 struct winsize ws;
6423 memset(&ws, 0, sizeof(ws));
6424 ws.ws_col = cols ? cols : 80;
6425 ws.ws_row = rows ? rows : 25;
6426 ioctl(master, TIOCSWINSZ, &ws);
6427
6428 pid_t pid = fork();
6429 if (pid < 0) { close(master); return 0; }
6430 if (pid == 0) {
6431 // Child: new session so the PTY slave becomes its CONTROLLING terminal
6432 // (setsid also makes it a process-group leader => group kill via -pid).
6433 close(master);
6434 setsid();
6435 int slave = open(slaveName, O_RDWR); // first tty open after setsid acquires it
6436 if (slave < 0) _exit(127);
6437 #ifdef TIOCSCTTY
6438 ioctl(slave, TIOCSCTTY, 0); // explicit, for platforms that need it
6439 #endif
6440 dup2(slave, STDIN_FILENO);
6441 dup2(slave, STDOUT_FILENO);
6442 dup2(slave, STDERR_FILENO);
6443 if (slave > STDERR_FILENO) close(slave);
6444 if (initdir && *initdir && chdir(initdir) != 0) _exit(126);
6445 if (env) {
6446 std::map<std::string, std::string>::const_iterator ei = env->begin();
6447 while (ei != env->end()) { setenv(ei->first.c_str(), ei->second.c_str(), 1); ei++; }
6448 }
6450 execl("/bin/sh", "sh", "-c", cmdline, (char*)NULL);
6451 _exit(127);
6452 }
6453 // Parent: keep the master, non-blocking reads.
6454 fcntl(master, F_SETFL, fcntl(master, F_GETFL, 0) | O_NONBLOCK);
6455 if (!TerminalMasterMap)
6456 TerminalMasterMap = new std::map<uint32, int>;
6457 (*TerminalMasterMap)[(uint32)pid] = master;
6458 return (uint32)pid;
6459#endif
6460}
6461
6462bool ReadProcessTerminal(uint32 proc, std::string& out, bool& eofOut) {
6463 eofOut = false;
6464#if defined(WINDOWS)
6465 (void)proc; (void)out;
6466 return false; // stub until ConPTY (2.7e)
6467#else
6468 int fd = -1;
6469 if (!TerminalMasterFind(proc, fd)) return false;
6470 char buf[4096];
6471 for (;;) {
6472 ssize_t got = read(fd, buf, sizeof(buf));
6473 if (got > 0) { out.append(buf, (size_t)got); continue; }
6474 if (got == 0) { eofOut = true; break; } // clean EOF
6475 if (errno == EINTR) continue;
6476 if (errno == EAGAIN || errno == EWOULDBLOCK) break; // no data right now
6477 // EIO: the slave side is gone (child exited/hung up). On a PTY master
6478 // this is the NORMAL end-of-stream, not an error (Thor rc requirement:
6479 // callers still reap the real exit code via waitpid on the pid).
6480 eofOut = true;
6481 break;
6482 }
6483 return true;
6484#endif
6485}
6486
6487bool WriteProcessTerminal(uint32 proc, const char* data, uint32 len) {
6488#if defined(WINDOWS)
6489 (void)proc; (void)data; (void)len;
6490 return false; // stub until ConPTY (2.7e)
6491#else
6492 if (!data || !len) return false;
6493 int fd = -1;
6494 if (!TerminalMasterFind(proc, fd)) return false;
6495 uint32 written = 0;
6496 while (written < len) {
6497 ssize_t n = write(fd, data + written, len - written);
6498 if (n < 0) {
6499 if (errno == EINTR) continue;
6500 if (errno == EAGAIN || errno == EWOULDBLOCK) { Sleep(2); continue; }
6501 return false; // EIO (child gone) or other hard error
6502 }
6503 written += (uint32)n;
6504 }
6505 return true;
6506#endif
6507}
6508
6509bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows) {
6510#if defined(WINDOWS)
6511 (void)proc; (void)cols; (void)rows;
6512 return false; // stub until ConPTY (2.7e)
6513#else
6514 int fd = -1;
6515 if (!TerminalMasterFind(proc, fd)) return false;
6516 struct winsize ws;
6517 memset(&ws, 0, sizeof(ws));
6518 ws.ws_col = cols ? cols : 80;
6519 ws.ws_row = rows ? rows : 25;
6520 if (ioctl(fd, TIOCSWINSZ, &ws) != 0) return false;
6521 kill(-(pid_t)proc, SIGWINCH); // child leads its own group (setsid)
6522 return true;
6523#endif
6524}
6525
6526void CloseProcessTerminal(uint32 proc) {
6527#if defined(WINDOWS)
6528 (void)proc; // stub until ConPTY (2.7e)
6529#else
6530 if (!TerminalMasterMap) return;
6531 std::map<uint32, int>::iterator i = TerminalMasterMap->find(proc);
6532 if (i == TerminalMasterMap->end()) return;
6533 close(i->second); // hangup: child's foreground group gets SIGHUP
6534 TerminalMasterMap->erase(i);
6535#endif
6536}
6537
6538bool SendProcessBreak(uint32 proc, int sig) {
6539 #if defined WINDOWS
6540 (void)sig;
6541 // Requires the child to have been created with CREATE_NEW_PROCESS_GROUP.
6542 // The group id equals the child's process id.
6543 return (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, (DWORD)proc) != 0);
6544 #else
6545 return (kill((pid_t)proc, sig) == 0);
6546 #endif
6547}
6548
6549uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode) {
6550 #if defined WINDOWS
6551 DWORD exitcode;
6552 std::map<uint32, ProcessData*>::iterator i = ProcessInformationMap->find(proc);
6553 if (i != ProcessInformationMap->end()) {
6554 ProcessData* pData = i->second;
6555 if (WaitForSingleObject(pData->procInfo.hProcess, timeout) == WAIT_OBJECT_0) {
6556 if (GetExitCodeProcess(pData->procInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
6557 return PROC_RUNNING;
6558 }
6559 else {
6560 ProcessInformationMap->erase(i);
6561 CloseHandle(pData->procInfo.hProcess);
6562 CloseHandle(pData->procInfo.hThread);
6563 if (pData->hOutRead) CloseHandle(pData->hOutRead);
6564 if (pData->hErrRead) CloseHandle(pData->hErrRead);
6565 if (pData->hInWrite) CloseHandle(pData->hInWrite); // 2.7c stdin pipe
6566 if (pData->hJob) CloseHandle(pData->hJob); // 2.7c per-child job
6567 delete pData;
6568 returncode = exitcode;
6569 return PROC_TERMINATED;
6570 }
6571 }
6572 return PROC_TIMEOUT;
6573 }
6574 else {
6575 HANDLE hproc = OpenProcess(NULL, NULL, (DWORD)proc);
6576 if (!hproc) {
6577 return PROC_ERROR;
6578 }
6579 if (WaitForSingleObject(hproc, timeout) == WAIT_OBJECT_0) {
6580 if (GetExitCodeProcess(hproc, &exitcode) && (exitcode == STILL_ACTIVE)) {
6581 CloseHandle(hproc);
6582 return PROC_RUNNING;
6583 }
6584 else {
6585 returncode = exitcode;
6586 CloseHandle(hproc);
6587 return PROC_TERMINATED;
6588 }
6589 }
6590 else {
6591 CloseHandle(hproc);
6592 return PROC_RUNNING;
6593 }
6594 }
6595 #else
6596 uint64 start = GetTimeNow();
6597 do {
6598 if (GetProcessStatus(proc, returncode) < PROC_RUNNING)
6599 return PROC_TERMINATED;
6600 utils::Sleep(10);
6601 } while (GetTimeAgeMS(start) < timeout);
6602 return PROC_RUNNING;
6603
6604 #endif
6605}
6606
6607
6608
6609
6610
6611
6612
6613
6614
6616// DLL Libraries //
6618
6619bool SetCommandLine(int argc, char* argv[]) {
6620
6623
6624 std::string key;
6625 const char* val;
6626 int32 n;
6627 CommandLineInfo::CommandLineInfoSingleton->CommandLineString = CommandLineInfo::CommandLineInfoSingleton->CommandLineExec = argv[0];
6628 CommandLineInfo::CommandLineInfoSingleton->CommandLineItems.push_back(argv[0]);
6629 for (n=1; n<argc; n++) {
6630 CommandLineInfo::CommandLineInfoSingleton->CommandLineItems.push_back(argv[n]);
6631 key = argv[n];
6632 val = strchr(argv[n], '=');
6633 if (val)
6634 CommandLineInfo::CommandLineInfoSingleton->CommandLineArgs[key.substr(0, val-argv[n])] = val+1;
6635 CommandLineInfo::CommandLineInfoSingleton->CommandLineString += ' ';
6636 CommandLineInfo::CommandLineInfoSingleton->CommandLineString += argv[n];
6637 }
6638
6639 //printf("Full: '%s'\n", CommandLineString.c_str());
6640 //printf("Base: '%s'\n", CommandLineExec.c_str());
6641
6642 //n = 0;
6643 //std::vector<std::string>::iterator it = CommandLineItems.begin(), itEnd = CommandLineItems.end();
6644 //while (it != itEnd) {
6645 // printf("[%u] '%s'\n", n++, (*it).c_str());
6646 // it++;
6647 //}
6648
6649 //n = 0;
6650 //std::map<std::string, std::string>::iterator mit = CommandLineArgs.begin(), mitEnd = CommandLineArgs.end();
6651 //while (mit != mitEnd) {
6652 // printf("[%u] '%s' = '%s'\n", n++, mit->first.c_str(), mit->second.c_str());
6653 // mit++;
6654 //}
6655
6656 //printf("Executable: '%s' '%s'\n", GetCommandLinePath().c_str(), GetCommandLineExecutableOnly().c_str());
6657 return true;
6658}
6659
6660std::string GetCommandLine() {
6662 return "";
6663 return CommandLineInfo::CommandLineInfoSingleton->CommandLineString;
6664}
6665
6666std::string GetCommandLinePath() {
6668 return "";
6669 std::string::size_type p1 = CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.find_last_of('/');
6670 std::string::size_type p2 = CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.find_last_of('\\');
6671 if (p1 == std::string::npos) {
6672 if (p2 == std::string::npos)
6673 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec;
6674 else
6675 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr(0, p2+1);
6676 }
6677 else if (p2 == std::string::npos)
6678 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr(0, p1+1);
6679 else
6680 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr(0, (p1 > p2) ? p1+1 : p2+1);
6681}
6682
6685 return "";
6686 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec;
6687}
6688
6691 return "";
6692 std::string::size_type p1 = CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.find_last_of('/');
6693 std::string::size_type p2 = CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.find_last_of('\\');
6694 if (p1 == std::string::npos) {
6695 if (p2 == std::string::npos)
6696 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec;
6697 else
6698 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr(p2+1);
6699 }
6700 else if (p2 == std::string::npos)
6701 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr(p1+1);
6702 else
6703 return CommandLineInfo::CommandLineInfoSingleton->CommandLineExec.substr((p1 > p2) ? p1+1 : p2+1);
6704}
6705
6708 return 0;
6709 return (uint32)CommandLineInfo::CommandLineInfoSingleton->CommandLineItems.size();
6710}
6711
6712std::string GetCommandLineArg(uint16 n) {
6714 return "";
6715 return CommandLineInfo::CommandLineInfoSingleton->CommandLineItems[n];
6716}
6717
6718std::string GetCommandLineArg(const char* key) {
6720 return "";
6721 return CommandLineInfo::CommandLineInfoSingleton->CommandLineArgs[key];
6722}
6723
6724bool HasCommandLineArg(const char* key, std::string& value) {
6726 return false;
6727 std::map<std::string, std::string>::const_iterator it =
6728 CommandLineInfo::CommandLineInfoSingleton->CommandLineArgs.find(key);
6729 if (it == CommandLineInfo::CommandLineInfoSingleton->CommandLineArgs.end())
6730 return false;
6731 value = it->second;
6732 return true;
6733}
6734
6735
6736
6738 handle = NULL;
6739}
6741 if (handle) {
6742 #ifdef WINDOWS
6743 FreeLibrary(handle);
6744 #else // WINDOWS
6745 // dlclose() bug: https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=28625
6746 // __dso_handle unreferenced
6747 // if there are any globally desclared objects in the library!!!
6748 dlclose(handle);
6749 #endif // WINDOWS
6750 }
6751}
6752
6753std::string Library::patchLibraryFilename(const char* filename, const char* path) {
6754 #ifdef WINDOWS
6755 return filename;
6756 #else
6757 std::string realLibName;
6758 if (utils::TextEndsWith(filename, ".so"))
6759 realLibName = filename;
6760 else
6761 realLibName = utils::StringFormat("%s.so", filename);
6762
6763 // Start of the file name within the path. (This used to read
6764 // `(filenameStart = find_last_of('/') == npos)`, which assigns the comparison, so any
6765 // filename with a directory got start 1 and became "/libhome/.../Name.so": a
6766 // <library path=".."> could never load.)
6767 size_t slash = realLibName.find_last_of('/');
6768 int32 filenameStart = (slash == std::string::npos) ? 0 : (int32)(slash + 1);
6769
6770 if (!utils::TextStartsWith(realLibName.c_str() + filenameStart, "lib", true))
6771 realLibName.insert(filenameStart, "lib");
6772
6773 if (!filenameStart) {
6774 if (!path)
6775 realLibName.insert(0, "./");
6776 else
6777 realLibName.insert(0, path);
6778 }
6779
6780 return realLibName;
6781 #endif
6782}
6783
6784bool Library::load(const char* filename) {
6785 if (!filename)
6786 return false;
6787 std::string errorText;
6788 //printf("Trying to find library: '%s'...\n", filename);
6789
6790 #ifdef WINDOWS
6791 LPVOID lpMsgBuf; //Message Buffer
6792 #ifdef _DEBUG
6793 handle = LoadLibrary(utils::StringFormat("%sDebug", filename).c_str());
6794 if (handle == NULL) {
6795 FormatMessage(
6796 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6797 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
6798 (LPTSTR)&lpMsgBuf, 0, NULL);
6799 LogPrint(0, LOG_SYSTEM, 0, "Could not find or load debug library '%sDebug': %s", filename, lpMsgBuf);
6800 LocalFree(lpMsgBuf);
6801 return false;
6802 }
6803 #else
6804 handle = LoadLibrary(filename);
6805 if (handle == NULL) {
6806 FormatMessage(
6807 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6808 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
6809 (LPTSTR) &lpMsgBuf, 0, NULL);
6810 LogPrint(0, LOG_SYSTEM, 0, "Could not find or load library '%s': %s", filename, lpMsgBuf);
6811 LocalFree(lpMsgBuf);
6812 return false;
6813 }
6814 #endif
6815 #else // WINDOWS
6816 handle = 0;
6817 const char* dlErrorText;
6818 std::string realLibName = patchLibraryFilename(filename);
6819 //printf("Trying patched library: '%s'...\n", realLibName.c_str());
6820
6821 // clear errors
6822 dlerror();
6823 #ifdef _DEBUG
6824 std::string debugName = realLibName;
6825 utils::StringSingleReplace(debugName, ".so", "Debug.so", true);
6826 // printf("Trying debug library: '%s'...\n", debugName.c_str());
6827 handle = dlopen(debugName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6828 if (!handle) {
6829 dlErrorText = dlerror();
6830 // printf("Error 1: '%s'...\n", dlErrorText);
6831 if (dlErrorText && strlen(dlErrorText) &&
6832 !(strstr(dlErrorText, "No such file") && strstr(dlErrorText, debugName.c_str())))
6833 errorText = dlErrorText;
6834 }
6835 #endif
6836
6837 if (!handle && !errorText.size()) {
6838 // A filename with a directory (<library path="..">) is opened exactly where it says.
6839 // This dlopen had been commented out, so such libraries were never even tried in a
6840 // release build. Path-less names keep their old behaviour: the executable-directory
6841 // lookup below.
6842 if (strchr(filename, '/'))
6843 handle = dlopen(realLibName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6844 if (!handle) {
6845 dlErrorText = dlerror();
6846 // printf("Error 2: '%s'...\n", dlErrorText);
6847 if (dlErrorText && strlen(dlErrorText) &&
6848 !(strstr(dlErrorText, "No such file") && strstr(dlErrorText, realLibName.c_str())))
6849 errorText = dlErrorText;
6850 }
6851 }
6852
6853 if (!handle && !errorText.size() && !strchr(filename, '/')) {
6854 realLibName = patchLibraryFilename(filename, utils::GetCommandLinePath().c_str());
6855 // printf("Trying library: '%s'...\n", realLibName.c_str());
6856 handle = dlopen(realLibName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6857 if (!handle) {
6858 dlErrorText = dlerror();
6859 // printf("Error 3: '%s'...\n", dlErrorText);
6860 if (dlErrorText && strlen(dlErrorText) &&
6861 !(strstr(dlErrorText, "No such file") && strstr(dlErrorText, realLibName.c_str())))
6862 errorText = dlErrorText;
6863 }
6864 }
6865
6866 if (handle == NULL) {
6867 if (errorText.size())
6868 LogPrint(0, LOG_SYSTEM, 0, "Could not load library file '%s': %s", realLibName.c_str(), errorText.c_str());
6869 else
6870 LogPrint(0, LOG_SYSTEM, 0, "Could not find library file '%s'", filename);
6871 return false;
6872 }
6873 #endif // WINDOWS
6874 return true;
6875}
6876
6878 if (handle == NULL)
6879 return NULL;
6880 if (!strlen(funcName))
6881 return NULL;
6882
6883 LibraryFunction func;
6884
6885 #ifdef WINDOWS
6886 func = (LibraryFunction)GetProcAddress(handle, funcName);
6887 if (func == NULL) {
6888 LPVOID lpMsgBuf; //Message Buffer
6889 //Generate Error Message from GetLastError
6890 FormatMessage(
6891 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6892 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
6893 (LPTSTR) &lpMsgBuf, 0, NULL);
6894 LogPrint(0, LOG_SYSTEM, 0, "Could not find library function: %s: %s", funcName, lpMsgBuf);
6895 // Free the buffer.
6896 LocalFree(lpMsgBuf);
6897 return NULL;
6898 }
6899 #else // WINDOWS
6900 const char* errmsg;
6901 dlerror();
6902 func = (LibraryFunction)dlsym(handle, funcName);
6903 errmsg = dlerror();
6904 if (errmsg != NULL) {
6905 LogPrint(0, LOG_SYSTEM, 0, "Could not find library function: %s: %s", (char*) funcName, (char*) errmsg);
6906 return NULL;
6907 }
6908 #endif // WINDOWS
6909 return func;
6910}
6911
6912Library* OpenLibrary(const char* libName) {
6913 Library* lib = new Library();
6914 if (!lib->load(libName)) {
6915 delete(lib);
6916 return NULL;
6917 }
6918 return lib;
6919}
6920
6921
6923// OS System //
6925
6926char OSLocalHostName[1024] = {0};
6927char OSArchitectureName[1024] = {0};
6928char OSName[1024] = {0};
6929
6930const char* GetComputerName() {
6931 //char name[1024];
6932 char* name = new char[1024];
6933 if (strlen(OSLocalHostName) == 0) {
6934 #ifdef WINDOWS
6935
6936 DWORD size = 1024;
6937 #ifdef POCKETPC
6938 delete [] name;
6939 return "PocketPC";
6940 #else
6941 if (::GetComputerName(name, &size) == 0) {
6942 delete [] name;
6943 return "";
6944 }
6945 else
6946 utils::strcpyavail(OSLocalHostName, name, 1024, true);
6947 #endif
6948
6949 //if (gethostname(name, 1024) == 0)
6950 // strcpy(OSLocalHostName, name);
6951 //else {
6952 // int er = WSAGetLastError();
6953 // if (er == WSANOTINITIALISED) {
6954 // WSADATA info;
6955 // if (WSAStartup(MAKEWORD(1,1), &info) == 0) {
6956 // // Now we can retry the socket() function
6957 // if (gethostname(hname, 1000) == 0)
6958 // strcpy(OSLocalHostName, name);
6959 // }
6960 // }
6961 //}
6962 #else
6963 std::string outString, errString;
6964 if (!RunOSCommand("uname -n", NULL, 1000, outString, errString)) {
6965 //if (!RunOSTextCommand("uname -n", name, size))
6966 delete [] name;
6967 return "";
6968 }
6969 else
6970 utils::strcpyavail(OSLocalHostName, outString.c_str(), 1024, true);
6971 #endif // WINDOWS
6972 }
6973 delete [] name;
6974 return OSLocalHostName;
6975}
6976
6978
6979 #if defined WINDOWS
6980 HANDLE hProcess = GetCurrentProcess();
6981 PROCESS_MEMORY_COUNTERS pmc;
6982 if (hProcess == NULL)
6983 return 0;
6984 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) != 0)
6985 return (uint64)pmc.WorkingSetSize;
6986 else
6987 return 0;
6988 #elif defined OSX
6989 struct task_basic_info_64 info;
6990 mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
6991 if (task_info(mach_task_self(), TASK_BASIC_INFO_64, (task_info_t)&info, &count) == KERN_SUCCESS)
6992 return (uint64)info.resident_size;
6993 return 0;
6994 #else
6995 /* Linux ---------------------------------------------------- */
6996 long rss = 0L;
6997 FILE* fp = NULL;
6998 if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
6999 return (uint64)0L; /* Can't open? */
7000 if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) {
7001 fclose( fp );
7002 return (uint64)0L; /* Can't read? */
7003 }
7004 fclose( fp );
7005 return (uint64)rss * (uint64)sysconf( _SC_PAGESIZE);
7006 #endif
7007}
7008
7010
7011 #if defined WINDOWS
7012 HANDLE hProcess = GetCurrentProcess();
7013 PROCESS_MEMORY_COUNTERS pmc;
7014 if (hProcess == NULL)
7015 return 0;
7016 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) != 0)
7017 return (uint64)pmc.PeakWorkingSetSize;
7018 else
7019 return 0;
7020 #elif defined OSX
7021 // macOS/BSD: ru_maxrss is in bytes (Linux uses KB)
7022 struct rusage usage;
7023 getrusage(RUSAGE_SELF, &usage);
7024 return (uint64)usage.ru_maxrss;
7025 #else
7026 // Linux: ru_maxrss is in KB
7027 struct rusage usage;
7028 getrusage( RUSAGE_SELF, &usage );
7029 return ((uint64)usage.ru_maxrss) * 1024L;
7030
7031
7033 //struct psinfo psinfo;
7034 //int fd = -1;
7035 //if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 )
7036 // return (size_t)0L; /* Can't open? */
7037 //if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) )
7038 //{
7039 // close( fd );
7040 // return (size_t)0L; /* Can't read? */
7041 //}
7042 //close( fd );
7043 //return (size_t)(psinfo.pr_rssize * 1024L);
7044
7045 #endif
7046}
7047
7048
7049uint16 GetCPUCount() {
7050 #if defined WINDOWS
7051 SYSTEM_INFO siSysInfo;
7052 GetSystemInfo(&siSysInfo);
7053 return (uint16) siSysInfo.dwNumberOfProcessors;
7054 #elif defined OSX
7055 int ncpu = 0;
7056 size_t len = sizeof(ncpu);
7057 if (sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0) == 0 && ncpu > 0)
7058 return (uint16)(ncpu > 65535 ? 65535 : ncpu);
7059 return 0;
7060 #else
7061 long n = sysconf(_SC_NPROCESSORS_ONLN);
7062 if (n > 0)
7063 return (uint16)(n > 65535 ? 65535 : (uint16)n);
7064 return 0;
7065 #endif
7066}
7067
7069 #if defined WINDOWS
7070 SYSTEM_INFO siSysInfo;
7071 GetSystemInfo(&siSysInfo);
7072 switch(siSysInfo.wProcessorArchitecture) {
7073 case PROCESSOR_ARCHITECTURE_AMD64:
7074 return OSCPU_AMD64;
7075 case PROCESSOR_ARCHITECTURE_IA64:
7076 return OSCPU_IA64;
7077 case PROCESSOR_ARCHITECTURE_INTEL:
7078 return OSCPU_X86;
7079 default:
7080 return OSCPU_UNKNOWN;
7081 }
7082 #elif defined OSX
7083 #if defined(__x86_64__)
7084 return OSCPU_AMD64;
7085 #elif defined(__i386__)
7086 return OSCPU_X86;
7087 #elif defined(__aarch64__)
7088 return OSCPU_UNKNOWN;
7089 #else
7090 return OSCPU_UNKNOWN;
7091 #endif
7092 #else
7093 #if defined(__x86_64__)
7094 return OSCPU_AMD64;
7095 #elif defined(__i386__)
7096 return OSCPU_X86;
7097 #elif defined(__aarch64__)
7098 return OSCPU_UNKNOWN;
7099 #else
7100 return OSCPU_UNKNOWN;
7101 #endif
7102 #endif
7103}
7104
7105uint64 GetCPUSpeed() {
7106 #if defined WINDOWS
7107 //HKEY hKey;
7108 //LONG lRet;
7109
7110 // Test for SP6 versus SP6a.
7111 //JString key = "HARDWARE\\DESCRIPTION\\SYSTEM\\CentralProcessor\\0";
7112 //lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &hKey );
7113 //if( lRet == ERROR_SUCCESS ) {
7114 // DWORD len = sizeof(int);
7115 // BYTE data[sizeof(int)];
7116 // key = "~MHz";
7117 // lRet = RegQueryValueEx(hKey, key, NULL, NULL, data, &len);
7118 // if (lRet == ERROR_SUCCESS) {
7119 // RegCloseKey(hKey);
7120 // return (uint64) (data[3] << 24) + (data[2] << 16) + (data[1] << 8) + (data[0] << 0);
7121 // }
7122 // else {
7123 // RegCloseKey(hKey);
7124 // return 0;
7125 // }
7126 //}
7127 #elif defined OSX
7128 uint64 freq = 0;
7129 size_t len = sizeof(freq);
7130 if (sysctlbyname("hw.cpufrequency", &freq, &len, NULL, 0) == 0)
7131 return freq;
7132 return 0;
7133 #else
7134 // Linux: optional /proc/cpuinfo cpu MHz
7135 std::ifstream cpuinfo("/proc/cpuinfo");
7136 std::string line;
7137 while (cpuinfo && getline(cpuinfo, line)) {
7138 if (line.compare(0, 7, "cpu MHz") == 0) {
7139 size_t colon = line.find(':');
7140 if (colon != std::string::npos) {
7141 double mhz = 0;
7142 if (sscanf(line.c_str() + colon + 1, "%lf", &mhz) == 1 && mhz > 0)
7143 return (uint64)(mhz * 1000000.0);
7144 }
7145 break;
7146 }
7147 }
7148 #endif
7149 return 0;
7150}
7151
7153 #if defined WINDOWS
7154 MEMORYSTATUS memstat;
7155 GlobalMemoryStatus(&memstat);
7156 return (uint64)memstat.dwTotalPhys;
7157 #else
7158 #ifdef __APPLE__
7159 uint64 memsize = 0;
7160 size_t len = sizeof(memsize);
7161 if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0)
7162 return memsize;
7163 return 0;
7164 #else
7165 struct sysinfo info;
7166 if (sysinfo(&info) == 0)
7167 return info.totalram;
7168 else
7169 return 0;
7170 #endif
7171 #endif
7172 return 0;
7173}
7174
7175bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM) {
7176 #if defined WINDOWS
7177 MEMORYSTATUSEX memstat;
7178 memset(&memstat, 0, sizeof(MEMORYSTATUSEX));
7179 memstat.dwLength = sizeof(MEMORYSTATUSEX);
7180 if (!GlobalMemoryStatusEx(&memstat)) {
7181 int a = GetLastError();
7182 return false;
7183 }
7184 totalRAM = (uint64)memstat.ullTotalPhys;
7185 freeRAM = (uint64)memstat.ullAvailPhys;
7186 return true;
7187 #else
7188 #ifdef __APPLE__
7189 uint64 memsize = 0;
7190 size_t len = sizeof(memsize);
7191 if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) != 0)
7192 return false;
7193 totalRAM = memsize;
7194 vm_statistics64_data_t vm_stat;
7195 mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
7196 if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) != KERN_SUCCESS)
7197 return false;
7198 vm_size_t page_size;
7199 if (host_page_size(mach_host_self(), &page_size) != KERN_SUCCESS)
7200 return false;
7201 freeRAM = (uint64)vm_stat.free_count * (uint64)page_size;
7202 return true;
7203 #else
7204 struct sysinfo info;
7205 if (sysinfo(&info) == 0) {
7206 totalRAM = info.totalram;
7207 freeRAM = info.freeram;
7208 return true;
7209 }
7210 else
7211 return false;
7212 #endif
7213 #endif
7214}
7215
7217 if (strlen(OSArchitectureName) == 0) {
7218 #if defined WINDOWS
7219 SYSTEM_INFO siSysInfo;
7220 GetSystemInfo(&siSysInfo);
7221
7222 switch(siSysInfo.wProcessorArchitecture) {
7223 case PROCESSOR_ARCHITECTURE_UNKNOWN:
7224 utils::strcpyavail(OSArchitectureName, "i386", 1024, true);
7225 case PROCESSOR_ARCHITECTURE_INTEL:
7226 switch(siSysInfo.wProcessorLevel) {
7227 case 3:
7228 utils::strcpyavail(OSArchitectureName, "i386", 1024, true);
7229 break;
7230 case 4:
7231 utils::strcpyavail(OSArchitectureName, "i486", 1024, true);
7232 break;
7233 case 5:
7234 utils::strcpyavail(OSArchitectureName, "i586", 1024, true);
7235 break;
7236 case 6:
7237 utils::strcpyavail(OSArchitectureName, "i686", 1024, true);
7238 break;
7239 case 7:
7240 utils::strcpyavail(OSArchitectureName, "i786", 1024, true);
7241 break;
7242 case 8:
7243 utils::strcpyavail(OSArchitectureName, "i886", 1024, true);
7244 break;
7245 case 9:
7246 utils::strcpyavail(OSArchitectureName, "i986", 1024, true);
7247 break;
7248 default:
7249 utils::strcpyavail(OSArchitectureName, "i686", 1024, true);
7250 break;
7251 }
7252 case PROCESSOR_ARCHITECTURE_MIPS:
7253 utils::strcpyavail(OSArchitectureName, "mips", 1024, true);
7254 break;
7255 case PROCESSOR_ARCHITECTURE_ALPHA:
7256 utils::strcpyavail(OSArchitectureName, "alpha", 1024, true);
7257 break;
7258 case PROCESSOR_ARCHITECTURE_PPC:
7259 utils::strcpyavail(OSArchitectureName, "ppc", 1024, true);
7260 break;
7261 case PROCESSOR_ARCHITECTURE_IA64:
7262 utils::strcpyavail(OSArchitectureName, "ia64", 1024, true);
7263 break;
7264 case PROCESSOR_ARCHITECTURE_AMD64:
7265 utils::strcpyavail(OSArchitectureName, "amd64", 1024, true);
7266 break;
7267 default:
7268 break;
7269 }
7270 #else
7271 // ######################################
7272 #endif
7273 }
7274 return OSArchitectureName;
7275}
7276
7277const char* GetSystemOSName() {
7278 if (strlen(OSName) == 0) {
7279 #if defined WINDOWS
7280 #ifdef POCKETPC
7281 utils::strcpyavail(OSName, "Microsoft PocketPC", 1024, true);
7282 #else
7283 switch(GetCPUArchitecture()) {
7284 case OSCPU_AMD64:
7285 utils::strcpyavail(OSName, "Microsoft Windows X64", 1024, true);
7286 break;
7287 case OSCPU_IA64:
7288 utils::strcpyavail(OSName, "Microsoft Windows IA64", 1024, true);
7289 break;
7290 case OSCPU_X86:
7291 utils::strcpyavail(OSName, "Microsoft Windows X86", 1024, true);
7292 break;
7293 default:
7294 utils::strcpyavail(OSName, "Microsoft Windows", 1024, true);
7295 break;
7296 }
7297 #endif
7298 #else
7299 // ######################################
7300 #endif
7301 }
7302 return OSName;
7303}
7304
7305bool GetSystemOSVersion(uint16& major, uint16& minor, uint16& build, char* text, uint16 textSize) {
7306 major = 0;
7307 minor = 0;
7308 build = 0;
7309 text[0] = 0;
7310 #if defined WINDOWS
7311 #ifdef POCKETPC
7312
7313 OSVERSIONINFO osvi;
7314 BOOL bOsVersionInfoEx;
7315
7316 // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
7317 // If that fails, try using the OSVERSIONINFO structure.
7318
7319 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
7320 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
7321
7322 if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
7323 {
7324 osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7325 if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
7326 return false;
7327 }
7328
7329 major = osvi.dwMajorVersion;
7330 minor = osvi.dwMinorVersion;
7331 if (strlen((char*)osvi.szCSDVersion) < textSize)
7332 utils::strcpyavail(text, (char*)osvi.szCSDVersion, textSize, true);
7333 #else
7334
7335 OSVERSIONINFOEX osvi;
7336 BOOL bOsVersionInfoEx;
7337
7338 // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
7339 // If that fails, try using the OSVERSIONINFO structure.
7340
7341 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
7342 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
7343
7344 if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
7345 {
7346 osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7347 if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
7348 return false;
7349 }
7350
7351 switch (osvi.dwPlatformId)
7352 {
7353 // Test for the Windows NT product family.
7354 case VER_PLATFORM_WIN32_NT:
7355
7356 // Display service pack (if any) and build number.
7357
7358 if( osvi.dwMajorVersion == 4 &&
7359 lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 )
7360 {
7361 HKEY hKey;
7362 LONG lRet;
7363
7364 // Test for SP6 versus SP6a.
7365 lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
7366 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
7367 0, KEY_QUERY_VALUE, &hKey );
7368 if( lRet == ERROR_SUCCESS ) {
7369 if (textSize > 16)
7370 utils::strcpyavail(text, "Service Pack 6a", textSize, true);
7371 build = osvi.dwBuildNumber & 0xFFFF;
7372 }
7373 else // Windows NT 4.0 prior to SP6a
7374 {
7375 major = (uint16)osvi.dwMajorVersion;
7376 minor = (uint16)osvi.dwMinorVersion;
7377 build = (uint16)osvi.dwBuildNumber & 0xFFFF;
7378 if (strlen((char*)osvi.szCSDVersion) < textSize)
7379 utils::strcpyavail(text, (char*)osvi.szCSDVersion, textSize, true);
7380 }
7381 RegCloseKey( hKey );
7382 }
7383 else // Windows NT 3.51 and earlier or Windows 2000 and later
7384 {
7385 major = (uint16)osvi.dwMajorVersion;
7386 minor = (uint16)osvi.dwMinorVersion;
7387 build = (uint16)osvi.dwBuildNumber & 0xFFFF;
7388
7389 if (strlen((char*)osvi.szCSDVersion) < textSize)
7390 utils::strcpyavail(text, (char*)osvi.szCSDVersion, textSize, true);
7391 }
7392 break;
7393 }
7394
7395 #endif
7396 #else
7397 // ######################################
7398 #endif
7399 return true;
7400}
7401
7402//bool RunOSTextCommand(const char* cmd, char** result, uint32 size) {
7403//
7404// #ifdef WINDOWS
7405// // Use RunOSCommand instead
7406// return false;
7407// #else
7408// fflush(stdin);
7409// fflush(stdout);
7410// FILE* runfile = popen(cmd, "r");
7411// if (runfile == NULL)
7412// return false;
7413//
7414// int res;
7415// int size = 4096;
7416// char buffer[size+1];
7417// std::string output;
7418//
7419// res = fread(buffer, 1, size, runfile);
7420// if (res <= 0) {
7421// pclose(runfile);
7422// return false;
7423// }
7424// do {
7425// buffer[res] = 0;
7426// output += buffer;
7427// } while (res = fread(buffer, 1, size, runfile));
7428//
7429// pclose(runfile);
7430// delete [] buffer;
7431// *result = new char[output.length()+1];
7432// memcpy(*result, output.c_str(), output.length());
7433// result[output.length()] = 0;
7434// return true;
7435// #endif
7436//}
7437
7438//bool GetSystemName(uint32 id, const char* title, char* name, uint32 size) {
7439// if ( (name == NULL) || (size < 64) )
7440// return false;
7441// memset(name, 0, 64);
7442// uint32 pos = 0;
7443// #ifdef WINDOWS
7444// strcpy_s(name, size, "Global\\");
7445// strcpy_s(name+(pos = (uint32)strlen(name)), size-pos, title);
7446// // _itoa_s(id, name+(pos = (uint32)strlen(name)), size-pos, 16);
7447// #else
7448// strncpy(name, "/", size);
7449// pos = (uint32)strlen(name);
7450// strncpy(name+pos, title, size-pos);
7451// #endif
7452// Int2Ascii((int32)id, name+(pos = (uint32)strlen(name)), size-pos, 16);
7453// return true;
7454//}
7455
7456char* Int2Ascii(int64 value, char* result, uint16 size, uint8 base) {
7457 if (base < 2 || base > 36) {
7458 result[0] = 0;
7459 return result;
7460 }
7461
7462 char* ptr = result, *ptr1 = result, tmp_char;
7463 int64 tmp_value;
7464
7465 do {
7466 tmp_value = value;
7467 value /= base;
7468 *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
7469 } while ( value );
7470
7471 // Apply negative sign
7472 if (tmp_value < 0)
7473 *ptr++ = '-';
7474 *ptr-- = '\0';
7475 while(ptr1 < ptr) {
7476 tmp_char = *ptr;
7477 *ptr--= *ptr1;
7478 *ptr1++ = tmp_char;
7479 }
7480 return result;
7481}
7482
7483char* Uint2Ascii(uint64 value, char* result, uint16 size, uint8 base) {
7484 if (base < 2 || base > 36) {
7485 result[0] = 0;
7486 return result;
7487 }
7488
7489 char* ptr = result, *ptr1 = result, tmp_char;
7490 int64 tmp_value;
7491
7492 do {
7493 tmp_value = value;
7494 value /= base;
7495 *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
7496 } while ( value );
7497
7498 *ptr-- = '\0';
7499 while(ptr1 < ptr) {
7500 tmp_char = *ptr;
7501 *ptr--= *ptr1;
7502 *ptr1++ = tmp_char;
7503 }
7504 return result;
7505}
7506
7507unsigned char* Ascii2UTF16LE(const char* ascii, uint32 len, uint32& size) {
7508 size = (len * 2) + 4;
7509 unsigned char* result = new unsigned char[size];
7510 result[0] = 0xff;
7511 result[1] = 0xfe;
7512 uint32 i = 2;
7513 const char* src = ascii;
7514 for (uint32 n = 0; n < len; n++) {
7515 result[i++] = *src;
7516 result[i++] = 0;
7517 src++;
7518 }
7519 result[i++] = 0;
7520 result[i++] = 0;
7521 size = (len * 2) + 2;
7522 return result;
7523}
7524
7525
7526bool GetSocketError(int error, char* errorString, uint16 errorStringMaxSize, bool* isRecoverable) {
7527
7528 if (errorStringMaxSize < 128)
7529 return false;
7530
7531 #ifdef WINDOWS
7532
7533 if (error == WSANOTINITIALISED) {
7534 utils::strcpyavail(errorString, "Cannot initialize WinSock!", errorStringMaxSize, true);
7535 *isRecoverable = false;
7536 }
7537 else if (error == WSAENETDOWN) {
7538 utils::strcpyavail(errorString, "The network subsystem or the associated service provider has failed", errorStringMaxSize, true);
7539 *isRecoverable = false;
7540 }
7541 else if (error == WSAEAFNOSUPPORT) {
7542 utils::strcpyavail(errorString, "The specified address family is not supported", errorStringMaxSize, true);
7543 *isRecoverable = false;
7544 }
7545 else if (error == WSAEINPROGRESS) {
7546 utils::strcpyavail(errorString, "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function", errorStringMaxSize, true);
7547 *isRecoverable = true;
7548 }
7549 else if (error == WSAEMFILE) {
7550 utils::strcpyavail(errorString, "No more socket descriptors are available", errorStringMaxSize, true);
7551 *isRecoverable = false;
7552 }
7553 else if (error == WSAENOBUFS) {
7554 utils::strcpyavail(errorString, "No buffer space is available. The socket cannot be created", errorStringMaxSize, true);
7555 *isRecoverable = false;
7556 }
7557 else if (error == WSAEPROTONOSUPPORT) {
7558 utils::strcpyavail(errorString, "The specified protocol is not supported", errorStringMaxSize, true);
7559 *isRecoverable = false;
7560 }
7561 else if (error == WSAEPROTOTYPE) {
7562 utils::strcpyavail(errorString, "The specified protocol is the wrong type for this socket", errorStringMaxSize, true);
7563 *isRecoverable = false;
7564 }
7565 else if (error == WSAESOCKTNOSUPPORT) {
7566 utils::strcpyavail(errorString, "The specified socket type is not supported in this address family", errorStringMaxSize, true);
7567 *isRecoverable = false;
7568 }
7569 else if (error == WSAEADDRINUSE) {
7570 utils::strcpyavail(errorString, "The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs during execution of the bind function, but could be delayed until this function if the bind was to a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be committed at the time of this function", errorStringMaxSize, true);
7571 *isRecoverable = false;
7572 }
7573 else if (error == WSAEINVAL) {
7574 utils::strcpyavail(errorString, "The socket has not been bound with bind", errorStringMaxSize, true);
7575 *isRecoverable = false;
7576 }
7577 else if (error == WSAEISCONN) {
7578 utils::strcpyavail(errorString, "The socket is already connected", errorStringMaxSize, true);
7579 *isRecoverable = false;
7580 }
7581 else if (error == WSAENOTSOCK) {
7582 utils::strcpyavail(errorString, "The descriptor is not a socket", errorStringMaxSize, true);
7583 *isRecoverable = false;
7584 }
7585 else if (error == WSAEOPNOTSUPP) {
7586 utils::strcpyavail(errorString, "The referenced socket is not of a type that supports the listen operation", errorStringMaxSize, true);
7587 *isRecoverable = false;
7588 }
7589 else if (error == WSAEADDRNOTAVAIL) {
7590 utils::strcpyavail(errorString, "The specified address is not a valid address for this machine", errorStringMaxSize, true);
7591 *isRecoverable = false;
7592 }
7593 else if (error == WSAEFAULT) {
7594 utils::strcpyavail(errorString, "The name or namelen parameter is not a valid part of the user address space", errorStringMaxSize, true);
7595 *isRecoverable = false;
7596 }
7597 else if (error == WSAEMFILE) {
7598 utils::strcpyavail(errorString, "The queue is nonempty upon entry to accept and there are no descriptors available", errorStringMaxSize, true);
7599 *isRecoverable = false;
7600 }
7601 else if (error == WSAEWOULDBLOCK) {
7602 utils::strcpyavail(errorString, "The socket is marked as nonblocking and no connections are present to be accepted", errorStringMaxSize, true);
7603 *isRecoverable = false;
7604 }
7605 else if (error == WSAETIMEDOUT) {
7606 utils::strcpyavail(errorString, "Attempt to connect timed out without establishing a connection", errorStringMaxSize, true);
7607 *isRecoverable = false;
7608 }
7609 else if (error == WSAENETUNREACH) {
7610 utils::strcpyavail(errorString, "The network cannot be reached from this host at this time", errorStringMaxSize, true);
7611 *isRecoverable = false;
7612 }
7613 else if (error == WSAEISCONN) {
7614 utils::strcpyavail(errorString, "The socket is already connected (connection-oriented sockets only)", errorStringMaxSize, true);
7615 *isRecoverable = false;
7616 }
7617 else if (error == WSAECONNREFUSED) {
7618 utils::strcpyavail(errorString, "The attempt to connect was forcefully rejected", errorStringMaxSize, true);
7619 *isRecoverable = false;
7620 }
7621 else if (error == WSAEAFNOSUPPORT) {
7622 utils::strcpyavail(errorString, "Addresses in the specified family cannot be used with this socket", errorStringMaxSize, true);
7623 *isRecoverable = false;
7624 }
7625 else if (error == WSAEADDRNOTAVAIL) {
7626 utils::strcpyavail(errorString, "The remote address is not a valid address (such as ADDR_ANY)", errorStringMaxSize, true);
7627 *isRecoverable = false;
7628 }
7629 else if (error == WSAEALREADY) {
7630 utils::strcpyavail(errorString, "A nonblocking connect call is in progress on the specified socket", errorStringMaxSize, true);
7631 *isRecoverable = false;
7632 }
7633 else if (error == WSAECONNRESET) {
7634 utils::strcpyavail(errorString, "Connection was reset", errorStringMaxSize, true);
7635 *isRecoverable = false;
7636 }
7637 else if (error == WSAECONNABORTED) {
7638 utils::strcpyavail(errorString, "Software caused connection abort", errorStringMaxSize, true);
7639 *isRecoverable = false;
7640 }
7641 else {
7642 snprintf(errorString, errorStringMaxSize, "TCP error with no description: %d", error);
7643 *isRecoverable = false;
7644 }
7645
7646 return true;
7647 #else
7648 if (error == 100) {
7649 utils::strcpyavail(errorString, "Cannot initialise socket", errorStringMaxSize, true);
7650 *isRecoverable = false;
7651 }
7652 else {
7653 utils::strcpyavail(errorString, strerror(error), errorStringMaxSize, true);
7654 *isRecoverable = false;
7655 }
7656
7657 return true;
7658 #endif
7659}
7660
7661
7663 #ifdef WINDOWS
7664 int err = WSAGetLastError();
7665 WSASetLastError(0);
7666 return err;
7667 #else
7668 return errno;
7669 #endif
7670}
7671
7673 #ifdef WINDOWS
7674 LPVOID lpMsgBuf; //Message Buffer
7675 DWORD error = GetLastError();
7676 uint32 len = FormatMessage(
7677 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
7678 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
7679 (LPTSTR) &lpMsgBuf, 0, NULL);
7680 std::string str = (char*)lpMsgBuf;
7681 LocalFree(lpMsgBuf);
7682 return str;
7683 #else
7684 return utils::StringFormat("Error number: %u", errno);
7685 #endif
7686}
7687
7688bool WaitForSocketWriteability(SOCKET s, int32 timeout) {
7689
7690 int maxfd = 0;
7691
7692 // If socket is not valid return true so the next read will report the error
7693 if (s == INVALID_SOCKET) return true;
7694
7695 struct timeval tv;
7696 tv.tv_sec = 0;
7697 tv.tv_usec = 0;
7698
7699 fd_set wds;
7700 // create a list of sockets to check for activity
7701 FD_ZERO(&wds);
7702 // specify mySocket
7703 FD_SET(s, &wds);
7704
7705 #ifdef WINDOWS
7706 #else
7707 maxfd = s + 1;
7708 #endif
7709
7710 if (timeout > 0) {
7711 ldiv_t d = ldiv(timeout*1000, 1000000);
7712 tv.tv_sec = d.quot;
7713 tv.tv_usec = d.rem;
7714 }
7715
7716 // Check for readability
7717 return( select(maxfd, NULL, &wds, NULL, &tv) > 0);
7718}
7719
7720bool WaitForSocketReadability(SOCKET s, int32 timeout) {
7721
7722 int maxfd = 0;
7723
7724 // If socket is not valid return true so the next read will report the error
7725 if (s == INVALID_SOCKET) return true;
7726
7727 struct timeval tv;
7728 tv.tv_sec = 0;
7729 tv.tv_usec = 0;
7730
7731 fd_set rdds;
7732 // create a list of sockets to check for activity
7733 FD_ZERO(&rdds);
7734 // specify mySocket
7735 FD_SET(s, &rdds);
7736
7737 #ifdef WINDOWS
7738 #else
7739 maxfd = s + 1;
7740 #endif
7741
7742 if (timeout > 0) {
7743 ldiv_t d = ldiv(timeout*1000, 1000000);
7744 tv.tv_sec = d.quot;
7745 tv.tv_usec = d.rem;
7746 }
7747
7748 // Check for readability
7749// uint64 t2 = GetTimeNow();
7750 int ret = select(maxfd, &rdds, NULL, NULL, &tv);
7751 //if (GetTimeAge(t2) > 1000) {
7752// LogPrint(0,LOG_NETWORK,0,"************** WaitForSocketReadability(%d) took %s ******************", s, PrintTimeDifString(GetTimeAge(t2)).c_str());
7753 //}
7754 return(ret > 0);
7755}
7756
7758 #if defined(WINDOWS)
7759 unsigned long parm = 1; // 1 = Non-blocking, 0 = Blocking
7760 ioctlsocket(s, FIONBIO, &parm);
7761 #else
7762 long parm = fcntl(s, F_GETFL);
7763 parm |= O_NONBLOCK;
7764 fcntl(s, F_SETFL, parm);
7765 #endif
7766 return true;
7767}
7768
7770 #if defined(WINDOWS)
7771 unsigned long parm = 0; // 1 = Non-blocking, 0 = Blocking
7772 ioctlsocket(s, FIONBIO, &parm);
7773 #else
7774 long parm = fcntl(s, F_GETFL);
7775 parm &= ~O_NONBLOCK;
7776 fcntl(s, F_SETFL, parm);
7777 #endif
7778 return true;
7779}
7780
7781bool LookupIPAddress(const char* name, uint32& address) {
7783 if ( (name == NULL) || (strlen(name) == 0) )
7784 return false;
7785
7786 // struct hostent* hent;
7787
7788 #ifdef WINDOWS
7789 //hent = gethostbyname(name);
7790 //if (hent == NULL)
7791 // return false;
7792 //else {
7793 // memcpy(&address, hent->h_addr_list[0], sizeof(address));
7794 // printf("IP1 of %s = %u.%u.%u.%u (%u)\n", name, GETIPADDRESSQUAD(address), address);
7795 // //return true;
7796 //}
7797
7798 //uint32 address2 = 0;
7799 struct addrinfo hints, *res;
7800 int error = -1;
7801 const char *cause = NULL;
7802
7803 memset(&hints, 0, sizeof(hints));
7804 //do not set to AI_NUMERICHOST, causes issues with connections...
7805 //hints.ai_flags = AI_NUMERICHOST; // AI_PASSIVE
7806 hints.ai_family = AF_INET;
7807 hints.ai_socktype = SOCK_STREAM;
7808 hints.ai_protocol = IPPROTO_TCP;
7809 __try {
7810 error = getaddrinfo(name, NULL, &hints, &res);
7811 }
7812 __except (EXCEPTION_CONTINUE_EXECUTION) {
7813 error = -1;
7814 }
7815
7816 if (!error) {
7817 memcpy(&address, res->ai_addr->sa_data + 2, sizeof(address));
7818 //printf("IP2 of %s = %u.%u.%u.%u (%u)\n", name, GETIPADDRESSQUAD(address), address);
7819 freeaddrinfo(res);
7820 return true;
7821 }
7822 else
7823 return false;
7824
7825
7826 #else
7827 struct addrinfo hints, *res;
7828 int error;
7829 const char *cause = NULL;
7830
7831 memset(&hints, 0, sizeof(hints));
7832 // hints.ai_flags = AI_NUMERICHOST; // AI_PASSIVE
7833 hints.ai_family = PF_UNSPEC;
7834 hints.ai_socktype = SOCK_STREAM;
7835 error = getaddrinfo(name, NULL, &hints, &res);
7836 if (!error) {
7837 memcpy(&address, res->ai_addr->sa_data+2, 4);
7838 freeaddrinfo(res);
7839 return true;
7840 }
7841 else
7842 return false;
7843 #endif // WINDOWS
7844}
7845
7846#ifdef WINDOWS
7847 bool IsNetworkInitialised = false;
7848 bool CheckNetworkInit() {
7849 if (IsNetworkInitialised) return true;
7850 WSADATA info;
7851 if (WSAStartup(MAKEWORD(1,1), &info) != 0) {
7852 LogPrint(0, LOG_NETWORK, 0, "Could not start Windows Networking...");
7853 return false;
7854 }
7855 IsNetworkInitialised = true;
7856 return true;
7857 }
7858#endif
7859
7860bool LookupHostname(uint32 address, char* name, uint32 maxSize) {
7862 struct hostent *pHost;
7863
7864 unsigned char* addrChars = (unsigned char*)&address;
7865 //char addrString[20];
7866 char* addrString = new char[20];
7867 snprintf(addrString, 20, "%u.%u.%u.%u", addrChars[0], addrChars[1], addrChars[2], addrChars[3]);
7868
7869 #ifdef WINDOWS
7870 pHost = gethostbyname(addrString);
7871 delete [] addrString;
7872 if (pHost == NULL) {
7873 return false;
7874 }
7875 if (strlen(pHost->h_name) > maxSize-1) {
7876 return false;
7877 }
7878 utils::strcpyavail(name, pHost->h_name, maxSize, true);
7879 return true;
7880 #else // WINDOWS
7881
7882 #ifdef Darwin
7883 pHost = gethostbyname(addrString);
7884 delete [] addrString;
7885 if (pHost == NULL)
7886 return false;
7887 else {
7888 if (strlen(pHost->h_name) > maxSize-1)
7889 return false;
7890 utils::strcpyavail(name, pHost->h_name, maxSize, true);
7891 return true;
7892 }
7893 #else // Darwin
7894
7895 pHost = new struct hostent;
7896 char bf[2000];
7897 int er;
7898 gethostbyname_r(addrString, pHost, bf, 2000, &pHost, &er);
7899 delete [] addrString;
7900 if (er != 0) {
7901 delete pHost;
7902 return false;
7903 }
7904 else {
7905 if (strlen(pHost->h_name) > maxSize-1)
7906 return false;
7907 utils::strcpyavail(name, pHost->h_name, maxSize, true);
7908 delete pHost;
7909 return true;
7910 }
7911
7912 #endif // Darwin
7913 #endif // WINDOWS
7914}
7915
7917 char* name = new char[256];
7918 if (!GetLocalHostname(name, 255)) {
7919 delete [] name;
7920 return "";
7921 }
7922
7923 std::string sname = name;
7924 delete [] name;
7925 return sname;
7926}
7927
7928bool GetLocalHostname(char* name, uint32 maxSize) {
7930
7931 if (gethostname(name, maxSize) == 0)
7932 return true;
7933 else
7934 return false;
7935
7936 //JString ipaddress = GetLocalIPAddress();
7937 //JString hostname = ipaddress;
7938 //struct hostent* hent;
7939 //if ( (ipaddress.equals("127.0.0.1")) || (ipaddress.equals("localhost")) ) {
7940 // localhostName = "127.0.0.1";
7941 // return localhostName;
7942 //}
7943
7944 //#ifdef WINDOWS
7945
7946 // hent = gethostbyname((char*) ipaddress);
7947 // if (hent != NULL)
7948 // localhostName = JString(hent->h_name);
7949 // else {
7950 // int err = WSAGetLastError();
7951 // if (DEBUGLEVEL(KITCHENSINK)) {
7952 // printf("getLocalHostname(): gethostbyaddr error %d...\n", err);
7953 // }
7954 // localhostName = ipaddress;
7955 // return ipaddress;
7956 // }
7957
7958 //#else // WINDOWS
7959
7960 // struct addrinfo hints, *res;
7961 // int error;
7962 // const char *cause = NULL;
7963
7964 // memset(&hints, 0, sizeof(hints));
7965 // hints.ai_flags = AI_NUMERICHOST;
7966 // hints.ai_family = PF_UNSPEC;
7967 // hints.ai_socktype = SOCK_STREAM;
7968 // error = getaddrinfo(ipaddress, NULL, &hints, &res);
7969 // if (error != 0) {
7970 // localhostName = ipaddress;
7971 // return ipaddress;
7972 // }
7973 // else {
7974 // if (res->ai_canonname != NULL) {
7975 // localhostName = res->ai_canonname;
7976 // }
7977 // else
7978 // localhostName = ipaddress;
7979 // }
7980 // freeaddrinfo(res);
7981
7982 //#endif // WINDOWS
7983
7984 //return localhostName;
7985
7986}
7987
7988bool GetLocalMACAddress(uint64& address) {
7989 address = 0;
7990 uint32 c;
7991 NetworkInterfaces* interfaces = GetLocalInterfaces(c);
7992 for (uint32 i=0; i<c; i++) {
7993 if ( (interfaces[i].address != 0) && (interfaces[i].address != LOCALHOSTIP) )
7994 address = interfaces[i].mac;
7995 }
7996 delete [] interfaces;
7997 return (address != 0);
7998}
7999
8000uint64* GetLocalMACAddresses(uint32& count) {
8001 uint32 c;
8002 NetworkInterfaces* interfaces = GetLocalInterfaces(c);
8003 if (!c)
8004 return NULL;
8005 uint64* addresses = new uint64[c];
8006 uint32 p=0;
8007 for (uint32 i=0; i<c; i++) {
8008 if ( (interfaces[i].address != 0) && (interfaces[i].address != LOCALHOSTIP) )
8009 addresses[p++] = interfaces[i].mac;
8010 }
8011 count = p;
8012 return addresses;
8013}
8014
8015bool IsLocalIPAddress(const char* addr) {
8016 uint32 address;
8017 if (!LookupIPAddress(addr, address))
8018 return false;
8019 return IsLocalIPAddress(address);
8020}
8021
8022bool IsLocalIPAddress(uint32& address) {
8024 uint32 count;
8025 uint32* addresses = GetLocalIPAddresses(count);
8026 if ((addresses == NULL) || (count == 0)) {
8027 delete [] addresses;
8028 return false;
8029 }
8030
8031 unsigned int n;
8032 for (n=0; n<count; n++) {
8033 if (addresses[n] == address) {
8034 delete [] addresses;
8035 return true;
8036 }
8037 }
8038 delete [] addresses;
8039 return false;
8040}
8041
8042bool GetLocalIPAddress(uint32& address) {
8044 uint32 count;
8045 uint32* addresses = GetLocalIPAddresses(count);
8046 if ((addresses == NULL) || (count == 0)) {
8047 delete [] addresses;
8048 return false;
8049 }
8050 // First find first non-localhost address
8051 unsigned int n;
8052 bool localhostPresent = false;
8053 for (n=0; n<count; n++) {
8054 if (addresses[n] != LOCALHOSTIP) {
8055 if (addresses[n] != 0) {
8056 address = addresses[n];
8057 delete [] addresses;
8058 return true;
8059 }
8060 }
8061 else
8062 localhostPresent = true;
8063 }
8064 delete [] addresses;
8065 // OK, then accept localhost, if present
8066 if (localhostPresent) {
8067 address = LOCALHOSTIP;
8068 return true;
8069 }
8070 else
8071 return false;
8072}
8073
8074uint32* GetLocalIPAddresses(uint32& count) {
8076
8077 uint32 maxSize = 128;
8078 uint32* addresses = new uint32[maxSize];
8079
8080 addresses[0] = LOCALHOSTIP;
8081 count = 1;
8082
8083 char* szHostName = new char[255];
8084
8085 bool canAskHost = true;
8086 if( gethostname(szHostName, 255) != 0 ) {
8087 #ifdef WINDOWS
8088 int err = GetLastOSErrorNumber();
8089 if (err == WSANOTINITIALISED) {
8090 WSADATA info;
8091 if (WSAStartup(MAKEWORD(1,1), &info) != 0) {
8092 delete [] szHostName;
8093 return addresses;
8094 }
8095 else {
8096 if( gethostname(szHostName, 255) != 0 )
8097 canAskHost = false;
8098 }
8099 }
8100 else
8101 canAskHost = false;
8102 #else // WINDOWS
8103 canAskHost = false;
8104 #endif // WINDOWS
8105 }
8106
8107 struct hostent * pHost;
8108 uint32 addr, j, i;
8109 bool exists;
8110 #if !defined(WINDOWS) && !defined(Darwin)
8111 // gethostbyname_r() writes its result INTO this caller-supplied buffer,
8112 // and the returned hostent's h_addr_list points INTO that buffer - so it
8113 // must outlive every read of pHost below. Freeing it before the
8114 // consumption loop was a real heap-use-after-free (ASan: 30/30 runs of
8115 // network_http reported it at the h_addr_list read). Freed after the loop.
8116 char* hostBuf = NULL;
8117 struct hostent* hostAlloc = NULL;
8118 #endif
8119
8120 if (canAskHost) {
8121 // Get host addresses
8122
8123 #ifdef WINDOWS
8124 pHost = gethostbyname(szHostName);
8125 #else // WINDOWS
8126
8127 #ifdef Darwin
8128 pHost = gethostbyname(szHostName);
8129 //if (pHost == NULL)
8130 // return addresses;
8131 #else // Darwin
8132
8133 hostAlloc = new struct hostent;
8134 hostBuf = new char[2000];
8135 int er = 0;
8136 struct hostent* hres = NULL;
8137 int res = gethostbyname_r(szHostName, hostAlloc, hostBuf, 2000, &hres, &er);
8138 // LogPrint(0, LOG_NETWORK, 0, "gethostbyname_r '%s' [%d] [%d]...\n", szHostName, res, er);
8139 // Success = res==0 AND non-NULL result. Keep the result in its own
8140 // pointer: glibc sets *result = NULL on failure, and the old code
8141 // passed &pHost, so that NULL overwrote our allocation - leaking the
8142 // hostent and leaving the trailing "delete pHost" deleting NULL.
8143 // Do NOT free hostBuf here: h_addr_list points into it.
8144 if ((res != 0) || (hres == NULL))
8145 pHost = NULL;
8146 else
8147 pHost = hres;
8148 #endif // Darwin
8149 #endif // WINDOWS
8150
8151 for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
8152 {
8153 exists = false;
8154 memcpy(&addr, ((unsigned char*)pHost->h_addr_list[i]), sizeof(uint32));
8155 if ( (addr != 0) && (addr != LOCALHOSTIP) ) {
8156 for (j=0; j<count; j++) {
8157 if (addresses[j] == addr) {
8158 exists = true;
8159 break;
8160 }
8161 }
8162 if (!exists)
8163 addresses[count++] = addr;
8164 }
8165 }
8166
8167 #ifdef WINDOWS
8168 #else // WINDOWS
8169 #ifdef Darwin
8170 endhostent();
8171 #else
8172 // Safe now: the h_addr_list reads above are done.
8173 delete hostAlloc;
8174 delete [] hostBuf;
8175 #endif // Darwin
8176 #endif // WINDOWS
8177 }
8178
8179 uint32 c;
8180 NetworkInterfaces* interfaces = GetLocalInterfaces(c);
8181 for (i=0; i<c; i++) {
8182 exists = false;
8183 if ( (interfaces[i].address != 0) && (interfaces[i].address != LOCALHOSTIP) ) {
8184 for (j=0; j<count; j++) {
8185 if (addresses[j] == interfaces[i].address) {
8186 exists = true;
8187 break;
8188 }
8189 }
8190 if (!exists)
8191 addresses[count++] = interfaces[i].address;
8192 }
8193 }
8194 delete [] interfaces;
8195 delete [] szHostName;
8196 return addresses;
8197}
8198
8201
8202 uint32 maxSize = 128;
8203 uint32 addr;
8204 NetworkInterfaces* interfaces = new NetworkInterfaces[maxSize];
8205 count = 0;
8206
8207 #ifdef WINDOWS
8208
8209 DWORD dwSize = 0;
8210 DWORD dwRetVal = 0;
8211
8212 unsigned int i = 0;
8213
8214 // Set the flags to pass to GetAdaptersAddresses
8215 ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
8216
8217 // default to unspecified address family (both)
8218 ULONG family = AF_INET;
8219
8220 LPVOID lpMsgBuf = NULL;
8221
8222 PIP_ADAPTER_ADDRESSES pAddresses = NULL;
8223 ULONG outBufLen = 0;
8224 ULONG Iterations = 0;
8225
8226 PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
8227 PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
8228 PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL;
8229 PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL;
8230 IP_ADAPTER_DNS_SERVER_ADDRESS *pDnServer = NULL;
8231 IP_ADAPTER_PREFIX *pPrefix = NULL;
8232
8233 // Allocate a 15 KB buffer to start with.
8234 outBufLen = 15000;
8235
8236 do {
8237
8238 pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);
8239 if (pAddresses == NULL)
8240 return interfaces;
8241
8242 dwRetVal =
8243 GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
8244
8245 if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
8246 FREE(pAddresses);
8247 pAddresses = NULL;
8248 }
8249 else
8250 break;
8251
8252 Iterations++;
8253
8254 } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < 10));
8255
8256
8257 if (dwRetVal == NO_ERROR) {
8258 // If successful, output some information from the data we received
8259 pCurrAddresses = pAddresses;
8260 while (pCurrAddresses) {
8261 if ( (pCurrAddresses->OperStatus == IfOperStatusUp) && (pCurrAddresses->IfIndex != 0)) {
8262
8263 // First check the IP address
8264 pUnicast = pCurrAddresses->FirstUnicastAddress;
8265 if (pUnicast != NULL) {
8266 for (i = 0; pUnicast != NULL; i++) {
8267 addr = *(uint32*)(((unsigned char*) ((SOCKADDR*)(pUnicast->Address.lpSockaddr))->sa_data) + 2);
8268 if ( (addr != 0) && (addr != LOCALHOSTIP) ) {
8269 interfaces[count].address = addr;
8270 interfaces[count].mac = 0;
8271 if (pCurrAddresses->PhysicalAddressLength == 6)
8272 memcpy(&(interfaces[count].mac), &(pCurrAddresses->PhysicalAddress), 6);
8273 WideCharToMultiByte( CP_ACP, 0, pCurrAddresses->Description, -1, interfaces[count].name, MAXKEYNAMELEN, NULL, NULL );
8274 WideCharToMultiByte( CP_ACP, 0, pCurrAddresses->FriendlyName, -1, interfaces[count].friendlyName, MAXKEYNAMELEN, NULL, NULL );
8275 count++;
8276 }
8277 pUnicast = pUnicast->Next;
8278 }
8279 }
8280 }
8281
8282 pCurrAddresses = pCurrAddresses->Next;
8283 }
8284 }
8285 if (pAddresses)
8286 FREE(pAddresses);
8287
8288 return interfaces;
8289
8290 #else
8291 int sock = 0;
8292 struct ifreq ifreq;
8293 struct sockaddr_in *saptr = NULL;
8294 struct if_nameindex *iflist = NULL, *listsave = NULL;
8295
8296 //need a socket for ioctl()
8297 if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
8298 return interfaces;
8299 }
8300
8301 //returns pointer to dynamically allocated list of structs
8302 iflist = listsave = if_nameindex();
8303
8304 if (iflist == NULL) {
8305 close(sock);
8306 return interfaces;
8307 }
8308
8309 //walk thru the array returned and query for each
8310 //interface's address
8311 //for(iflist; iflist->if_index != 0; iflist++) {
8312 for(; iflist->if_index != 0; iflist++) {
8313 //copy in the interface name to look up address of
8314 strncpy(ifreq.ifr_name, iflist->if_name, IF_NAMESIZE);
8315 //get the address for this interface
8316 if(ioctl(sock, SIOCGIFADDR, &ifreq) != 0) {
8317 // ignore;
8318 continue;
8319 }
8320 //print out the address
8321 saptr = (struct sockaddr_in *)&ifreq.ifr_addr;
8322 //unsigned char* ip = (unsigned char*)&(saptr->sin_addr.s_addr);
8323 //printf("**** %u.%u.%u.%u ***\n", ip[0], ip[1], ip[2], ip[3]);
8324 memcpy(&(interfaces[count].address), &(saptr->sin_addr.s_addr), sizeof(uint32));
8325 utils::strcpyavail(interfaces[count].name, ifreq.ifr_name, MAXKEYNAMELEN, true);
8326 #ifdef __APPLE__
8327 interfaces[count].mac = 0;
8328 #else
8329 // get the MAC address (Linux only)
8330 interfaces[count].mac = 0;
8331 ioctl(sock, SIOCGIFHWADDR, &ifreq);
8332 memcpy(&(interfaces[count].mac), &(ifreq.ifr_hwaddr.sa_data), 6);
8333 #endif
8334 count++;
8335 }
8336 //free the dynamic memory kernel allocated for us
8337 if_freenameindex(listsave);
8338 close(sock);
8339
8340 #endif
8341
8342 return interfaces;
8343}
8344
8345bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort) {
8347
8348 SOCKET socket;
8349 struct sockaddr_in addr;
8350 addr.sin_family= AF_INET;
8351 addr.sin_addr.s_addr=INADDR_ANY;
8352 bool result = false;
8353
8354 nextPort = lastPort + 1;
8355 while (nextPort < lastPort + 1000) {
8356 if((socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
8357 return false;
8358
8359 #ifdef WINDOWS
8360 // Set the exclusive address option, preventing other software binding to
8361 // non-INADDR_ANY (i.e. interface addresses such as localhost directly)
8362 int one = 1;
8363 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &one, sizeof(one));
8364 #else
8365 /*
8366 This socket option tells the kernel that even if this port is busy (in
8367 the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
8368 but with another state, you will still get an address already in use
8369 error. It is useful if your server has been shut down, and then
8370 restarted right away while sockets are still active on its port. You
8371 should be aware that if any unexpected data comes in, it may confuse
8372 your server, but while this is possible, it is not likely.
8373 */
8374 int one = 1;
8375 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,sizeof(one));
8376 #endif
8377
8378 addr.sin_port=htons(nextPort);
8379
8380 result = (bind(socket,(SOCKADDR*)&addr,sizeof(struct sockaddr_in))!=SOCKET_ERROR);
8381 shutdown(socket, SD_BOTH);
8382 closesocket(socket);
8383
8384 if (result)
8385 return true;
8386
8387 nextPort++;
8388 }
8389 return false;
8390
8391}
8392
8394 printf("Testing Utils...\n\n");
8395
8396 char hostname[1024];
8397 if (!GetLocalHostname(hostname, 1023)) {
8398 printf("Error GetLocalHostname\n");
8399 return false;
8400 }
8401 printf("Local Hostname: '%s'\n\n", hostname);
8402
8403 uint32 addr;
8404 unsigned char* addrChars = (unsigned char*) &addr;
8405 if (!GetLocalIPAddress(addr)) {
8406 printf("Error GetLocalIPAddress\n");
8407 return false;
8408 }
8409 printf("Local IP Address: %u.%u.%u.%u\n\n", addrChars[0], addrChars[1], addrChars[2], addrChars[3]);
8410
8411 uint32 count;
8412 uint32* addresses = GetLocalIPAddresses(count);
8413 if (addresses == NULL) {
8414 printf("Error GetLocalIPAddresses\n");
8415 return false;
8416 }
8417 uint32 n;
8418 for (n=0; n<count; n++) {
8419 addrChars = (unsigned char*) &addresses[n];
8420 printf("Local IP Address[%u]: %u.%u.%u.%u (%u,%u)\n\n", n, addrChars[0], addrChars[1], addrChars[2], addrChars[3], addresses[n], LOCALHOSTIP);
8421 }
8422 delete [] addresses;
8423
8424 NetworkInterfaces* interfaces = GetLocalInterfaces(count);
8425 for (n=0; n<count; n++) {
8426 addrChars = (unsigned char*) &(interfaces[n]);
8427 printf("Local Interface[%u] %s: %u.%u.%u.%u (%llX)\n\n", n, interfaces[n].name,
8428 addrChars[0], addrChars[1], addrChars[2], addrChars[3], interfaces[n].mac);
8429 }
8430 delete [] interfaces;
8431
8432 return true;
8433}
8434
8435void PrintBinary(void* p, uint32 size, bool asInt, const char* title) {
8436 if (title != NULL)
8437 printf("--- %s %u ---\n", title, size);
8438 unsigned char c;
8439 for (uint32 n=0; n<size; n++) {
8440 c = *(((unsigned char*)p)+n);
8441 if (asInt)
8442 printf("[%u] ", (unsigned int)c);
8443 else
8444 printf("[%c] ", c);
8445 if ( (n > 0) && ((n+1)%10 == 0) )
8446 printf("\n");
8447 }
8448 printf("\n");
8449}
8450
8451// const char* stristr(const char *str, const char *substr, uint32 len) {
8452// if (!str || !substr) return NULL;
8453// const char *a, *b;
8454// uint32 n=0, m, sslen = (uint32)strlen(substr);
8455// for(;*str;*str++,n++) {
8456// a = str;
8457// b = substr;
8458// m = n+sslen;
8459// while((*a++ | 32) == (*b++ | 32)) {
8460// if(!*b)
8461// return str;
8462// if (len && (++m > len))
8463// return NULL;
8464// }
8465// }
8466// return NULL;
8467// }
8468
8469
8470const char* stristr(const char *str, const char *substr, uint32 len) {
8471 if (!str || !substr) return NULL;
8472 uint32 sslen = (uint32)strlen(substr);
8473 if (sslen == 0) return (const char*)str;
8474 const char *a, *b;
8475 uint32 n=0, m;
8476 for (; *str; str++, n++) {
8477 a = str;
8478 b = substr;
8479 m = n+sslen;
8480 /* Case-insensitive compare via |32 (ASCII A–Z only). */
8481 while ((*a++ | 32) == (*b++ | 32)) {
8482 if (!*b)
8483 return str;
8484 if (len && (++m > len))
8485 return NULL;
8486 }
8487 }
8488 return NULL;
8489}
8490
8491uint32 strcpyavail(char* dst, const char* src, uint32 maxlen, bool copyAvailable) {
8492 if ( !dst || ! src || !maxlen )
8493 return 0;
8494 uint32 len = (uint32)strlen(src);
8495 if (len > maxlen-1) {
8496 if (!copyAvailable)
8497 return 0;
8498 else {
8499 memcpy(dst, src, maxlen-1);
8500 dst[maxlen] = 0;
8501 return maxlen-1;
8502 }
8503 }
8504 else
8505 memcpy(dst, src, len+1);
8506 return len;
8507}
8508
8509bool GetNextLineEnd(const char *str, uint32 size, uint32& len, uint32& crSize) {
8510 if (!str || !size)
8511 return false;
8512
8513 for (len = 0; len < size; len++) {
8514 // Checking for CR and CRLF
8515 if (str[len] == 13) {
8516 crSize = ( (len < size-1) && (str[len+1] == 10 ) ) ? 2 : 1;
8517 return true;
8518 }
8519 // Checking for LF only without CR
8520 if (str[len] == 10) {
8521 crSize = 1;
8522 return true;
8523 }
8524 }
8525 return false;
8526}
8527
8528std::string TextCapitalise(const char* text) {
8529 if (!text)
8530 return "";
8531 std::string str = text;
8532 if (!str.length())
8533 return "";
8534 std::string::iterator i = str.begin(), e = str.end();
8535 *i = ::toupper(*i);
8536 i++;
8537 if (i != e)
8538 std::transform(i, e, i, ::tolower);
8539 return str;
8540}
8541
8542std::string TextUppercase(const char* text) {
8543 std::string str = text;
8544 std::transform(str.begin(), str.end(), str.begin(), ::toupper);
8545 return str;
8546}
8547
8548std::string TextLowercase(const char* text) {
8549 std::string str = text;
8550 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
8551 return str;
8552}
8553
8554std::string TextIndent(const char* text, const char* indent) {
8555 std::vector<std::string> lines = utils::TextListSplitLines(text, true, false);
8556 std::vector<std::string>::iterator i = lines.begin(), e = lines.end();
8557 std::string output;
8558 while (i != e) {
8559 output += utils::StringFormat("%s%s\n", indent, (*i).c_str());
8560 i++;
8561 }
8562 return output;
8563}
8564
8565std::string TextUnindent(const char* text) {
8566 uint32 len = (uint32)strlen(text);
8567 if (!len) return "";
8568 if (text[0] > 32)
8569 return text;
8570
8571 // Find initial spacing char sequence
8572 uint32 s = 0, p = 0;
8573 // Find initial line endings
8574 while ( ((text[s] == '\n') || (text[s] == '\r')) && (s < len))
8575 s++;
8576 p = s;
8577 while ((text[p] <= 32) && (p < len))
8578 p++;
8579 std::string indentString = std::string(text+s, p-s);
8580 std::string str = text;
8581 StringSingleReplace(str, indentString, "", false);
8582 return str;
8583}
8584
8585
8586std::string TextTrimQuotes(const char* text) {
8587 if (text) {
8588 uint32 begin = 0, end = (uint32)strlen(text);
8589 if (begin == end)
8590 return "";
8591 while ((begin < end) && (text[begin] <= 32) || (text[begin] == '\"') || (text[begin] == '\''))
8592 begin++;
8593 if (begin == end)
8594 return "";
8595 while ((end > begin) && (text[end-1] <= 32) || (text[end-1] == '\"') || (text[end-1] == '\''))
8596 end--;
8597 return std::string(text+begin, end-begin);
8598 }
8599 else
8600 return "";
8601}
8602
8603
8604std::string TextTrim(const char* text) {
8605 if (text) {
8606 uint32 begin = 0, end = (uint32)strlen(text);
8607 if (begin == end)
8608 return "";
8609 while ((text[begin] <= 32) && (begin < end))
8610 begin++;
8611 while ((end > begin) && (text[end-1] <= 32))
8612 end--;
8613 return std::string(text+begin, end-begin);
8614 }
8615 else
8616 return "";
8617}
8618
8619std::multimap<std::string, std::string> TextMultiMapSplit(const char* text, const char* outersplit, const char* innersplit) {
8620 std::multimap<std::string, std::string> result;
8621 typedef std::pair <std::string, std::string> Map_String_Pair;
8622
8623 if (!text || !outersplit || !innersplit)
8624 return result;
8625
8626 const char* pstr = text, *lstr = text;
8627 const char* src = text;
8628
8629 while (pstr = strstr(src, outersplit)) {
8630 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8631 // result[TextTrim(std::string(src, lstr-src).c_str())] = TextTrim(std::string(lstr+1, pstr-lstr-1).c_str());
8632 result.insert(Map_String_Pair(TextTrim(std::string(src, lstr-src).c_str()), TextTrim(std::string(lstr+1, pstr-lstr-1).c_str())));
8633 }
8634 src = pstr + 1;
8635 }
8636 pstr = src + strlen(src);
8637 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8638 // result[TextTrim(std::string(src, lstr-src).c_str())] = TextTrim(std::string(lstr+1, pstr-lstr-1).c_str());
8639 result.insert(Map_String_Pair(TextTrim(std::string(src, lstr-src).c_str()), TextTrim(std::string(lstr+1, pstr-lstr-1).c_str())));
8640 }
8641
8642 return result;
8643}
8644
8645
8646std::map<std::string, std::string> TextMapSplit(const char* text, const char* outersplit, const char* innersplit) {
8647 std::map<std::string, std::string> result;
8648 typedef std::pair <std::string, std::string> Map_String_Pair;
8649
8650 if (!text || !outersplit || !innersplit)
8651 return result;
8652
8653 const char* pstr = text, *lstr = text;
8654 const char* src = text;
8655
8656 while (pstr = strstr(src, outersplit)) {
8657 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8658 // result[TextTrim(std::string(src, lstr-src).c_str())] = TextTrim(std::string(lstr+1, pstr-lstr-1).c_str());
8659 result.insert(Map_String_Pair(TextTrim(std::string(src, lstr - src).c_str()), TextTrim(std::string(lstr + 1, pstr - lstr - 1).c_str())));
8660 }
8661 src = pstr + 1;
8662 }
8663 pstr = src + strlen(src);
8664 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8665 // result[TextTrim(std::string(src, lstr-src).c_str())] = TextTrim(std::string(lstr+1, pstr-lstr-1).c_str());
8666 result.insert(Map_String_Pair(TextTrim(std::string(src, lstr - src).c_str()), TextTrim(std::string(lstr + 1, pstr - lstr - 1).c_str())));
8667 }
8668
8669 return result;
8670}
8671
8672char** SplitCommandline(const char* cmdline, int& argc) {
8673 std::vector<std::string> args = TextCommandlineSplit(cmdline);
8674 uint32 size = (uint32)args.size();
8675 if (!size)
8676 return NULL;
8677
8678 char** argv = new char*[size+1];
8679 uint32 c = 0;
8680 std::vector<std::string>::iterator i = args.begin(), e = args.end();
8681 while (i != e) {
8682 argv[c] = new char[(*i).length()+1];
8683 strcpy(argv[c], (*i).c_str());
8684 c++;
8685 i++;
8686 }
8687 argv[c] = NULL;
8688 argc = (int)c;
8689 return argv;
8690}
8691
8692wchar_t** SplitCommandlineW(const char* cmdline, int& argc) {
8693 std::vector<std::string> args = TextCommandlineSplit(cmdline);
8694 uint32 size = (uint32)args.size();
8695 if (!size)
8696 return NULL;
8697
8698 wchar_t** argv = new wchar_t*[size+1];
8699 uint32 c = 0;
8700 std::vector<std::string>::iterator i = args.begin(), e = args.end();
8701 while (i != e) {
8702 argv[c] = new wchar_t[(*i).length()+1];
8703 mbstowcs(argv[c], (*i).c_str(), (*i).length() + 1);
8704 c++;
8705 i++;
8706 }
8707 argv[c] = NULL;
8708 argc = (int)c;
8709 return argv;
8710}
8711
8712bool DeleteCommandline(char** argv, int argc) {
8713 for (uint32 n=0; n<(uint32)argc; n++)
8714 delete [] argv[n];
8715 delete [] argv;
8716 return true;
8717}
8718
8719std::vector<std::string> TextCommandlineSplit(const char* cmdline) {
8720
8721 bool insideQuotes = false;
8722 bool lastWasWhiteSpace = false;
8723 std::vector<std::string> vect;
8724 std::string arg, val, str;
8725 unsigned char ch;
8726
8727 uint32 len = (uint32)strlen(cmdline);
8728
8729 bool keepQuotes = false;
8730
8731 for (uint32 n=0; n<len; n++) {
8732 ch = cmdline[n];
8733 if (ch <= 32) {
8734 if (!insideQuotes) {
8735 if (!lastWasWhiteSpace) {
8736 // An arg is ended, parse it...
8737 vect.push_back(str);
8738 str = "";
8739 }
8740 else {
8741 // Ignore this whitespace then...
8742 }
8743 lastWasWhiteSpace = true;
8744 }
8745 else {
8746 str += ch;
8747 }
8748 }
8749 else if (ch == '"') {
8750 insideQuotes = !insideQuotes;
8751 if (keepQuotes)
8752 str += ch;
8753 lastWasWhiteSpace = false;
8754 }
8755 else {
8756 str += ch;
8757 lastWasWhiteSpace = false;
8758 }
8759 }
8760
8761 if (str.length() > 0) {
8762 vect.push_back(str);
8763 str = "";
8764 }
8765
8766 return vect;
8767}
8768
8769std::vector<std::string> TextListSplitLines(const char* text, bool keepEmpty, bool autoTrim) {
8770 if (!text || !strlen(text))
8771 return std::vector<std::string>();
8772
8773 if (strstr(text, "\r\n"))
8774 return TextListSplit(text, "\r\n", keepEmpty, autoTrim);
8775 else if (strstr(text, "\n\r"))
8776 return TextListSplit(text, "\n\r", keepEmpty, autoTrim);
8777 else if (strstr(text, "\n"))
8778 return TextListSplit(text, "\n", keepEmpty, autoTrim);
8779 else if (strstr(text, "\r"))
8780 return TextListSplit(text, "\n", keepEmpty, autoTrim);
8781
8782 std::vector<std::string> result;
8783 result.push_back(text);
8784 return result;
8785}
8786
8787std::vector<std::string> TextListBreakLines(const char* text, uint32 maxLineLength) {
8788 if (!text || !strlen(text))
8789 return std::vector<std::string>();
8790
8791 std::string str;
8792 std::vector<std::string> result;
8793 uint32 s = 0, n = 0, len = (uint32)strlen(text);
8794 int p = -1;
8795 while (n < len) {
8796 if (text[n] == 13) {
8797 if (n == s)
8798 result.push_back("");
8799 else {
8800 str = std::string(text + s, n - s);
8801 result.push_back(TextTrim(str.c_str()));
8802 }
8803 if ((n < len - 1) && (text[n + 1] == 10))
8804 s = n + 2;
8805 else
8806 s = n + 1;
8807 p = -1;
8808 }
8809 else if (text[n] == 10) {
8810 if (n == s)
8811 result.push_back("");
8812 else {
8813 str = std::string(text + s, n - s);
8814 result.push_back(TextTrim(str.c_str()));
8815 }
8816 if ((n < len - 1) && (text[n + 1] == 13))
8817 s = n + 2;
8818 else
8819 s = n + 1;
8820 p = -1;
8821 }
8822 else if ((n-s < maxLineLength) && (text[n] == 32)) {
8823 p = n - s;
8824 }
8825 else if (n - s >= maxLineLength) {
8826 if (p == 0) {
8827 result.push_back("");
8828 s += p + 1;
8829 p = -1;
8830 n = s - 1;
8831 }
8832 else if (p > 0) {
8833 str = std::string(text + s, p);
8834 result.push_back(TextTrim(str.c_str()));
8835 s += p + 1;
8836 p = -1;
8837 n = s - 1;
8838 }
8839 else {
8840 str = std::string(text + s, maxLineLength);
8841 result.push_back(TextTrim(str.c_str()));
8842 s += maxLineLength;
8843 p = -1;
8844 n = s;
8845 }
8846 }
8847 n++;
8848 }
8849 if (s < n) {
8850 str = std::string(text + s, n - s);
8851 result.push_back(TextTrim(str.c_str()));
8852 }
8853
8854 return result;
8855}
8856
8857std::string TextListBreakLines(const char* text, uint32 maxLineLength, const char* breakstr) {
8858 std::vector<std::string> lines = TextListBreakLines(text, maxLineLength);
8859 if (!breakstr)
8860 return TextJoin(lines, "\n");
8861 else
8862 return TextJoin(lines, breakstr);
8863}
8864
8865std::string TextJoin(std::vector<std::string> &list, const char* split, uint32 start, uint32 count) {
8866 std::ostringstream o;
8867 std::vector<std::string>::iterator i = list.begin(), e = list.end();
8868 uint32 l = 0, c = 0;
8869 while (i != e) {
8870 if (!count || ((l >= start) && (c < count))) {
8871 if (c++) o << split;
8872 o << *i;
8873 }
8874 l++;
8875 i++;
8876 }
8877 return o.str();
8878}
8879
8880std::string TextJoin(std::list<std::string> &list, const char* split, uint32 start, uint32 count) {
8881 std::ostringstream o;
8882 std::list<std::string>::iterator i = list.begin(), e = list.end();
8883 uint32 l = 0, c = 0;
8884 while (i != e) {
8885 if (!count || ((l >= start) && (c < count))) {
8886 if (c++) o << split;
8887 o << *i;
8888 }
8889 l++;
8890 i++;
8891 }
8892 return o.str();
8893}
8894
8895std::string TextJoin(std::map<std::string, std::string> &map, const char* innersplit, const char* outersplit, bool keyquotes, bool valquotes) {
8896 std::ostringstream o;
8897 std::map<std::string, std::string>::iterator i = map.begin(), e = map.end();
8898 uint32 c = 0;
8899 while (i != e) {
8900 if (c++) o << outersplit;
8901 if (keyquotes && valquotes)
8902 o << "\"" << i->first << "\"" << innersplit << "\"" << i->second << "\"";
8903 else if (valquotes)
8904 o << i->first << innersplit << "\"" << i->second << "\"";
8905 else
8906 o << i->first << innersplit << i->second;
8907 i++;
8908 }
8909 return o.str();
8910}
8911
8912std::string TextJoinJSON(std::map<std::string, std::string> &map) {
8913 std::ostringstream o;
8914 std::map<std::string, std::string>::iterator i = map.begin(), e = map.end();
8915 uint32 c = 0;
8916 o << "{ ";
8917 while (i != e) {
8918 if (c++)
8919 o << ", \"" << utils::EncodeJSON(i->first) << "\": \"" << utils::EncodeJSON(i->second) << "\"";
8920 else
8921 o << " \"" << utils::EncodeJSON(i->first) << "\": \"" << utils::EncodeJSON(i->second) << "\"";
8922 i++;
8923 }
8924 o << " }";
8925 return o.str();
8926}
8927
8928std::string TextJoinXML(std::map<std::string, std::string> &map, const char* innernodeName, const char* outernodeName) {
8929 if (!innernodeName || !strlen(innernodeName))
8930 return "";
8931 std::ostringstream o;
8932 std::map<std::string, std::string>::iterator i = map.begin(), e = map.end();
8933 if (outernodeName && strlen(outernodeName))
8934 o << "<" << outernodeName << ">\n";
8935 while (i != e) {
8936 o << "<" << innernodeName << " " << html::EncodeHTML(i->first) << "=\"" << html::EncodeHTML(i->second) << "\" />\n";
8937 i++;
8938 }
8939 if (outernodeName && strlen(outernodeName))
8940 o << "</" << outernodeName << ">\n";
8941 return o.str();
8942}
8943
8944
8945
8946std::vector<std::string> TextListSplit(const char* text, const char* split, bool keepEmpty, bool autoTrim) {
8947 std::vector<std::string> result;
8948 if (!text || !split)
8949 return result;
8950
8951 uint32 splitLen = (uint32)strlen(split);
8952 const char* pstr = text;
8953 const char* src = text;
8954
8955 while (pstr = strstr(src, split)) {
8956 if (pstr - src || keepEmpty) {
8957 if (autoTrim)
8958 result.push_back(TextTrim(std::string(src, pstr - src).c_str()));
8959 else
8960 result.push_back(std::string(src, pstr - src).c_str());
8961 }
8962 src = pstr + splitLen;
8963 }
8964 pstr = src + strlen(src);
8965 if (pstr - src) {
8966 if (autoTrim)
8967 result.push_back(TextTrim(std::string(src, pstr - src).c_str()));
8968 else
8969 result.push_back(std::string(src, pstr - src).c_str());
8970 }
8971 return result;
8972}
8973
8974std::string TextVectorConcat(std::vector<std::string> vect, const char* sep, bool allowEmpty) {
8975 std::string result;
8976 std::vector<std::string>::iterator i, e;
8977 for (i=vect.begin(), e=vect.end(); i!=e; i++) {
8978 if (allowEmpty || (*i).size()) {
8979 if (result.size())
8980 result += sep;
8981 result += *i;
8982 }
8983 }
8984 return result;
8985}
8986
8987char* StringFormat(uint32& size, const char *format, ...) {
8988 if (strlen(format) == 0) {
8989 size = 0;
8990 return 0;
8991 }
8992
8993 va_list args;
8994 va_start(args, format);
8995 char* res = StringFormatVA(size, format, args);
8996 va_end(args);
8997 return res;
8998}
8999
9000
9001char* StringFormatVA(uint32& size, const char *format, va_list orig_args) {
9002 char* str = NULL;
9003
9004 #ifdef WINDOWS
9005 int len = _vscprintf(format, orig_args) + 10;
9006 str = (char*)malloc(len+1);
9007 #ifdef CYGWIN
9008 len = vsnprintf(str, len, format, orig_args);
9009 #else
9010 len = _vsnprintf_s(str, len, len+1, format, orig_args);
9011 #endif
9012
9013 if (len)
9014 size = (uint32)strlen(str);
9015 else {
9016 size = 0;
9017 free((char*)str);
9018 str = NULL;
9019 }
9020 #else // WINDOWS
9021 int len = vasprintf(&str, format, orig_args);
9022 if(len >= 0)
9023 size = strlen(str);
9024 else
9025 size = 0;
9026 #endif //HAVE_VASPRINTF
9027
9028 return str;
9029}
9030
9031bool StringFormatInto(char* dst, uint32 maxsize, const char *format, ...) {
9032 if (!dst || !maxsize)
9033 return false;
9034 if (strlen(format) == 0) {
9035 dst[0] = 0;
9036 return true;
9037 }
9038
9039 uint32 len = 0;
9040 va_list args;
9041 va_start(args, format);
9042 char* str = StringFormatVA(len, format, args);
9043 va_end(args);
9044 if (str && len) {
9045 if (len > maxsize) {
9046 free(str);
9047 return false;
9048 }
9049 else {
9050 utils::strcpyavail(dst, str, maxsize, true);
9051 free(str);
9052 return true;
9053 }
9054 }
9055 else {
9056 free(str);
9057 return false;
9058 }
9059}
9060
9061std::string StringFormat(const char *format, ...) {
9062 if (strlen(format) == 0)
9063 return "";
9064
9065 std::string res;
9066 uint32 len = 0;
9067 va_list args;
9068 va_start(args, format);
9069 char* str = StringFormatVA(len, format, args);
9070 va_end(args);
9071 if (str && len)
9072 res = str;
9073 else
9074 res = "";
9075 free(str);
9076 return res;
9077}
9078
9079uint32 StringSingleReplace(std::string& text, std::string key, std::string value, bool onlyFirst) {
9080 if (!text.size() || !key.size())
9081 return 0;
9082
9083 uint32 c = 0;
9084 size_t p = 0;
9085 uint32 keylen = (uint32)key.size();
9086
9087 while ( (p = text.find(key, p)) != std::string::npos) {
9088 text.replace(p, keylen, value);
9089 p++;
9090 c++;
9091 if (onlyFirst)
9092 break;
9093 }
9094 return c;
9095}
9096
9097uint32 StringMultiReplace(std::string& text, std::map<std::string, std::string>& map, bool onlyFirst) {
9098 if (!text.size() || !map.size())
9099 return 0;
9100
9101 uint32 c = 0;
9102
9103 std::map<std::string, std::string>::iterator it, itEnd;
9104 for (it = map.begin(), itEnd = map.end(); it != itEnd; ++it)
9105 c += StringSingleReplace(text, it->first, it->second, onlyFirst);
9106
9107 return c;
9108}
9109
9110
9111// Example use
9112 //uint32 len;
9113 //char* file = utils::ReadAFile("test.html", len);
9114 //std::string sfile = file;
9115
9116 //std::list<std::map<std::string, std::string> > list;
9117
9118 //char tmp[64];
9119 //std::map<std::string, std::string> map;
9120 //for (uint32 n=0; n<10; n++) {
9121 // map["%1%"] = utils::Int2Ascii(n, tmp, 64, 10);
9122 // map["%2%"] = "Hello2";
9123 // map["%3%"] = "Hello3";
9124 // map["%4%"] = "Hello4";
9125 // map["%5%"] = "Hello5";
9126 // list.push_back(map);
9127 //}
9128
9129 //utils::ScriptReplace(sfile, "test", list);
9130
9131uint32 StringScriptReplace(std::string& text, std::string name, std::list<std::map<std::string, std::string> >& list) {
9132 if (!text.size() || !name.size())
9133 return 0;
9134
9135 uint32 c = 0;
9136
9137 char* start = new char[name.size() + 50];
9138 snprintf(start, name.size()+50, "<!-- start:%s -->", name.c_str());
9139 char* end = new char[name.size() + 50];
9140 snprintf(end, name.size()+50, "<!-- end:%s -->", name.c_str());
9141
9142 // Find the section boundaries
9143 size_t a1 = text.find(start);
9144 if (a1 == std::string::npos) {
9145 delete [] start;
9146 delete [] end;
9147 return 0;
9148 }
9149 size_t b1 = text.find(end);
9150 if (b1 == std::string::npos) {
9151 delete [] start;
9152 delete [] end;
9153 return 0;
9154 }
9155
9156 uint32 a2 = (uint32)(a1 + strlen(start));
9157 uint32 b2 = (uint32)(b1 + strlen(end));
9158
9159 // Copy it
9160 std::string section = text.substr(a2, b1-a2);
9161 std::string tmp;
9162 std::string result;
9163
9164 std::list<std::map<std::string, std::string> >::iterator it, itEnd;
9165 for (it = list.begin(), itEnd = list.end(); it != itEnd; ++it) {
9166 tmp = section;
9167 c += StringMultiReplace(tmp, *it, false);
9168 result += tmp;
9169 }
9170
9171 text.replace(a1, b2-a1, result);
9172 delete [] start;
9173 delete [] end;
9174 return c;
9175}
9176
9177
9178
9179unsigned char Hex2Char(const char* str) {
9180 unsigned char c = (unsigned char) strtol(str, NULL, 16);
9181 if (c == 0)
9182 return ' ';
9183 else
9184 return c;
9185}
9186
9187unsigned char Dec2Char(const char* str) {
9188 unsigned char c = (unsigned char) strtol(str, NULL, 10);
9189 if (c == 0)
9190 return ' ';
9191 else
9192 return c;
9193}
9194
9195int8 CompareFloats(float64 a, float64 b) {
9196 float64 diff = a - b;
9197 if ((diff < std::numeric_limits<float64>::epsilon()) && (-diff < std::numeric_limits<float64>::epsilon()))
9198 return 0;
9199 else if (diff > 0)
9200 return 1;
9201 else
9202 return -1;
9203}
9204
9205
9206#define poly 0xEDB88320
9207/* Some compilers need
9208 #define poly 0xEDB88320uL
9209 */
9210
9211/* On entry, addr=>start of data
9212 num = length of data
9213 crc = incoming CRC */
9214int CRC32(const char *addr, uint32 length, int32 crc) {
9215 uint32 i;
9216 for (; length>0; length--) { /* Step through bytes in memory */
9217 crc = crc ^ *addr++; /* Fetch byte from memory, XOR into CRC */
9218 for (i=0; i<8; i++) { /* Prepare to rotate 8 bits */
9219 if (crc & 1) /* b0 is set... */
9220 crc = (crc >> 1) ^ poly; /* rotate and XOR with ZIP polynomic */
9221 else /* b0 is clear... */
9222 crc >>= 1; /* just rotate */
9223 /* Some compilers need:
9224 crc &= 0xFFFFFFFF;
9225 */
9226 } /* Loop for 8 bits */
9227 } /* Loop until num=0 */
9228 return(crc); /* Return updated CRC */
9229}
9230
9231
9232std::string ReadAFileString(std::string filename) {
9233 uint32 length;
9234 char* data = ReadAFile(filename.c_str(), length, false);
9235 if (!data || !length)
9236 return "";
9237 std::string dataString = data;
9238 delete [] data;
9239 return dataString;
9240}
9241
9242char* ReadAFile(const char* dir, const char* filename, uint32& length, bool binary) {
9243 if (!dir || !filename || strlen(filename) == 0)
9244 return NULL;
9245
9246 char* fullname = new char[strlen(dir) + strlen(filename) + 5];
9247 snprintf(fullname, strlen(dir) + strlen(filename) + 5, "%s/%s", dir, filename);
9248 char* res = ReadAFile(fullname, length, binary);
9249 delete [] fullname;
9250 return res;
9251}
9252
9253char* ReadAFile(const char* filename, uint32& length, bool binary) {
9254 if (!filename || strlen(filename) == 0)
9255 return NULL;
9256
9257 length = 0;
9258
9259 FILE* file;
9260 if (binary)
9261 file = fopen(filename, "rb");
9262 else
9263 file = fopen(filename, "r");
9264 if (file == NULL) {
9265 //LogPrint(0,0,0,"Couldn't open file %s", filename);
9266 return NULL;
9267 }
9268
9269 fseek(file, 0, SEEK_END);
9270 length = ftell(file);
9271 fseek(file, 0, SEEK_SET);
9272
9273 if (length <= 0) {
9274 fclose(file);
9275 //LogPrint(0,0,0,"File %s has no size", filename);
9276 return NULL;
9277 }
9278
9279 char* data = new char[length+1];
9280
9281 int res = (int)fread(data, 1, length, file);
9282
9283 if ((res <= 0) || (res != length)) {
9284 int error = ferror(file);
9285 int eof = feof(file);
9286 if (eof == 0) {
9287 delete [] data;
9288 fclose(file);
9289 LogPrint(0,0,0,"File %s has no data", filename);
9290 return NULL;
9291 }
9292 }
9293
9294 fclose(file);
9295
9296 length = (uint32)res;
9297 data[length] = 0;
9298 return data;
9299}
9300
9301bool WriteAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary) {
9302 if (!dir || !filename || strlen(filename) == 0)
9303 return false;
9304
9305 char* fullname = new char[strlen(dir) + strlen(filename) + 5];
9306 snprintf(fullname, strlen(dir) + strlen(filename) + 5, "%s/%s", dir, filename);
9307 bool res = WriteAFile(fullname, data, length, binary);
9308 delete [] fullname;
9309 return res;
9310}
9311
9312bool WriteAFile(const char* filename, const char* data, uint32 length, bool binary) {
9313 if (!filename || strlen(filename) == 0)
9314 return false;
9315
9316 FILE* file;
9317 if (binary)
9318 file = fopen(filename, "wb");
9319 else
9320 file = fopen(filename, "w");
9321 if (file == NULL)
9322 return false;
9323
9324 int res = (int)fwrite(data, 1, length, file);
9325 fclose(file);
9326 return (res == length);
9327}
9328
9329bool AppendToAFile(const char* dir, const char* filename, const char* data, uint32 length, bool binary) {
9330 if (!dir || !filename || strlen(filename) == 0)
9331 return false;
9332
9333 char* fullname = new char[strlen(dir) + strlen(filename) + 5];
9334 snprintf(fullname, strlen(dir) + strlen(filename) + 5, "%s/%s", dir, filename);
9335 bool res = AppendToAFile(fullname, data, length, binary);
9336 delete [] fullname;
9337 return res;
9338}
9339
9340bool AppendToAFile(const char* filename, const char* data, uint32 length, bool binary) {
9341 if (!filename || strlen(filename) == 0)
9342 return false;
9343
9344 FILE* file;
9345 if (binary)
9346 file = fopen(filename, "ab");
9347 else
9348 file = fopen(filename, "a");
9349 if (file == NULL)
9350 return false;
9351
9352 int res = (int)fwrite(data, 1, length, file);
9353 fclose(file);
9354 return (res == length);
9355}
9356
9357bool DeleteAFile(const char* dir, const char* filename, bool force) {
9358 if (!dir || !filename || strlen(filename) == 0)
9359 return false;
9360
9361 char* fullname = new char[strlen(dir) + strlen(filename) + 5];
9362 snprintf(fullname, strlen(dir) + strlen(filename) + 5, "%s/%s", dir, filename);
9363 bool res = DeleteADir(fullname, force);
9364 delete [] fullname;
9365 return res;
9366}
9367
9368bool DeleteAFile(const char* filename, bool force) {
9369 return DeleteADir(filename, force);
9370}
9371
9372bool ChangeAFileAttr(const char* filename, bool read, bool write) {
9373 if (!filename || strlen(filename) == 0)
9374 return false;
9375 #ifdef WINDOWS
9376 if (!write)
9377 return (SetFileAttributes(filename, FILE_ATTRIBUTE_READONLY) != 0);
9378 else
9379 return (SetFileAttributes(filename, FILE_ATTRIBUTE_NORMAL) != 0);
9380 #else
9381 if (read && write)
9382 return (chmod(filename,S_IREAD | S_IWRITE) != 0);
9383 else if (read)
9384 return (chmod(filename,S_IREAD) == 0);
9385 else if (write)
9386 return (chmod(filename,S_IWRITE) == 0);
9387 else
9388 return (chmod(filename,0) == 0);
9389 #endif
9390}
9391
9392bool MoveAFile(const char* oldfilename, const char* newfilename, bool force) {
9393 #ifdef WINDOWS
9394 bool result;
9395 if (force)
9396 result = (MoveFileEx(oldfilename, newfilename, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != 0);
9397 else
9398 result = (MoveFileEx(oldfilename, newfilename, MOVEFILE_COPY_ALLOWED) != 0);
9399 if (result)
9400 return true;
9401 LogPrint(0,LOG_SYSTEM,0,"MoveAFile '%s' to '%s' failed with: %s", oldfilename, newfilename, GetLastOSErrorMessage().c_str());
9402 return false;
9403 #else
9404 if (rename(oldfilename, newfilename) == 0)
9405 return true;
9406 int error = errno;
9407 if (force) {
9408 FileDetails info = GetFileDetails(newfilename);
9409 if (info.doesExist) {
9410 delete(newfilename);
9411 if (rename(oldfilename, newfilename) == 0)
9412 return true;
9413 }
9414 }
9415 if (error == EXDEV) {
9416 if (CopyAFile(newfilename, oldfilename)) {
9417 DeleteAFile(oldfilename, true);
9418 return true;
9419 }
9420 }
9421 return false;
9422 #endif
9423}
9424
9425bool MoveAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force) {
9426 if (!newdir || !newfilename || !strlen(newfilename) ||
9427 !olddir || !oldfilename || !strlen(oldfilename) )
9428 return false;
9429
9430 char* oldname = new char[strlen(olddir) + strlen(oldfilename) + 5];
9431 snprintf(oldname, strlen(olddir) + strlen(oldfilename) + 5, "%s/%s", olddir, oldfilename);
9432 char* newname = new char[strlen(newdir) + strlen(newfilename) + 5];
9433 snprintf(newname, strlen(newdir) + strlen(newfilename) + 5, "%s/%s", newdir, newfilename);
9434 bool res = MoveAFile(newname, oldname, force);
9435 delete [] oldname;
9436 delete [] newname;
9437 return res;
9438}
9439
9440bool CopyAFile(const char* oldfilename, const char* newfilename, bool force) {
9441 #ifdef WINDOWS
9442 if (force)
9443 return (CopyFile(oldfilename, newfilename, FALSE) != 0);
9444 else
9445 return (CopyFile(oldfilename, newfilename, TRUE) != 0);
9446 #else
9447 FileDetails target = GetFileDetails(newfilename);
9448 if (target.doesExist && !force)
9449 return false;
9450 if (target.isDirectory)
9451 return false;
9452 uint32 size;
9453 char* data = ReadAFile(oldfilename, size, true);
9454 if (!data || !size) {
9455 delete [] data;
9456 return false;
9457 }
9458
9459 if ((target.doesExist) && !DeleteAFile(newfilename, true)) {
9460 delete [] data;
9461 return false;
9462 }
9463
9464 if (!WriteAFile(newfilename, data, size, true)) {
9465 delete [] data;
9466 return false;
9467 }
9468 delete [] data;
9469 return true;
9470 #endif
9471}
9472
9473bool CopyAFile(const char* olddir, const char* oldfilename, const char* newdir, const char* newfilename, bool force) {
9474 if (!newdir || !newfilename || !strlen(newfilename) ||
9475 !olddir || !oldfilename || !strlen(oldfilename) )
9476 return false;
9477
9478 char* oldname = new char[strlen(olddir) + strlen(oldfilename) + 5];
9479 snprintf(oldname, strlen(olddir) + strlen(oldfilename) + 5, "%s/%s", olddir, oldfilename);
9480 char* newname = new char[strlen(newdir) + strlen(newfilename) + 5];
9481 snprintf(newname, strlen(newdir) + strlen(newfilename) + 5, "%s/%s", newdir, newfilename);
9482 bool res = CopyAFile(newname, oldname, force);
9483 delete [] oldname;
9484 delete [] newname;
9485 return res;
9486}
9487
9488bool CreateADir(const char* dirname) {
9489 if (!dirname || strlen(dirname) == 0)
9490 return false;
9491
9492 // Create missing parent directories first (16 Nov 2026): a PsyProbe 2 satellite asks for
9493 // <master datadir>/satellite-<node>/ before the master has created <master datadir> - Linux won that race, Windows
9494 // did not. A trailing separator is ignored.
9495 {
9496 std::string path = dirname;
9497 while (path.size() > 1 && (path[path.size() - 1] == '/' || path[path.size() - 1] == '\\'))
9498 path.erase(path.size() - 1);
9499 if (path != dirname)
9500 return CreateADir(path.c_str());
9501 size_t sep = path.find_last_of("/\\");
9502 if (sep != std::string::npos && sep > 0) {
9503 std::string parent = path.substr(0, sep);
9504 bool isDriveRoot = (parent.size() == 2 && parent[1] == ':');
9505 if (!isDriveRoot && !GetFileDetails(parent.c_str()).doesExist)
9506 CreateADir(parent.c_str());
9507 }
9508 }
9509
9510 FileDetails info = GetFileDetails(dirname);
9511
9512 if (info.doesExist) {
9513 if (info.isDirectory)
9514 return true;
9515 else
9516 return false;
9517 }
9518
9519 #ifdef WINDOWS
9520 if (CreateDirectory(dirname, NULL) != 0)
9521 return true;
9522 else
9523 return false;
9524 #else
9525 if (mkdir(dirname, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
9526 return true;
9527 else
9528 return false;
9529 #endif
9530}
9531
9532bool DeleteADir(const char* dirname, bool force) {
9533 if (!dirname || strlen(dirname) == 0)
9534 return false;
9535
9536 FileDetails info = GetFileDetails(dirname);
9537
9538 if (!info.doesExist)
9539 return true;
9540
9541 // If it is a file
9542 if (!info.isDirectory) {
9543 #ifdef WINDOWS
9544 if (DeleteFile(dirname) != 0)
9545 return true;
9546 else if (!force)
9547 return false;
9548 else {
9549 ChangeAFileAttr(dirname, true, true);
9550 if (DeleteFile(dirname) != 0)
9551 return true;
9552 else
9553 return false;
9554 }
9555 #else
9556 if (unlink(dirname) == 0)
9557 return true;
9558 else if (!force)
9559 return false;
9560 else {
9561 ChangeAFileAttr(dirname, true, true);
9562 if (unlink(dirname) == 0)
9563 return true;
9564 else
9565 return false;
9566 }
9567 #endif
9568 }
9569
9570 // Now we know it is a dir
9571 #ifdef WINDOWS
9572 if (RemoveDirectory(dirname) != 0)
9573 return true;
9574 else if (!force)
9575 return false;
9576 else {
9577 DeleteFilesInADir(dirname, true);
9578 if (RemoveDirectory(dirname) != 0)
9579 return true;
9580 else
9581 return false;
9582 }
9583 #else
9584 if (rmdir(dirname) == 0)
9585 return true;
9586 else if (!force)
9587 return false;
9588 else {
9589 DeleteFilesInADir(dirname, true);
9590 if (rmdir(dirname) == 0)
9591 return true;
9592 else
9593 return false;
9594 }
9595 #endif
9596
9597}
9598
9599bool DeleteFilesInADir(const char* dirname, bool force) {
9600 if (!dirname || strlen(dirname) == 0)
9601 return false;
9602
9603 uint32 count;
9604 char* files = utils::GetFileList(dirname, NULL, count, true);
9605 if (!files)
9606 return true;
9607
9608 const char* name;
9609 for (uint32 n = 0; n<count; n++) {
9610 name = files + (n*(MAXFILENAMELEN+1));
9611 if (!DeleteADir(name, force)) {
9612 delete[] files;
9613 return false;
9614 }
9615 }
9616
9617 delete [] files;
9618 return true;
9619}
9620
9621
9622
9623
9624
9625uint32 TextReplaceCharsInPlace(char* str, uint32 size, char find, char replace) {
9626 uint32 c = 0;
9627 for (uint32 n=0; n<size; n++) {
9628 if (str[n] == find) {
9629 str[n] = replace;
9630 c++;
9631 }
9632 }
9633 return c;
9634}
9635
9636const char* laststrstr(const char* str1, const char* str2) {
9637 const char* strp;
9638 int len1, len2;
9639
9640 len2 = (int)strlen(str2);
9641 if(len2==0)
9642 return (char*)str1;
9643
9644 len1 = (int)strlen(str1);
9645 if (len1 == len2)
9646 return (strcmp(str1, str2) == 0) ? str1 : 0;
9647 else if (len1 - len2 < 0)
9648 return 0;
9649
9650 strp = (char*)(str1 + len1 - len2);
9651 while(strp != str1) {
9652 if(*strp == *str2) {
9653 if(strncmp(strp,str2,len2)==0)
9654 return strp;
9655 }
9656 strp--;
9657 }
9658 return 0;
9659}
9660
9661const char* laststristr(const char* str1, const char* str2) {
9662 const char* strp;
9663 int len1, len2;
9664
9665 len2 = (int)strlen(str2);
9666 if(len2==0)
9667 return (char*)str1;
9668
9669 len1 = (int)strlen(str1);
9670 if (len1 == len2)
9671 return (stricmp(str1, str2) == 0) ? str1 : 0;
9672 else if (len1 - len2 < 0)
9673 return 0;
9674
9675 strp = (char*)(str1 + len1 - len2);
9676 while(strp != str1) {
9677 if(*strp == *str2) {
9678 if(strnicmp(strp,str2,len2)==0)
9679 return strp;
9680 }
9681 strp--;
9682 }
9683 return 0;
9684}
9685
9686bool TextEndsWith(const char* str, const char* end, bool caseSensitive) {
9687 if (!caseSensitive)
9688 return (laststristr(str, end) == str + strlen(str) - strlen(end));
9689 else
9690 return (laststrstr(str, end) == str + strlen(str) - strlen(end));
9691}
9692
9693bool TextStartsWith(const char* str, const char* start, bool caseSensitive) {
9694 if (!caseSensitive)
9695 return (stristr(str, start) == str);
9696 else
9697 return (strstr(str, start) == str);
9698}
9699
9700
9701std::string GetFilePath(const char* filename) {
9702 std::string name = filename;
9703 std::string::size_type p1 = name.find_last_of('/');
9704 std::string::size_type p2 = name.find_last_of('\\');
9705 if (p1 == std::string::npos) {
9706 if (p2 == std::string::npos)
9707 return "";
9708 else
9709 return name.substr(0, p2 + 1);
9710 }
9711 else if (p2 == std::string::npos)
9712 return name.substr(0, p1 + 1);
9713 else
9714 return name.substr(0, (p1 > p2) ? p1 + 1 : p2 + 1);
9715}
9716
9717const char* GetFileBasename(const char* filename) {
9718 std::string name = filename;
9719 std::string::size_type p1 = name.find_last_of('/');
9720 std::string::size_type p2 = name.find_last_of('\\');
9721 if (p1 == std::string::npos) {
9722 if (p2 == std::string::npos)
9723 return filename;
9724 else
9725 return filename + p2 + 1;
9726 }
9727 else if (p2 == std::string::npos)
9728 return filename + p1 + 1;
9729 else
9730 return (p1 > p2) ? filename + p1 + 1 : filename + p2 + 1;
9731}
9732
9733std::string GetCurrentDir() {
9734
9735 char cCurrentPath[FILENAME_MAX];
9736
9737 if (!GetCurrentDirEx(cCurrentPath, sizeof(cCurrentPath)))
9738 {
9739 return "";
9740 }
9741 cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
9742 //printf("The current working directory is %s\n", cCurrentPath);
9743 return cCurrentPath;
9744}
9745
9746char* GetFileList(const char* dirname, const char* ext, uint32& count, bool fullpath, uint32 maxNameLen) {
9747 DIR* dir = opendir(dirname);
9748 if (dir == NULL)
9749 return NULL;
9750
9751 uint32 extlen = (ext == NULL) ? 0 : (uint32)strlen(ext);
9752 struct dirent* direntry = NULL;
9753
9754 uint32 tempMaxCount = 50;
9755 uint32 len = (maxNameLen+1)*tempMaxCount;
9756 char* result = new char[len];
9757 char* dst = result;
9758 char* tmp;
9759 uint32 dirnamelen = (uint32)strlen(dirname);
9760 bool dirslash = (*(dirname + dirnamelen - 1) == '/') || (*(dirname + dirnamelen - 1) == '\\');
9761
9762 count = 0;
9763 direntry = readdir(dir);
9764 while (direntry) {
9765 #ifdef WINDOWS
9766 if (direntry->d_name && direntry->d_name[0] != '\0') {
9767 #else
9768 if (direntry->d_name[0] != '\0') {
9769 #endif
9770 if ( !strcmp(direntry->d_name, ".") || !strcmp(direntry->d_name, "..") ) {
9771 direntry = readdir(dir);
9772 continue;
9773 }
9774 if (ext && extlen && !TextEndsWith(direntry->d_name, ext)) {
9775 direntry = readdir(dir);
9776 continue;
9777 }
9778 if (fullpath) {
9779 utils::strcpyavail(dst, dirname, maxNameLen, true);
9780 if (!dirslash) {
9781 memset(dst+dirnamelen, '/', 1);
9782 utils::strcpyavail(dst+dirnamelen+1, direntry->d_name, maxNameLen, true);
9783 }
9784 else
9785 utils::strcpyavail(dst+dirnamelen, direntry->d_name, maxNameLen, true);
9786 }
9787 else
9788 utils::strcpyavail(dst, direntry->d_name, maxNameLen, true);
9789 dst+= maxNameLen+1;
9790 count++;
9791 if (count >= tempMaxCount) {
9792 tempMaxCount *= 2;
9793 tmp = new char[len*2];
9794 memcpy(tmp, result, len);
9795 delete [] result;
9796 result = tmp;
9797 dst = result + len;
9798 len *= 2;
9799 }
9800 }
9801 direntry = readdir(dir);
9802 }
9803 closedir(dir);
9804 return result;
9805}
9806
9807bool DoesADirExist(const char* dirname) {
9808 FileDetails details = GetFileDetails(dirname);
9809 return (details.doesExist && details.isDirectory);
9810}
9811
9812bool DoesAFileExist(const char* filename) {
9813 FileDetails details = GetFileDetails(filename);
9814 return (details.doesExist && !details.isDirectory);
9815}
9816
9817FileDetails GetFileDetails(const char* filename) {
9818 struct stat statbuf;
9819 int fd, result;
9820
9821 FileDetails info;
9822
9823 info.doesExist = false;
9824 info.isDirectory = false;
9825 info.isReadable = false;
9826 info.isWritable = false;
9827 info.isExecutable = false;
9828 info.size = 0;
9829 info.lastAccessTime = 0;
9830 info.lastModifyTime = 0;
9831 info.creationTime = 0;
9832
9833 // If file cannot be opened
9834 if ((fd = _open(filename, O_RDONLY)) == -1) {
9835 // On Windows, this might be a dir
9836 DIR* dir = opendir(filename);
9837 if (dir == NULL)
9838 return info;
9839 struct dirent* direntry = readdir(dir);
9840
9841 info.doesExist = true;
9842 info.isDirectory = true;
9844 info.isReadable = true;
9845 info.isWritable = true;
9846 info.isExecutable = true;
9847
9848 closedir(dir);
9849 return info;
9850 }
9851
9852 // Get data associated with "fd":
9853 result = fstat(fd, &statbuf);
9854
9855 // Check if statistics are valid:
9856 if( result != 0 ) {
9857 _close(fd);
9858 return info;
9859 }
9860
9861 _close(fd);
9862 info.doesExist = true;
9863
9864 info.size = statbuf.st_size;
9865 info.isDirectory = ((statbuf.st_mode & S_IFDIR) != 0);
9866 info.lastAccessTime = FTime2PsyTime(statbuf.st_atime);
9867 info.lastModifyTime = FTime2PsyTime(statbuf.st_ctime);
9868 info.creationTime = FTime2PsyTime(statbuf.st_ctime);
9869
9870 #ifdef WINDOWS
9871 info.isReadable = ((statbuf.st_mode & _S_IREAD) != 0);
9872 info.isWritable = ((statbuf.st_mode & _S_IWRITE) != 0);
9873 info.isExecutable = ((statbuf.st_mode & _S_IEXEC) != 0);
9874 #else
9875 info.isReadable = ((statbuf.st_mode & S_IRUSR) != 0);
9876 info.isWritable = ((statbuf.st_mode & S_IWUSR) != 0);
9877 info.isExecutable = ((statbuf.st_mode & S_IXUSR) != 0);
9878 #endif
9879
9880 return info;
9881
9882}
9883
9884char* TextSubstringCopy(const char* ascii, uint32 start, uint32 end) {
9885 uint32 len;
9886 char* copy;
9887 if (!ascii || (start >= end) || (!(len = (uint32)strlen(ascii))) ) {
9888 copy = new char[1];
9889 copy[0] = 0;
9890 }
9891 else {
9892 if (end > len - 1)
9893 end = len - 1;
9894 copy = new char[end - start + 2];
9895 memcpy(copy, ascii + start,
9896 end - start + 1);
9897 copy[end - start + 1] = 0;
9898 }
9899 return copy;
9900}
9901
9902
9903bool IsTextNumeric(const char* ascii, uint32 start, uint32 end) {
9904 if (!ascii || (start > end)) return false;
9905 uint32 len = (uint32)strlen(ascii);
9906 uint32 stop = end ? end+1 : len;
9907 if (stop > len) stop = len;
9908 for (uint32 n=start; n<stop; n++) {
9909 if (( ascii[n] < '0' || ascii[n] > '9') && ascii[n] != '.')
9910 return false;
9911 }
9912 return true;
9913}
9914
9915int64 Ascii2Int64(const char* ascii, uint32 start, uint32 end) {
9916 if (!ascii || (start > end)) return false;
9917 if (!end)
9918 #ifdef WINDOWS
9919 return _strtoi64(ascii + start, NULL, 10);
9920 #else
9921 return strtoll(ascii + start, NULL, 10);
9922 #endif
9923 char* copy = TextSubstringCopy(ascii, start, end);
9924 #ifdef WINDOWS
9925 int64 val = _strtoi64(copy, NULL, 10);
9926 #else
9927 int64 val = strtoll(copy, NULL, 10);
9928 #endif
9929 delete[] copy;
9930 return val;
9931}
9932
9933uint64 Ascii2Uint64(const char* ascii, uint32 start, uint32 end) {
9934 if (!ascii || (start > end)) return false;
9935 if (!end)
9936 #ifdef WINDOWS
9937 return _strtoui64(ascii + start, NULL, 10);
9938 #else
9939 return strtoull(ascii + start, NULL, 10);
9940 #endif
9941 char* copy = TextSubstringCopy(ascii, start, end);
9942 #ifdef WINDOWS
9943 uint64 val = _strtoui64(copy, NULL, 10);
9944 #else
9945 uint64 val = strtoull(copy, NULL, 10);
9946 #endif
9947 delete[] copy;
9948 return val;
9949}
9950
9951uint64 AsciiHex2Uint64(const char* ascii, uint32 start, uint32 end) {
9952 if (!ascii || (start > end)) return false;
9953 if (!end)
9954 #ifdef WINDOWS
9955 return _strtoui64(ascii + start, NULL, 16);
9956 #else
9957 return strtoull(ascii + start, NULL, 16);
9958 #endif
9959 char* copy = TextSubstringCopy(ascii, start, end);
9960 #ifdef WINDOWS
9961 uint64 val = _strtoui64(copy, NULL, 16);
9962 #else
9963 uint64 val = strtoull(copy, NULL, 16);
9964 #endif
9965 delete[] copy;
9966 return val;
9967}
9968
9969int32 Ascii2Int32(const char* ascii, uint32 start, uint32 end) {
9970 if (!ascii || (start > end)) return false;
9971 if (!end)
9972 return (int32)strtol(ascii + start, NULL, 10);
9973 char* copy = TextSubstringCopy(ascii, start, end);
9974 int32 val = (int32)strtol(copy, NULL, 10);
9975 delete[] copy;
9976 return val;
9977}
9978
9979uint32 Ascii2Uint32(const char* ascii, uint32 start, uint32 end) {
9980 if (!ascii || (start > end)) return false;
9981 if (!end)
9982 return (uint32)strtoul(ascii + start, NULL, 10);
9983 char* copy = TextSubstringCopy(ascii, start, end);
9984 uint32 val = (uint32)strtoul(copy, NULL, 10);
9985 delete[] copy;
9986 return val;
9987}
9988
9989uint32 AsciiHex2Uint32(const char* ascii, uint32 start, uint32 end) {
9990 if (!ascii || (start > end)) return false;
9991 if (!end)
9992 return (uint32)strtoul(ascii + start, NULL, 16);
9993 char* copy = TextSubstringCopy(ascii, start, end);
9994 uint32 val = (uint32)strtoul(copy, NULL, 16);
9995 delete[] copy;
9996 return val;
9997}
9998
9999float64 Ascii2Float64(const char* ascii, uint32 start, uint32 end) {
10000 if (!ascii || (start > end)) return false;
10001 if (!end)
10002 return strtod(ascii + start, NULL);
10003 char* copy = TextSubstringCopy(ascii, start, end);
10004 float64 val = strtod(copy, NULL);
10005 delete[] copy;
10006 return val;
10007}
10008
10009
10010std::string DecodeJSON(std::string str) {
10011 bool isEscaped = false;
10012 char* tmp = new char[5];
10013 tmp[4] = 0;
10014 std::ostringstream o;
10015 std::string::iterator c;
10016 for (c = str.begin(); c != str.end(); c++) {
10017 if (isEscaped) {
10018 switch (*c) {
10019 case '"': o << "\""; break;
10020 case '\\': o << "\\"; break;
10021 case 'b': o << "\b"; break;
10022 case 'f': o << "\f"; break;
10023 case 'n': o << "\n"; break;
10024 case 'r': o << "\r"; break;
10025 case 't': o << "\t"; break;
10026 case 'u':
10027 c++;
10028 tmp[0] = (uint8)(*c++);
10029 tmp[1] = (uint8)(*c++);
10030 tmp[2] = (uint8)(*c++);
10031 tmp[3] = (uint8)(*c);
10032 o << (char) strtol(tmp, NULL, 16);
10033 break;
10034 default: o << *c;
10035 }
10036 isEscaped = false;
10037 }
10038 else {
10039 switch (*c) {
10040 case '\\': isEscaped = true; break;
10041 default: o << *c;
10042 }
10043 }
10044 }
10045 delete[] tmp;
10046 return o.str();
10047}
10048
10049std::string EncodeJSON(std::string str) {
10050 std::ostringstream o;
10051 std::string::iterator c;
10052 for (c = str.begin(); c != str.end(); c++) {
10053 switch (*c) {
10054 case '"': o << "\\\""; break;
10055 case '\\': o << "\\\\"; break;
10056 case '\b': o << "\\b"; break;
10057 case '\f': o << "\\f"; break;
10058 case '\n': o << "\\n"; break;
10059 case '\r': o << "\\r"; break;
10060 case '\t': o << "\\t"; break;
10061 default:
10062 if ('\x00' <= *c && *c <= '\x1f') {
10063 o << "\\u"
10064 << std::hex << std::setw(4) << std::setfill('0') << (int)*c;
10065 } else {
10066 o << *c;
10067 }
10068 }
10069 }
10070 return o.str();
10071
10072 //if (str.size() == 0)
10073 // return str;
10074 //std::string result = str;
10075 //char c;
10076 //char* tmp = (char*)malloc(20);
10077
10078 //for (uint32 n=0; n<result.size(); n++) {
10079 // switch(c = result[n]) {
10080 // case '\n':
10081 // result.replace(n, 1, "\\n");
10082 // n+=1;
10083 // break;
10084 // case '\r':
10085 // result.replace(n, 1, "\\r");
10086 // n+=1;
10087 // break;
10088 // case '\t':
10089 // result.replace(n, 1, "\\t");
10090 // n+=2;
10091 // break;
10092 // case '"':
10093 // result.replace(n, 1, "\\\"");
10094 // n+=2;
10095 // break;
10096 // case '\\':
10097 // result.replace(n, 1, "\\\\");
10098 // n+=2;
10099 // break;
10100 // case '\b':
10101 // result.replace(n, 1, "\\b");
10102 // n+=2;
10103 // break;
10104 // case '\f':
10105 // result.replace(n, 1, "\\f");
10106 // n+=2;
10107 // break;
10108 // default:
10109 // if ('\x00' <= c && c <= '\x1f') {
10110 // snprintf(tmp, 20, "\\u%.4x;", (int) c & 0xFF);
10111 // result.replace(n, 1, tmp);
10112 // n+=(uint32)strlen(tmp)-1;
10113 // }
10114 // break;
10115 // }
10116 //}
10117
10118 //free((char*)tmp);
10119
10120 //return result;
10121}
10122
10123
10124// Seeds the rand() function
10125bool SeedRandomValues(uint32 seedvalue) {
10126 srand( seedvalue ? seedvalue : (uint32)GetTimeNow());
10127 return true;
10128}
10129
10130// Returns a random value between 0.0 and 1.0
10131double RandomValue() {
10132 double d = 0;
10133 double t = (1.0/((RAND_MAX + 1.0)*(RAND_MAX + 1.0)*(RAND_MAX + 1.0)));
10134 do {
10135 d = (rand () * ((RAND_MAX + 1.0) * (RAND_MAX + 1.0))
10136 + rand () * (RAND_MAX + 1.0)
10137 + rand ()) * t;
10138 } while (d >= 1); /* Round off */
10139 return d;
10140}
10141
10142// Returns a random value between 0.0 and max
10143double RandomValue(double max) {
10144 return RandomValue() * max;
10145}
10146
10147// Returns a random value between from and to
10148double RandomValue(double from, double to) {
10149 if (to < from)
10150 return (RandomValue()*(from-to))+to;
10151 else
10152 return (RandomValue()*(to-from))+from;
10153}
10154
10155// Returns a random value between from and to, rounded to nearest interval
10156double RandomValue(double from, double to, double interval) {
10157 if (to < from)
10158 return RandomValue(to, from, interval);
10159 double r = RandomValue(0, to-from);
10160 uint64 n = (uint64)(r/interval);
10161 double l = r - (n*interval);
10162 if (l >= (0.5*interval))
10163 return from + (n*interval);
10164 else
10165 return from + ((n+1)*interval);
10166}
10167
10168int64 RandomInt(int64 from, int64 to) {
10169 return (int64)roundl(RandomValue((double)from, (double)to));
10170}
10171
10172
10173//std::string BytifySize(int32 val) {
10174// return BytifySize((double)val);
10175//}
10176
10177std::string BytifySize(double val) {
10178
10179 double kb = 1024;
10180 double mb = kb*1024;
10181 double gb = mb*1024;
10182 double tb = gb*1024;
10183
10184 char *tmp = new char[64];
10185
10186 if (val < 512)
10187 snprintf(tmp, 64, "%.2f B", val);
10188 else if (val < 512*kb) {
10189 val = val / kb;
10190 snprintf(tmp, 64, "%.2f KB", val);
10191 }
10192 else if (val < 512*mb) {
10193 val = val / mb;
10194 snprintf(tmp, 64, "%.2f MB", val);
10195 }
10196 else if (val < 512*gb) {
10197 val = val / gb;
10198 snprintf(tmp, 64, "%.2f GB", val);
10199 }
10200 else {
10201 val = val / tb;
10202 snprintf(tmp, 64, "%.2f TB", val);
10203 }
10204
10205 std::string result = tmp;
10206 delete [] tmp;
10207 return result;
10208}
10209
10210//std::string BytifySizes(int32 val1, int32 val2) {
10211// return BytifySizes((double)val1, (double) val2);
10212//}
10213
10214std::string BytifySizes(double val1, double val2) {
10215
10216 double kb = 1024;
10217 double mb = kb*1024;
10218 double gb = mb*1024;
10219 double tb = gb*1024;
10220
10221 char *tmp = new char[64];
10222 char *end = new char[64];
10223
10224 double val;
10225 double maximum = ((val1 > val2) ? val1 : val2);
10226
10227 if (maximum < 512) {
10228 val = 1;
10229 utils::strcpyavail(end, "B", 32, true);
10230 }
10231 else if (maximum < 512*kb) {
10232 val = kb;
10233 utils::strcpyavail(end, "KB", 32, true);
10234 }
10235 else if (maximum < 512*mb) {
10236 val = mb;
10237 utils::strcpyavail(end, "MB", 32, true);
10238 }
10239 else if (maximum < 512*gb) {
10240 val = gb;
10241 utils::strcpyavail(end, "GB", 32, true);
10242 }
10243 else {
10244 val = gb;
10245 utils::strcpyavail(end, "TB", 32, true);
10246 }
10247 snprintf(tmp, 64, "%.2f / %.2f %s", ((double)val1)/val, ((double)val2)/val, (char*) end);
10248
10249 std::string result = tmp;
10250 delete [] tmp;
10251 delete [] end;
10252 return result;
10253
10254}
10255
10256//std::string BytifyRate(int32 val) {
10257// return BytifyRate((double)val);
10258//}
10259
10260std::string BytifyRate(double val) {
10261 char *tmp = new char[64];
10262 snprintf(tmp, 64, "%s/sec", (char*) BytifySize(val).c_str());
10263 std::string result = tmp;
10264 delete [] tmp;
10265 return result;
10266}
10267
10268//std::string BytifyRates(int32 val1, int32 val2) {
10269// return BytifyRates((double)val1, (double)val2);
10270//}
10271
10272std::string BytifyRates(double val1, double val2) {
10273 char *tmp = new char[64];
10274 snprintf(tmp, 64, "%s/sec", (char*) BytifySizes(val1, val2).c_str());
10275 std::string result = tmp;
10276 delete [] tmp;
10277 return result;
10278}
10279
10280
10281
10282
10283
10284
10285
10286#ifdef WINDOWS
10287
10288uint32 ReadRegistryDWORD(const char* key, const char* entry) {
10289 HKEY hKeyRoot, hKey;
10290 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10291
10292 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10293 if (err != ERROR_SUCCESS)
10294 return 0;
10295
10296 DWORD dwType = REG_DWORD;
10297 DWORD numVal = 0;
10298 DWORD dwSize = sizeof(numVal);
10299
10300 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)&numVal, &dwSize);
10301 RegCloseKey(hKey);
10302 if (err != ERROR_SUCCESS)
10303 return 0;
10304 return numVal;
10305}
10306
10307uint64 ReadRegistryQWORD(const char* key, const char* entry) {
10308 HKEY hKeyRoot, hKey;
10309 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10310
10311 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10312 if (err != ERROR_SUCCESS)
10313 return 0;
10314
10315 DWORD dwType = REG_QWORD;
10316 uint64 numVal = 0;
10317 DWORD dwSize = sizeof(numVal);
10318
10319 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)&numVal, &dwSize);
10320 RegCloseKey(hKey);
10321 if (err != ERROR_SUCCESS)
10322 return 0;
10323 return numVal;
10324}
10325
10326std::string ReadRegistryString(const char* key, const char* entry) {
10327 HKEY hKeyRoot, hKey;
10328 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10329
10330 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10331 if (err != ERROR_SUCCESS) {
10332 return "";
10333 }
10334
10335 DWORD dwType = REG_SZ;
10336 DWORD dwSize = 4096;
10337 char* lszValue = new char[dwSize];
10338
10339 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)lszValue, &dwSize);
10340 RegCloseKey(hKey);
10341 if (err != ERROR_SUCCESS) {
10342 delete[] lszValue;
10343 return "";
10344 }
10345
10346 std::string val = lszValue;
10347 delete[] lszValue;
10348 return val;
10349}
10350
10351bool WriteRegistryDWORD(const char* key, const char* entry, uint32 value) {
10352 DWORD dwDisposition;
10353 HKEY hKeyRoot, hKey;
10354 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10355
10356 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_WRITE | KEY_WOW64_64KEY, &hKey);
10357 if (err != ERROR_SUCCESS) {
10358 err = RegCreateKeyEx(hKeyRoot, keySubName.c_str(), 0, NULL, 0, KEY_WRITE | KEY_WOW64_64KEY, NULL, &hKey, &dwDisposition);
10359 if (err != ERROR_SUCCESS)
10360 return false;
10361 }
10362
10363 DWORD dwType = REG_DWORD;
10364 err = RegSetValueEx(hKey, entry, 0, dwType, (const BYTE*)&value, sizeof(value));
10365 RegCloseKey(hKey);
10366 return (err == ERROR_SUCCESS);
10367}
10368
10369bool WriteRegistryQWORD(const char* key, const char* entry, uint64 value) {
10370 DWORD dwDisposition;
10371 HKEY hKeyRoot, hKey;
10372 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10373
10374 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_WRITE | KEY_WOW64_64KEY, &hKey);
10375 if (err != ERROR_SUCCESS) {
10376 err = RegCreateKeyEx(hKeyRoot, keySubName.c_str(), 0, NULL, 0, KEY_WRITE | KEY_WOW64_64KEY, NULL, &hKey, &dwDisposition);
10377 if (err != ERROR_SUCCESS)
10378 return false;
10379 }
10380
10381 DWORD dwType = REG_QWORD;
10382 err = RegSetValueEx(hKey, entry, 0, dwType, (const BYTE*)&value, sizeof(value));
10383 RegCloseKey(hKey);
10384 return (err == ERROR_SUCCESS);
10385}
10386
10387bool WriteRegistryString(const char* key, const char* entry, const char* value) {
10388 DWORD dwDisposition;
10389 HKEY hKeyRoot, hKey;
10390 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10391
10392 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_WRITE | KEY_WOW64_64KEY, &hKey);
10393 if (err != ERROR_SUCCESS) {
10394 err = RegCreateKeyEx(hKeyRoot, keySubName.c_str(), 0, NULL, 0, KEY_WRITE | KEY_WOW64_64KEY, NULL, &hKey, &dwDisposition);
10395 if (err != ERROR_SUCCESS)
10396 return false;
10397 }
10398
10399 DWORD dwType = REG_SZ;
10400 DWORD dwSize = 4096;
10401
10402 err = RegSetValueEx(hKey, entry, 0, dwType, (LPBYTE)value, (DWORD)(strlen(value) + 1));
10403 RegCloseKey(hKey);
10404 return (err == ERROR_SUCCESS);
10405}
10406
10407bool DeleteRegistryEntry(const char* key, const char* entry) {
10408 HKEY hKeyRoot, hKey;
10409 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10410
10411 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_SET_VALUE | KEY_WOW64_64KEY, &hKey);
10412 if (err != ERROR_SUCCESS)
10413 return false;
10414
10415 //std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10416 err = RegDeleteValue(hKey, entry);
10417 return (err == ERROR_SUCCESS);
10418}
10419
10420bool DeleteRegistryKey(const char* entry) {
10421 // https://msdn.microsoft.com/en-us/library/aa379776(VS.85).aspx
10422
10423 HKEY hKeyRoot;
10424 std::string keySubName = GetRegistryKeyInfo(entry, hKeyRoot);
10425 uint32 err = RegDeleteKeyEx(hKeyRoot, keySubName.c_str(), KEY_WOW64_64KEY, 0);
10426 return (err == ERROR_SUCCESS);
10427}
10428
10429bool DeleteRegistryTree(const char* root, const char* key) {
10430 if (!key || !strlen(key))
10431 return false;
10432
10433 HKEY hKey;
10434 HKEY hKeyRoot;
10435 std::string keySubName = GetRegistryKeyInfo(root, hKeyRoot);
10436 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, DELETE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE | KEY_WOW64_64KEY, &hKey);
10437 if (err != ERROR_SUCCESS)
10438 return false;
10439
10440 err = RegDeleteTree(hKey, key);
10441 return (err == ERROR_SUCCESS);
10442}
10443
10444//bool CopyRegistryKey(const char* key, const char* newName) {
10445//}
10446
10447bool CopyRegistryTree(const char* entry, const char* newName) {
10448 // https://msdn.microsoft.com/en-us/library/aa379768(VS.85).aspx
10449
10450 // access 64 or 32-bit registry: https://msdn.microsoft.com/en-us/library/aa384129(v=vs.85).aspx
10451 // we always use the 64-bit registry here
10452
10453 DWORD dwDisposition;
10454 HKEY hKey;
10455 HKEY hKeyRoot;
10456 HKEY hKeyNew;
10457 HKEY hKeyNewRoot;
10458 uint32 err;
10459
10460 std::string keySubName = GetRegistryKeyInfo(entry, hKeyRoot);
10461 std::string keySubNewName = GetRegistryKeyInfo(newName, hKeyNewRoot);
10462
10463 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10464 if (err != ERROR_SUCCESS)
10465 return false;
10466
10467 err = RegCreateKeyEx(hKeyNewRoot, keySubNewName.c_str(), 0, NULL, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, NULL, &hKeyNew, &dwDisposition);
10468 if (err != ERROR_SUCCESS) {
10469 RegCloseKey(hKey);
10470 return false;
10471 }
10472
10473 err = RegCopyTree(hKey, NULL, hKeyNew);
10474
10475 RegCloseKey(hKey);
10476 RegCloseKey(hKeyNew);
10477
10478 if (err != ERROR_SUCCESS) {
10479 RegDeleteKeyEx(hKeyNewRoot, keySubNewName.c_str(), KEY_WOW64_64KEY, 0);
10480 return false;
10481 }
10482 return true;
10483}
10484
10485//bool RenameRegistryKey(const char* key, const char* newName) {
10486// if (!CopyRegistryKey(key, newName))
10487// return false;
10488// if (!DeleteRegistryKey(key)) {
10489// CopyRegistryKey(newName, key);
10490// return false;
10491// }
10492// return true;
10493//}
10494
10495//bool RenameRegistryTree(const char* entry, const char* newName) {
10496 //if (!CopyRegistryTree(entry, newName))
10497 // return false;
10498 //if (!DeleteRegistryTree(entry)) {
10499 // CopyRegistryTree(newName, entry);
10500 // return false;
10501 //}
10502// return true;
10503//}
10504
10505std::string GetRegistryKeyInfo(const char* key, HKEY &hKeyRoot) {
10506 std::vector<std::string> path = utils::TextListSplit(key, "\\");
10507 if (!path.size()) path = utils::TextListSplit(key, "/");
10508 if (path.size() < 2) return false;
10509 if (stristr(path.at(0).c_str(), "HKEY_CLASSES_ROOT"))
10510 hKeyRoot = HKEY_CLASSES_ROOT;
10511 else if (stristr(path.at(0).c_str(), "HKEY_CURRENT_USER"))
10512 hKeyRoot = HKEY_CURRENT_USER;
10513 else if (stristr(path.at(0).c_str(), "HKEY_LOCAL_MACHINE"))
10514 hKeyRoot = HKEY_LOCAL_MACHINE;
10515 else if (stristr(path.at(0).c_str(), "HKEY_USERS"))
10516 hKeyRoot = HKEY_USERS;
10517 return utils::TextJoin(path, "\\", 1, (DWORD)(path.size() - 1));
10518}
10519
10520std::string GetRegistryParentKeyInfo(const char* key, HKEY &hKeyRoot) {
10521 std::vector<std::string> path = utils::TextListSplit(key, "\\");
10522 if (!path.size()) path = utils::TextListSplit(key, "/");
10523 if (path.size() < 2) return false;
10524 if (stristr(path.at(0).c_str(), "HKEY_CLASSES_ROOT"))
10525 hKeyRoot = HKEY_CLASSES_ROOT;
10526 else if (stristr(path.at(0).c_str(), "HKEY_CURRENT_USER"))
10527 hKeyRoot = HKEY_CURRENT_USER;
10528 else if (stristr(path.at(0).c_str(), "HKEY_LOCAL_MACHINE"))
10529 hKeyRoot = HKEY_LOCAL_MACHINE;
10530 else if (stristr(path.at(0).c_str(), "HKEY_USERS"))
10531 hKeyRoot = HKEY_USERS;
10532 return utils::TextJoin(path, "\\", 1, (DWORD)(path.size() - 2));
10533}
10534
10535
10536#else // WINDOWS
10537 int32 ReadRegistryDWORD(const char* key) { return 0; }
10538 int64 ReadRegistryQWORD(const char* key) { return 0; }
10539 std::string ReadRegistryString(const char* key) { return ""; }
10540 bool WriteRegistryDWORD(const char* key, int32 value) { return false; }
10541 bool WriteRegistryQWORD(const char* key, int64 value) { return false; }
10542 bool WriteRegistryString(const char* key, const char* value) { return false; }
10543 bool DeleteRegistryKey(const char* key) { return false; }
10544 bool DeleteRegistryTree(const char* key) { return false; }
10545 //bool CopyRegistryKey(const char* key, const char* newName) { return false; }
10546 bool CopyRegistryTree(const char* entry, const char* newName) { return false; }
10547 //bool RenameRegistryKey(const char* key, const char* newName) { return false; }
10548 bool RenameRegistryTree(const char* entry, const char* newName) { return false; }
10549#endif // WINDOWS
10550
10551
10552
10553} // namespace utils
10554
10555// Adapters so the utils:: free-function tests can be registered as bool() pointers.
10556static bool Test_Utils() { return utils::UnitTest_Utils(); }
10563static bool Test_Timer() { return utils::UnitTest_Timer(); }
10564
10567 "Bitfield slot allocation: SetBit/SetBitN, first-free and last-occupied searches", "util");
10569 "Timer scheduling and trigger delivery via waitForTimer", "util");
10571 "ProbeProcessWait: stdin-blocked child detected, busy child not flagged, cpuTimeMs grows", "util");
10573 "A child launched with the shutdown signals blocked (as in Psyclone) still stops on SIGTERM", "util");
10575 "A named mutex whose owner died holding it (process or thread) can be taken again", "util");
10577 "A named segment/Mutex/Semaphore/Event stays the same object after another user closes it", "util");
10578 UnitTestRunner::instance().registerTest("utils_semaphore_userdeath", Test_SemaphoreUserDeath,
10579 "A named semaphore still works after a user process was killed inside wait()/signal()", "util");
10581 "A named event still wakes waiters after a user process was killed inside waitNext()/signal()", "util");
10582}
10583
10584} // namespace cmlabs
10585
10586
HTML/URL helper utilities: entity encoding/decoding, MIME type lookup and URL component parsing.
#define PROC_ERROR
Error state.
Definition MemoryMaps.h:153
Object type ids used to tag and verify every binary structure in CMSDK memory.
#define CONSTCHARID
Definition ObjectIDs.h:38
#define CHARDATAID
Definition ObjectIDs.h:40
#define CONSTCHARINFOID
Definition ObjectIDs.h:43
#define DOUBLEID
Definition ObjectIDs.h:42
#define DATAMESSAGEINFOID
Definition ObjectIDs.h:69
#define LOGENTRYID
Definition ObjectIDs.h:55
#define DATAMESSAGEID
Definition ObjectIDs.h:75
#define INTID
Definition ObjectIDs.h:41
#define CHARDATAINFOID
Definition ObjectIDs.h:44
#define TIMEID
Definition ObjectIDs.h:39
#define strnicmp
Definition Standard.h:188
Process-wide thread registry and lifecycle manager: the concurrency core of CMSDK.
#define BITOCCUPIED
Definition Types.h:34
#define BITFREE
Definition Types.h:33
#define MAXVALUINT16
Definition Types.h:85
#define MAXVALUINT32
Definition Types.h:87
Small, dependency-free unit test harness used by all CMSDK object tests.
#define poly
Definition Utils.cpp:9206
Cross-platform utility toolbox for CMSDK: threading, synchronization, shared memory,...
#define LOGPRINT
Definition Utils.h:227
#define WINSHMEMSPACE
Definition Utils.h:82
#define SD_BOTH
Definition Utils.h:168
#define MAXKEYNAMELEN
Definition Utils.h:85
#define OSCPU_IA64
Definition Utils.h:174
#define LOG_SYSTEM
Definition Utils.h:214
#define OSCPU_X86
Definition Utils.h:172
#define OSCPU_UNKNOWN
Definition Utils.h:171
#define LOGDEBUG
Definition Utils.h:228
#define thread_ret_val(ret)
Definition Utils.h:131
#define EVENTMEMSIZE
Definition Utils.h:160
#define INVALID_SOCKET
Definition Utils.h:137
#define GetCurrentDirEx
Definition Utils.h:79
#define CHECKNETWORKINIT
Definition Utils.h:1622
#define THREAD_STATS_ADHOC
Definition Utils.h:102
#define closesocket(X)
Definition Utils.h:138
#define THREAD_STATS_OFF
Definition Utils.h:100
#define SEMAPHOREMEMSIZE
Definition Utils.h:161
#define WSAEWOULDBLOCK
Definition Utils.h:1623
#define THREAD_RET
Definition Utils.h:127
#define stricmp
Definition Utils.h:132
#define LOCALHOSTIP
Definition Utils.h:1681
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define SOCKET_ERROR
Definition Utils.h:136
#define LogPrint
Definition Utils.h:330
#define MAXFILENAMELEN
Definition Utils.h:89
#define MALLOC(x)
Definition Utils.h:1682
THREAD_RET(* THREAD_FUNCTION)(void *)
Definition Utils.h:128
#define LOG_NETWORK
Definition Utils.h:215
#define THREAD_STATS_AUTO
Definition Utils.h:101
#define MUTEXMEMSIZE
Definition Utils.h:158
#define ThreadHandle
Definition Utils.h:125
#define OSCPU_AMD64
Definition Utils.h:173
#define MAXSHMEMNAMELEN
Definition Utils.h:90
struct sockaddr SOCKADDR
Definition Utils.h:135
#define LOG_MAXCOUNT
Definition Utils.h:225
#define THREAD_ARG
Definition Utils.h:130
#define SOCKET
Definition Utils.h:134
RAII guard whose single static instance triggers global utility cleanup at program exit.
Definition Utils.h:195
CleanShutdown()
Default constructor; no side effects.
Definition Utils.cpp:75
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Definition Utils.cpp:79
Callback interface for receiving log entries produced through LogSystem.
Definition Utils.h:273
Process-wide singleton logging hub with per-topic verbosity/debug levels.
Definition Utils.h:289
char * logfile
Definition Utils.h:326
static bool SetLogFileOutput(const char *logfile, bool printOut=true)
Direct log output to a file.
Definition Utils.cpp:315
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:209
bool printToStdOut
Definition Utils.h:327
static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style informational logging (usually invoked via the LogPrint macro).
Definition Utils.cpp:346
static bool LogSystemDebug(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style debug logging (usually invoked via the LogDebug macro); same parameters as LogSystemPrin...
Definition Utils.cpp:394
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
Definition Utils.h:295
static bool SetLogLevelDebug(uint8 level)
Set the debug level threshold for all topics.
Definition Utils.cpp:220
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
Definition Utils.cpp:244
static bool Shutdown()
Terminate all managed threads, then destroy the singleton.
static UnitTestRunner & instance()
Access the singleton (created on first use).
void registerTest(const char *name, UnitTestFunc func, const char *description="", const char *category="", bool inDefaultRun=true, uint32 timeoutSec=0)
Register a test with the runner.
Singleton snapshot of the parsed process command line (set via SetCommandLine()).
Definition Utils.h:1499
static CommandLineInfo * CommandLineInfoSingleton
Definition Utils.h:1501
Auto-reset notification event (condition variable style), optionally named for cross-process use.
Definition Utils.h:567
pthread_cond_t * event
Definition Utils.h:586
bool waitNext()
Block until the next signal() occurs.
Definition Utils.cpp:2165
Event()
Create an anonymous, process-local event.
Definition Utils.cpp:2097
bool signal()
Wake all threads currently waiting on this event.
Definition Utils.cpp:2193
pthread_mutex_t * mutex
Definition Utils.h:587
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
Definition Utils.h:1539
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
Definition Utils.cpp:6877
static std::string patchLibraryFilename(const char *filename, const char *path=NULL)
Normalize a library name into a platform filename (adds lib prefix / .dll, .so, .dylib suffix and opt...
Definition Utils.cpp:6753
bool load(const char *filename)
Load a library.
Definition Utils.cpp:6784
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:480
Mutex()
Create an anonymous, process-local mutex.
Definition Utils.cpp:1393
void setCancelSafe(bool on)
Make this mutex cancellation-safe (POSIX only; no-op on Windows).
Definition Utils.cpp:1369
bool leave()
Release the mutex.
Definition Utils.cpp:1704
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1512
pthread_mutex_t * mutex
Definition Utils.h:526
Counting semaphore, optionally named for cross-process use.
Definition Utils.h:536
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
Definition Utils.cpp:1876
bool signal()
Increment (release) the semaphore, waking one waiter.
Definition Utils.cpp:2006
bool wait()
Block until the semaphore can be decremented.
Definition Utils.cpp:1969
Multiplexing timer: schedule many periodic timers and consume their expiries from one queue.
Definition Utils.h:703
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
Definition Utils.cpp:2265
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
Definition Utils.h:706
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
Definition Utils.cpp:2389
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
Definition Utils.cpp:2411
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
Definition Utils.cpp:2362
uint64 FTime2PsyTime(uint64 t)
Convert an ftime-style value (ms since Unix epoch) to a PsyTime µs timestamp.
Definition PsyTime.cpp:758
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
std::string PrintTimeNowString(bool local=true, bool us=true, bool ms=true)
Format GetTimeNow().
Definition PsyTime.cpp:672
std::string PrintTimeDifString(uint64 t, bool us=true, bool ms=true)
Definition PsyTime.cpp:722
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
Definition PsyTime.cpp:35
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
Definition PsyTime.cpp:25
bool UnitTest_Utils()
Aggregate self test for miscellaneous utils functionality.
Definition Utils.cpp:3012
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
Definition Utils.cpp:4068
bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows)
Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).
Definition Utils.cpp:6509
uint32 NewProcess(const char *cmdline, const char *initdir=NULL, const char *title=NULL, int16 x=-1, int16 y=-1, int16 w=-1, int16 h=-1)
Launch a detached child process.
Definition Utils.cpp:5356
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
Definition Utils.cpp:1313
static std::map< uint32, ProcessData * > * ProcessInformationMap
Definition Utils.h:666
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
Definition Utils.cpp:4541
bool UnitTest_MutexOwnerDeath()
Definition Utils.cpp:2626
void ReleaseProcessCapture(uint32 proc)
POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captur...
Definition Utils.cpp:5554
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
Definition Utils.cpp:4266
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
Definition Utils.cpp:1177
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
Definition Utils.cpp:4933
bool UnitTest_ChildSignalMask()
Self test: a child launched with the shutdown signals blocked still stops on SIGTERM (POSIX).
Definition Utils.cpp:2588
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
Definition Utils.h:623
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
Definition Utils.cpp:5023
bool CloseProcessInput(uint32 proc)
Close a child's stdin, delivering EOF (T1.1 step 2.7c).
Definition Utils.cpp:6318
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
Definition Utils.cpp:5572
#define PROC_RUNNING
Definition Utils.h:1317
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
Definition Utils.h:626
static Mutex * SharedMemorySemaphoreMapMutex
Definition Utils.h:624
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
Definition Utils.cpp:3965
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
Definition Utils.cpp:9636
uint32 RemovePortSharedSegments(uint16 port)
Remove every shared-memory/semaphore name for this port (as ClearStaleSharedSegments,...
Definition Utils.cpp:3627
std::pair< std::string, Event * > SharedMemoryEventMapPair
Definition Utils.h:629
bool DestroyEvent(const char *name)
Destroy a named global event.
Definition Utils.cpp:1292
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
Definition Utils.cpp:1136
static SharedMemoryFileHandleMapType * SharedMemoryFileHandleMap
Definition Utils.h:412
bool TextStartsWith(const char *str, const char *start, bool caseSensitive=true)
Test whether str starts with start.
Definition Utils.cpp:9693
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
Definition Utils.cpp:4956
bool ReadProcessTerminal(uint32 proc, std::string &out, bool &eofOut)
Non-blocking read of the merged terminal stream.
Definition Utils.cpp:6462
bool GetProcAndOSCPUUsage(double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
Sample CPU usage of this process and of the whole OS since the previous call.
Definition Utils.cpp:4758
bool UnitTest_SemaphoreUserDeath()
Definition Utils.cpp:2891
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
Definition Utils.cpp:4441
uint32 NewProcessTerminal(const char *cmdline, const char *initdir, const std::map< std::string, std::string > *env, uint16 cols=0, uint16 rows=0)
Launch a child on a new pseudo-terminal (POSIX: posix_openpt + fork; child setsid() + TIOCSCTTY so it...
Definition Utils.cpp:6392
static std::map< std::string, Event * > * SharedMemoryEventMap
Definition Utils.h:628
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
Definition Utils.cpp:5105
bool WriteProcessTerminal(uint32 proc, const char *data, uint32 len)
Write bytes to the child's terminal input (its stdin).
Definition Utils.cpp:6487
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
Definition Utils.cpp:4511
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
Definition Utils.cpp:4144
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
Definition Utils.cpp:4058
uint32 NewProcessEx(const char *cmdline, const char *initdir, const char *title, const std::map< std::string, std::string > *env, bool captureOutput, bool ignoreOutput, bool newProcessGroup, int posixParentDeathSig=0, bool posixUseShell=false)
Launch a child with environment overrides and optional output capture.
Definition Utils.cpp:6039
static std::map< uint32, DrumBeatInfo > * DrumBeatMap
Definition Utils.h:458
bool SignalThread(ThreadHandle hThread, int32 signal)
Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
Definition Utils.cpp:5047
bool UnitTest_EventUserDeath()
Definition Utils.cpp:2946
bool BlockShutdownSignals()
Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.
Definition Utils.cpp:4390
bool UnitTest_ProbeProcessWait()
Definition Utils.cpp:2527
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
Definition Utils.cpp:3380
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
Definition Utils.cpp:4048
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
Definition Utils.cpp:1318
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
Definition Utils.cpp:868
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
Definition Utils.cpp:945
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
Definition Utils.cpp:9661
bool ProbeProcessWait(uint32 pid, ProcessWaitInfo &out)
Probe whether a child process (group) appears blocked reading stdin (fd 0).
Definition Utils.cpp:5817
static Mutex * SharedMemoryMutexMapMutex
Definition Utils.h:621
#define SharedMemoryFileHandleMapType
Definition Utils.h:410
bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
Create a periodic timer ("drum beat") that calls func every interval ms.
Definition Utils.cpp:769
bool ReapThread(ThreadHandle &hThread)
Definition Utils.cpp:4224
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
Definition Utils.cpp:4088
bool UnlinkSharedMemorySegment(char *data)
Remove a segment's name now, whoever created it; every existing mapping stays valid.
Definition Utils.cpp:3548
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
Definition Utils.cpp:5489
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
Definition Utils.h:435
static Mutex * SharedMemoryEventMapMutex
Definition Utils.h:627
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
Definition Utils.cpp:1095
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
Definition Utils.cpp:985
int RunOSCommand(const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
Run a command synchronously and capture its output.
Definition Utils.cpp:5151
char * CreateSharedMemorySegment(const char *name, uint64 size, bool force=false)
Create a named shared memory segment and map it into this process.
Definition Utils.cpp:3247
std::string PrintBitFieldString(const char *bitfield, uint32 bytesize, uint32 size, const char *title)
Like GetBitFieldAsString() but prefixed with title and formatted for printing.
Definition Utils.cpp:4009
std::string GetBitFieldAsString(const char *bitfield, uint32 bytesize, uint32 size)
Render the first size bits as a '0'/'1' string, for debugging.
Definition Utils.cpp:3990
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
Definition Utils.cpp:6549
uint32 GetLocalProcessID()
Get the OS process id of the current process.
Definition Utils.cpp:5142
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
Definition Utils.cpp:901
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
Definition Utils.cpp:1211
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
Definition Utils.cpp:3491
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
Definition Utils.cpp:4316
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
Definition Utils.cpp:3722
bool StartSignalThread(ShutdownSignalCallback cb)
Start the dedicated signal-handling thread (POSIX only).
Definition Utils.cpp:4402
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
Definition Utils.cpp:4461
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
Definition Utils.cpp:4038
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
Definition Utils.cpp:5063
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
Definition Utils.cpp:4190
void(* ShutdownSignalCallback)(int sig, int count)
Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.
Definition Utils.h:1186
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
Definition Utils.cpp:998
bool UnitTest_SharedNames()
Definition Utils.cpp:2733
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
Definition Utils.cpp:4450
#define PROC_TERMINATED
Definition Utils.h:1315
bool DisownSharedMemorySegment(char *data)
Give up this process's ownership of a segment's name, so closing it here only unmaps.
Definition Utils.cpp:3529
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
Definition Utils.cpp:8470
void CloseProcessTerminal(uint32 proc)
Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked term...
Definition Utils.cpp:6526
std::list< std::string > GetProgramTrace()
Capture the current call stack.
Definition Utils.cpp:4103
uint64 hton64(const uint64_t *input)
Convert a 64-bit value from host to network byte order.
static uint16 SharedSystemInstance
Definition Utils.h:414
static void TimerCallback(int sig, siginfo_t *siginfo, void *context)
POSIX signal-based timer callback trampoline (SIGEV_SIGNAL); routes the expiry into the owning Timer'...
Definition Utils.cpp:2447
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
Definition Utils.cpp:8435
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
Definition Utils.h:622
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
Definition Utils.cpp:3690
bool SignalEvent(const char *name)
Signal a named global event.
Definition Utils.cpp:1279
bool WriteProcessInput(uint32 proc, const char *data, uint32 len)
Write to the stdin of a child launched with captureOutput=true (T1.1 step 2.7c).
Definition Utils.cpp:6288
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
Definition Utils.cpp:4553
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
Definition Utils.cpp:8509
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
Definition Utils.cpp:3940
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
Definition Utils.cpp:3659
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
Definition Utils.cpp:4711
bool ReadProcessOutput(uint32 proc, std::string &out, std::string &err)
Read any pending captured stdout/stderr from a child launched with captureOutput=true.
Definition Utils.cpp:6334
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
Definition Utils.cpp:4975
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
Definition Utils.h:625
bool StopSignalThread()
Stop the dedicated signal thread and join it.
Definition Utils.cpp:4425
bool SendProcessBreak(uint32 proc, int sig)
Attempt a graceful stop: POSIX sends the given signal; Windows posts a CTRL_BREAK to the child's proc...
Definition Utils.cpp:6538
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
Definition Utils.cpp:3877
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
Definition Utils.cpp:3684
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
Definition Utils.cpp:822
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
Definition Utils.cpp:9686
bool UnitTest_Timer()
Self test for the Timer class.
Definition Utils.cpp:2460
#define PROC_TIMEOUT
Definition Utils.h:1318
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
Definition Utils.cpp:3845
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
Definition Utils.cpp:4501
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
Definition Utils.cpp:5083
bool TryReapThread(ThreadHandle &hThread)
Definition Utils.cpp:4240
bool UtilsTest()
Run the built-in self test of the utils module.
Definition Utils.cpp:8393
#define PROCBUFSIZE
Definition Utils.h:1332
uint32 Calc32BitFieldSize(uint32 bitsize)
Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
Definition Utils.cpp:3680
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
Definition Utils.cpp:9625
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:8491
void ClearStaleSharedSegments(uint16 port)
Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.
Definition Utils.cpp:3648
std::pair< uint32, ProcessData * > Proc_Pair
Definition Utils.h:667
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
Definition Utils.cpp:4876
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
Definition Utils.cpp:4481
std::string EncodeHTML(std::string str)
Encode a plain string for safe embedding in HTML (e.g.
Definition HTML.cpp:51
void fail(const char *fmt,...)
Set an explanatory reason shown on the FAIL line.
void metric(const char *name, double value, const char *unit="", bool higherIsBetter=true)
Record a performance metric.
void detail(const char *fmt,...)
Verbose-only indented diagnostic line (shown only when verbose=1).
void progress(int percent, const char *action)
Report progress with a short description of the current action.
static pthread_mutex_t SharedSegmentLock
Definition Utils.cpp:1038
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
Definition Utils.cpp:10125
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:7662
static THREAD_RET THREAD_FUNCTION_CALL SignalThreadMain(THREAD_ARG arg)
Definition Utils.cpp:4370
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
Definition Utils.cpp:7672
static bool AnyCancelSafeMutexes()
Definition Utils.cpp:1351
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
Definition Utils.cpp:8787
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
Definition Utils.cpp:9195
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
Definition Utils.cpp:8074
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
Definition Utils.cpp:10049
unsigned char * Ascii2UTF16LE(const char *ascii, uint32 len, uint32 &size)
Convert 8-bit ASCII text to UTF-16LE (used for Windows wide APIs and some protocols).
Definition Utils.cpp:7507
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
Definition Utils.cpp:6977
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
Definition Utils.cpp:8672
uint64 ReadRegistryQWORD(const char *key, const char *entry)
Read a 64-bit registry value.
static std::map< uint32, int > * TerminalMasterMap
Definition Utils.cpp:6382
std::string GetCommandLineArg(uint16 n)
Get the n-th positional command line item.
Definition Utils.cpp:6712
static void RegisterSharedSegment(void *data, const char *path, uint64 size, bool created)
Definition Utils.cpp:1042
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
Definition Utils.cpp:9488
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
Definition Utils.cpp:10272
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
Definition Utils.cpp:9440
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
Definition Utils.cpp:9599
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
Definition Utils.cpp:6706
uint16 GetCPUArchitecture()
CPU architecture id.
Definition Utils.cpp:7068
char OSLocalHostName[1024]
Definition Utils.cpp:6926
char OSArchitectureName[1024]
Definition Utils.cpp:6927
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:9232
static uint32 g_shutdownSignalCount
Definition Utils.cpp:4368
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:9001
static void SetSemaphoreOwnsName(const void *sem, bool owns)
Definition Utils.cpp:1066
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
Definition Utils.cpp:8542
static std::condition_variable & gLaunchCv
Definition Utils.cpp:6001
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
Definition Utils.cpp:9214
static pthread_mutex_t g_cancelSafeSetLock
Definition Utils.cpp:1331
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:7720
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
Definition Utils.cpp:8000
bool WaitForNextEvent(const char *name, uint32 ms, bool autocreate)
Definition Utils.cpp:1240
static volatile int g_cancelSafeCount
Definition Utils.cpp:1349
const char * GetSystemArchitecture()
Architecture name string, e.g.
Definition Utils.cpp:7216
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
Definition Utils.cpp:8604
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:6666
static bool EventWordWait(void *data, uint32 timeoutMS, bool infinite)
Definition Utils.cpp:2064
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
Definition Utils.cpp:6724
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
Definition Utils.cpp:7769
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
Definition Utils.cpp:9979
uint64 GetCPUSpeed()
Nominal CPU clock speed.
Definition Utils.cpp:7105
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
Definition Utils.cpp:8692
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
Definition Utils.cpp:8974
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
Definition Utils.cpp:9340
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
Definition Utils.cpp:8554
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
Definition Utils.cpp:9187
static std::map< void *, SharedSegmentInfo > * SharedSegments
Definition Utils.cpp:1039
char * GetFileList(const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
List files in a directory matching an extension.
Definition Utils.cpp:9746
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
Definition Utils.cpp:8345
static std::map< const void *, bool > * g_cancelSafeSet
Definition Utils.cpp:1332
static std::map< const void *, pid_t > * SharedSemaphoreCreators
Definition Utils.cpp:1040
static void ResetChildSignalMask()
Definition Utils.cpp:5349
static std::mutex & gLaunchMx
Definition Utils.cpp:6000
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
Definition Utils.cpp:9392
uint64 GetTime()
Definition Utils.cpp:735
uint32 StringMultiReplace(std::string &text, std::map< std::string, std::string > &map, bool onlyFirst)
Apply many key→value replacements in one pass.
Definition Utils.cpp:9097
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
Definition Utils.cpp:8946
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
Definition Utils.cpp:9903
uint16 GetCPUCount()
Number of logical CPU cores.
Definition Utils.cpp:7049
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
Definition Utils.cpp:7483
std::map< std::string, std::string > TextMapSplit(const char *text, const char *outersplit, const char *innersplit)
Split "k=v<sep>k=v..." text into a map (later duplicates overwrite earlier ones).
Definition Utils.cpp:8646
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
Definition Utils.cpp:7009
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
Definition Utils.cpp:8712
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
Definition Utils.cpp:9989
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
Definition Utils.cpp:10543
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
Definition Utils.cpp:7928
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
Definition Utils.cpp:8565
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
Definition Utils.cpp:7305
uint32 StringScriptReplace(std::string &text, std::string name, std::list< std::map< std::string, std::string > > &list)
Expand a named repeating template block in text once per map in list, substituting each map's keys in...
Definition Utils.cpp:9131
std::string TextJoinXML(std::map< std::string, std::string > &map, const char *innernodeName, const char *outernodeName)
Serialize a map as XML, one innernodeName element per pair inside an outernodeName element.
Definition Utils.cpp:8928
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
Definition Utils.cpp:6619
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
Definition Utils.cpp:9079
uint64 GetSystemMemorySize()
Total physical RAM installed.
Definition Utils.cpp:7152
uint32 ReadRegistryDWORD(const char *key, const char *entry)
Read a 32-bit registry value.
static bool TerminalMasterFind(uint32 proc, int &fd)
Definition Utils.cpp:6383
static ShutdownSignalCallback g_shutdownCallback
Definition Utils.cpp:4367
bool GetLocalMACAddress(uint64 &address)
Get the primary local MAC address.
Definition Utils.cpp:7988
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:7688
FileDetails GetFileDetails(const char *filename)
Stat a file.
Definition Utils.cpp:9817
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:10131
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
Definition Utils.cpp:7526
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
Definition Utils.cpp:6689
static volatile sig_atomic_t g_signalThreadStop
Definition Utils.cpp:4366
std::multimap< std::string, std::string > TextMultiMapSplit(const char *text, const char *outersplit, const char *innersplit)
Split "k=v<sep>k=v..." text into a multimap (duplicate keys preserved).
Definition Utils.cpp:8619
bool RenameRegistryTree(const char *entry, const char *newName)
Definition Utils.cpp:10548
static bool ContainsPortToken(const char *name, const char *portstr, size_t plen)
Definition Utils.cpp:3593
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:8042
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
Definition Utils.cpp:7860
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
Definition Utils.cpp:9884
static bool EventWordSignal(void *data)
Definition Utils.cpp:2087
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:7781
static uint32 ClearSegmentsIn(const char *dir, const char *prefix, const char *portstr, size_t plen)
Definition Utils.cpp:3606
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
Definition Utils.cpp:7456
std::string GetLocalHostnameString()
Local hostname as std::string.
Definition Utils.cpp:7916
static pid_t DoPosixForkExec(PosixLaunchRequest &r)
Definition Utils.cpp:5898
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
Definition Utils.cpp:9969
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
Definition Utils.cpp:9812
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
Definition Utils.cpp:8199
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:8586
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
Definition Utils.cpp:9179
bool DeleteAFile(const char *filename, bool force)
Delete a file.
Definition Utils.cpp:9368
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
Definition Utils.cpp:9372
static bool MutexIsCancelSafe(const void *m)
Definition Utils.cpp:1359
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:10177
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
Definition Utils.cpp:6683
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:9031
std::vector< std::string > TextListSplitLines(const char *text, bool keepEmpty=true, bool autoTrim=false)
Split text into lines, handling both \n and \r\n.
Definition Utils.cpp:8769
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:9312
std::string GetCurrentDir()
Current working directory.
Definition Utils.cpp:9733
std::string GetCommandLine()
Get the full original command line as one string.
Definition Utils.cpp:6660
static bool SharedSegmentIsOwned(void *data)
Definition Utils.cpp:1055
bool CalcTimeout(struct timespec &timeout, uint32 ms)
Definition Utils.cpp:720
static std::mutex gLaunchSerialMx
Definition Utils.cpp:6004
std::string ReadRegistryString(const char *key, const char *entry)
Read a string registry value.
char OSName[1024]
Definition Utils.cpp:6928
std::vector< std::string > TextCommandlineSplit(const char *cmdline)
Split a command line into arguments, honouring quoting rules.
Definition Utils.cpp:8719
static void SharedNamesWait(volatile bool *flag, uint32 ms)
Definition Utils.cpp:2727
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
Definition Utils.cpp:9807
bool DeleteRegistryEntry(const char *key, const char *entry)
Delete a single value from a key.
static bool gLauncherStarted
Definition Utils.cpp:6003
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:9061
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:7757
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:9532
bool WriteRegistryQWORD(const char *key, const char *entry, uint64 value)
Write a 64-bit registry value.
char * ReadAFile(const char *filename, uint32 &length, bool binary=false)
Read an entire file into a new buffer.
Definition Utils.cpp:9253
static __thread int g_savedCancelState
Definition Utils.cpp:1333
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
Definition Utils.cpp:9933
uint64 AsciiHex2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit hexadecimal integer (with or without 0x) from a substring.
Definition Utils.cpp:9951
const char * GetFileBasename(const char *filename)
Filename portion of a path.
Definition Utils.cpp:9717
static PosixLaunchRequest * gLaunchReq
Definition Utils.cpp:6002
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:6912
bool WriteRegistryString(const char *key, const char *entry, const char *value)
Write a string registry value.
static void DrumBeatCallback(union sigval p)
Definition Utils.cpp:757
bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM)
Query total and free physical memory.
Definition Utils.cpp:7175
static THREAD_RET THREAD_FUNCTION_CALL ProcessLauncherRun(THREAD_ARG)
Definition Utils.cpp:6006
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
Definition Utils.cpp:9915
static pid_t SubmitLaunchRequest(PosixLaunchRequest &req)
Definition Utils.cpp:6020
bool WriteRegistryDWORD(const char *key, const char *entry, uint32 value)
Write a 32-bit registry value (creates the key when needed).
std::string TextJoinJSON(std::map< std::string, std::string > &map)
Serialize a map as a JSON object (keys/values escaped).
Definition Utils.cpp:8912
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
Definition Utils.cpp:10546
static bool g_signalThreadRunning
Definition Utils.cpp:4365
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
Definition Utils.h:1494
bool DeleteRegistryTree(const char *root, const char *key)
Recursively delete a key and all subkeys.
std::string TextLowercase(const char *text)
Convert to lower case (ASCII/current locale).
Definition Utils.cpp:8548
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
Definition Utils.cpp:10010
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:8528
const char * GetComputerName()
Get this machine's hostname.
Definition Utils.cpp:6930
std::string GetFilePath(const char *filename)
Directory portion of a path.
Definition Utils.cpp:9701
static bool TakeSemaphoreOwnsName(const void *sem)
Definition Utils.cpp:1078
static void SignalShutdownSigset(sigset_t *set)
Definition Utils.cpp:4356
const char * GetSystemOSName()
OS name string, e.g.
Definition Utils.cpp:7277
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
Definition Utils.cpp:10214
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
Definition Utils.cpp:8015
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
Definition Utils.cpp:9999
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
Definition Utils.cpp:8865
static pthread_t g_signalThread
Definition Utils.cpp:4364
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
Definition Utils.cpp:10168
std::string BytifyRate(double val)
Format a byte rate, e.g.
Definition Utils.cpp:10260
static bool Test_Utils()
Definition Utils.cpp:10556
CleanShutdown CleanShutdownInstance
Definition Utils.cpp:73
struct dirent * readdir(DIR *)
static void InitSharedMutexObject(pthread_mutex_t *m)
Definition Utils.cpp:480
static void SharedLockWakeOne(volatile uint32_t *addr)
Definition Utils.cpp:510
static bool Test_ChildSignalMask()
Definition Utils.cpp:10558
DIR * opendir(const char *)
Definition direntwin.cpp:53
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
Definition Utils.cpp:89
static bool Test_MutexOwnerDeath()
Definition Utils.cpp:10559
static bool Test_ProbeProcessWait()
Definition Utils.cpp:10557
uint32 CleanShutdownInstanceCount
Definition Utils.cpp:72
static bool Test_SharedNames()
Definition Utils.cpp:10560
static void SharedLockWait(volatile uint32_t *addr, uint32_t value, uint32_t timeoutUS)
Definition Utils.cpp:494
void Register_Utils_Tests()
Definition Utils.cpp:10565
int closedir(DIR *)
Definition direntwin.cpp:95
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
Definition Utils.cpp:182
static bool Test_Timer()
Definition Utils.cpp:10563
static void SharedLockWakeAll(volatile uint32_t *addr)
Definition Utils.cpp:524
static bool Test_SemaphoreUserDeath()
Definition Utils.cpp:10561
static bool Test_EventUserDeath()
Definition Utils.cpp:10562
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Definition Utils.cpp:157
Wire/storage layout of one log record: fixed header immediately followed by the message text.
Definition Utils.h:245
uint32 source
Definition Utils.h:249
uint32 size
Definition Utils.h:246
std::string toJSON()
Serialize the entry (header fields + text) as a JSON object string.
Definition Utils.cpp:298
uint8 level
Definition Utils.h:251
uint64 time
Definition Utils.h:248
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
Definition Utils.cpp:287
uint8 subject
Definition Utils.h:250
uint8 type
Definition Utils.h:252
uint32 cid
Definition Utils.h:247
const char * getText(uint32 &len)
Access the text payload stored after the header.
Definition Utils.cpp:280
std::string toXML()
Serialize the entry as an XML fragment.
Definition Utils.cpp:306
char * d_name
Definition direntwin.h:35
Bookkeeping record for one periodic "drum beat" timer.
Definition Utils.h:440
Existence, type, permission and timestamp information for one file, as returned by GetFileDetails().
Definition Utils.h:1908
Description of one local network interface (IPv4 address, MAC and names).
Definition Utils.h:1649
char friendlyName[MAXKEYNAMELEN+1]
Definition Utils.h:1653
char name[MAXKEYNAMELEN+1]
Definition Utils.h:1652
const std::map< std::string, std::string > * env
Definition Utils.cpp:5884
POSIX capture bookkeeping for children started via NewProcessEx(captureOutput).
Definition Utils.h:661
int errFD
Parent read-end of the child's stderr (-1 = not captured).
Definition Utils.h:664
int outFD
Parent read-end of the child's stdout (-1 = not captured).
Definition Utils.h:663
Snapshot from ProbeProcessWait(): is the child (group) alive, is it blocked reading stdin,...
Definition Utils.h:1418
uint64 cpuTimeMs
cumulative user+sys CPU across the process group, in ms
Definition Utils.h:1422
bool waitingStdin
blocked reading fd 0 (exact on Linux; best-effort composite elsewhere)
Definition Utils.h:1421
bool alive
process (or group) still exists
Definition Utils.h:1419
bool waitExact
true only when the OS reported the exact blocking syscall (Linux /proc/<pid>/syscall)
Definition Utils.h:1420
volatile uint32_t waiters
Definition Utils.cpp:2060
One scheduled entry inside a Timer: id, active window and platform timer handle.
Definition Utils.h:674
A single timer expiry: which timer fired and when.
Definition Utils.h:692
#define TRUE
Definition xml_parser.h:124
#define FALSE
Definition xml_parser.h:121