9 #define _CRT_SECURE_NO_WARNINGS
21#include <mach/vm_statistics.h>
23#include <mach/host_info.h>
24#include <mach/task_info.h>
25#include <mach/thread_act.h>
26#include <sys/sysctl.h>
33#include <condition_variable>
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>
48 #define CMSDK_HAVE_OS_SYNC 1
51 #ifndef CMSDK_HAVE_OS_SYNC
52 #define CMSDK_HAVE_OS_SYNC 0
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
61 #include <sys/syscall.h>
62 #include <linux/futex.h>
93 std::map<std::string, utils::Semaphore*>::iterator si;
108 std::map<std::string, utils::Event*>::iterator ei;
123 std::map<std::string, utils::Mutex*>::iterator mi;
172 return "String info";
174 return "Binary info";
176 return "Message info";
178 return "Unknown type";
183 if ((
stricmp(typeName,
"string") == 0) || (
stricmp(typeName,
"text") == 0))
185 else if (
stricmp(typeName,
"time") == 0)
187 else if ((
stricmp(typeName,
"integer") == 0) || (
stricmp(typeName,
"int") == 0))
189 else if ((
stricmp(typeName,
"float") == 0) || (
stricmp(typeName,
"double") == 0))
191 else if (
stricmp(typeName,
"binary") == 0)
193 else if (
stricmp(typeName,
"message") == 0)
195 else if (
stricmp(typeName,
"string info") == 0)
197 else if (
stricmp(typeName,
"binary info") == 0)
199 else if (
stricmp(typeName,
"message info") == 0)
282 return (
char*)
this+
sizeof(
LogEntry);
291 if (avail < (int32)len)
293 memcpy((
char*)
this+
sizeof(
LogEntry), text, len);
294 *((
char*)
this+
sizeof(
LogEntry)+len) = 0;
300 const char* text =
getText(len);
302 "{ \"time\": %llu, \"level\": %u, \"source\": %u, \"subject\": %u, \"type\": %u, \"text\": \"%s\" }",
308 const char* text =
getText(len);
310 "<entry time=\"%llu\" level=\"%u\" source=\"%u\" subject=\"%u\" type=\"%u\" text=\"%s\" />\n",
362 va_start(args, formatstring);
375 entry->
level = level;
386 std::cout << strline;
410 va_start(args, formatstring);
423 entry->
level = level;
444 static int macos_pthread_mutex_timedlock(pthread_mutex_t *mutex,
const struct timespec *abs_timeout)
454 while ((rv = pthread_mutex_trylock(mutex)) == EBUSY) {
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))
461 struct timespec nap = { 0, 1000000 };
462 nanosleep(&nap, NULL);
478#ifndef CMSDK_MUTEX_PID_RECOVERY
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);
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);
503 __ulock_wait(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO, (
void*)addr, value, timeoutUS ? timeoutUS : 1);
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);
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);
518 __ulock_wake(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO, (
void*)addr, 0);
520 syscall(SYS_futex, (uint32_t*)addr, FUTEX_WAKE, 1, NULL, NULL, 0);
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);
532 __ulock_wake(CMSDK_UL_COMPARE_AND_WAIT_SHARED | CMSDK_ULF_NO_ERRNO | CMSDK_ULF_WAKE_ALL, (
void*)addr, 0);
534 syscall(SYS_futex, (uint32_t*)addr, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
538#if defined(CMSDK_MUTEX_PID_RECOVERY) || defined(CMSDK_SEMAPHORE_WORD)
557struct SharedLockWord {
558 volatile uint32_t owner;
559 volatile uint32_t waiters;
560 volatile uint64_t tid;
561 volatile uint32_t depth;
562 volatile uint32_t recoveries;
564static_assert(
sizeof(SharedLockWord) <=
MUTEXMEMSIZE,
"MUTEXMEMSIZE too small for the lock word");
566static inline SharedLockWord* SharedLockOf(pthread_mutex_t* m) {
return (SharedLockWord*)(
void*)m; }
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;
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();
585 pthread_threadid_np(NULL, &t);
588 t_sharedLockTid = (uint64_t)syscall(SYS_gettid);
590 t_sharedLockGen = g_sharedLockForkGen;
592 pid = t_sharedLockPid;
593 tid = t_sharedLockTid;
597static bool SharedLockPidIsDead(uint32_t pid, uint32_t mypid) {
598 if (!pid || (pid == mypid))
600 if (kill((pid_t)pid, 0) != 0)
601 return (errno == ESRCH);
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);
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);
618 const char* p = strrchr(buf,
')');
619 return (p && p[1] ==
' ' && p[2] ==
'Z');
623static inline void SharedLockTake(SharedLockWord* w, uint64_t me) {
626 __atomic_thread_fence(__ATOMIC_SEQ_CST);
630static int SharedLockAcquire(pthread_mutex_t* m, uint32 timeoutMS,
bool infinite,
const char* name) {
631 SharedLockWord* w = SharedLockOf(m);
632 if (!w)
return EINVAL;
635 SharedLockSelf(mypid, me);
636 uint64 start = 0, lastCheck = 0;
639 uint32_t cur = __atomic_load_n(&w->owner, __ATOMIC_SEQ_CST);
640 if (cur == mypid && w->tid == me) {
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);
654 #if defined(__x86_64__) || defined(__i386__)
655 __builtin_ia32_pause();
656 #elif defined(__aarch64__)
657 __asm__ __volatile__(
"yield");
663 if (!infinite && (
GetTimeAgeMS(start) >= (int64)timeoutMS))
666 uint32_t sleepUS = 50000;
669 if (leftMS <= 0)
return ETIMEDOUT;
670 if (leftMS * 1000 < (int64)sleepUS) sleepUS = (uint32_t)(leftMS * 1000);
672 __atomic_fetch_add(&w->waiters, 1, __ATOMIC_SEQ_CST);
674 __atomic_fetch_sub(&w->waiters, 1, __ATOMIC_SEQ_CST);
676 if ((cur != mypid) && (__atomic_load_n(&w->owner, __ATOMIC_SEQ_CST) == cur) && (
GetTimeAgeMS(lastCheck) >= 50)) {
678 if (!SharedLockPidIsDead(cur, mypid))
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);
693static bool SharedLockRelease(pthread_mutex_t* m) {
694 SharedLockWord* w = SharedLockOf(m);
695 if (!w)
return false;
698 SharedLockSelf(mypid, me);
699 if ((__atomic_load_n(&w->owner, __ATOMIC_SEQ_CST) != mypid) || (w->tid != me))
707 __atomic_store_n(&w->owner, 0, __ATOMIC_SEQ_CST);
708 if (__atomic_load_n(&w->waiters, __ATOMIC_SEQ_CST))
722 if (gettimeofday(&now, NULL) != 0)
725 timeout.tv_sec = now.tv_sec + (ms / 1000);
726 int64 us = (int64)(now.tv_usec) + ((ms % 1000)*1000);
727 while (us >= 1000000) {
731 timeout.tv_nsec = (long)(us * 1000);
737 if ( gettimeofday(&tv, NULL))
739 return (tv.tv_usec + tv.tv_sec * 1000000LL);
746 VOID CALLBACK
DrumBeatCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) {
747 DrumBeatInfo* info = (DrumBeatInfo*) lpParameter;
749 if (!info->id || !info->createdTime || !info->started || !func)
752 if (!info->func(info->id, info->count))
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);
796 info->
handle = timer_source;
799 struct sigevent timer_event;
806 timer_event.sigev_notify = SIGEV_THREAD;
807 timer_event.sigev_notify_attributes = NULL;
809 timer_event.sigev_value.sival_ptr = (
void *)info;
810 int ret = timer_create(CLOCK_REALTIME, &timer_event, &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);
842 dispatch_source_set_event_handler(info->
handle, ^{
844 if (!inf->func(inf->id, inf->count))
845 StopDrumBeat(inf->id);
847 dispatch_resume(info->
handle);
851 struct itimerspec newtv;
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;
858 int ret = timer_settime(info->
handle, 0, &newtv, NULL);
879 DeleteTimerQueueTimer(NULL, info->
handle, NULL);
885 dispatch_suspend(info->
handle);
889 struct itimerspec newtv;
890 memset(&newtv, 0,
sizeof(itimerspec));
891 int ret = timer_settime(info->
handle, 0, &newtv, NULL);
923 dispatch_source_cancel(info->
handle);
925 dispatch_resume(info->
handle);
926 dispatch_release(info->
handle);
931 timer_delete(info->
handle);
945bool EnterMutex(
const char* name, uint32 ms,
bool autocreate) {
962 mutex =
new Mutex(name);
974 mutex =
new Mutex(name);
982 return (mutex->
enter(ms));
995 return (i->second->leave());
1049 info.
creator = created ? getpid() : 0;
1059 std::map<void*, SharedSegmentInfo>::iterator i =
SharedSegments->find(data);
1060 owned = (i !=
SharedSegments->end()) && i->second.creator && (i->second.creator == getpid());
1071 (*SharedSemaphoreCreators)[sem] = getpid();
1084 owns = (i->second == getpid());
1118 semaphore = i->second;
1132 semaphore = i->second;
1159 semaphore = i->second;
1173 semaphore = i->second;
1174 return (semaphore->
wait(ms));
1197 semaphore = i->second;
1207 semaphore = i->second;
1208 return (semaphore->
signal());
1256 event =
new Event(name);
1268 event =
new Event(name);
1289 return (i->second->signal());
1352 #if defined(__GNUC__) || defined(__clang__)
1379 (*g_cancelSafeSet)[
this] =
true;
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);
1417 pthread_mutexattr_destroy(&attr);
1430 mutex = ::CreateMutex(NULL,
FALSE, this->name);
1444 mutex = (pthread_mutex_t*) data;
1451 mutex = (pthread_mutex_t*) data;
1452 #ifdef CMSDK_MUTEX_PID_RECOVERY
1463bool CloseMutexHandle(HANDLE mutex) {
1469 __except (EXCEPTION_EXECUTE_HANDLER) {
1490 CloseMutexHandle(
mutex);
1495 pthread_mutex_destroy(
mutex);
1500 #ifndef CMSDK_MUTEX_PID_RECOVERY
1502 pthread_mutex_destroy(
mutex);
1515 reply = WaitForSingleObject(
mutex, INFINITE);
1520 if (reply == WAIT_OBJECT_0 || reply == WAIT_ABANDONED) {
1528 else if (reply == WAIT_FAILED && GetLastError() == ERROR_INVALID_HANDLE) {
1546 int prevCancelState = 0;
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);
1552 int error = pthread_mutex_lock(
mutex);
1553 if (error == EOWNERDEAD) {
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 :
"-");
1564 if (cs &&
count == 0)
1571 pthread_setcancelstate(prevCancelState, NULL);
1586 reply = WaitForSingleObject(
mutex, timeout);
1588 if (reply == WAIT_OBJECT_0 || reply == WAIT_ABANDONED) {
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",
1610 else if (reply == WAIT_FAILED) {
1611 DWORD mtxErr = GetLastError();
1612 if (mtxErr == ERROR_INVALID_HANDLE)
1614 char* msg =
new char[2048];
1615 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1616 NULL, mtxErr, 0, msg, 2048, NULL);
1618 LogPrint(0,
LOG_SYSTEM, 0,
"[%u]Mutex enter failed[%p](%s): %s - currently held by %u, count %u, total %u",
1624 LogPrint(0,
LOG_SYSTEM,0,
"[%u]Mutex enter error[%p](%s): %d - currently held by %u, count %u, total %u",
1634 int prevCancelState = 0;
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);
1644 int error = pthread_mutex_timedlock(
mutex, &ts);
1645 if (error == EOWNERDEAD) {
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 :
"-");
1654 if (cs &&
count == 0)
1665 pthread_setcancelstate(prevCancelState, NULL);
1667 if (error == EINVAL) {
1669 errorMsg ? errorMsg :
"-", error, timeout, (uint64)(ts.tv_sec), (int64)(ts.tv_nsec));
1673 LogPrint(0,
LOG_SYSTEM,0,
"Mutex enter timeout %u: '%s' (%d) [%p] - held by %u", timeout, errorMsg ? errorMsg :
"-", error,
this,
osid);
1709 uint32 osid2 =
osid;
1717 if (ReleaseMutex(
mutex) != 0) {
1746 uint32 prevOsid =
osid;
1749 #ifdef CMSDK_MUTEX_PID_RECOVERY
1750 bool released =
name ? SharedLockRelease(
mutex) : (pthread_mutex_unlock(
mutex) == 0);
1752 bool released = (pthread_mutex_unlock(
mutex) == 0);
1760 pthread_setcancelstate(restoreState, NULL);
1791#ifdef CMSDK_SEMAPHORE_WORD
1802struct SharedSemWord {
1803 volatile uint32_t count;
1804 volatile uint32_t waiters;
1806static_assert(
sizeof(SharedSemWord) <=
SEMAPHOREMEMSIZE,
"SEMAPHOREMEMSIZE too small for the semaphore word");
1808static void* SemWordOpen(
const char* name,
const void* owner) {
1810 snprintf(shmemname,
sizeof(shmemname),
"Semaphore_%s", name);
1816 SharedSemWord* w = (SharedSemWord*)data;
1818 __atomic_store_n(&w->count, 1, __ATOMIC_SEQ_CST);
1824static void SemWordClose(
void* data,
const void* owner) {
1832static bool SemWordWait(
void* data, uint32 timeoutMS,
bool infinite) {
1833 SharedSemWord* w = (SharedSemWord*)data;
1834 if (!w)
return false;
1837 uint32_t c = __atomic_load_n(&w->count, __ATOMIC_SEQ_CST);
1839 if (__atomic_compare_exchange_n(&w->count, &c, c - 1,
false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
1843 uint32_t sleepUS = 50000;
1850 if (leftMS * 1000 < (int64)sleepUS)
1851 sleepUS = (uint32_t)(leftMS * 1000);
1853 __atomic_fetch_add(&w->waiters, 1, __ATOMIC_SEQ_CST);
1855 __atomic_fetch_sub(&w->waiters, 1, __ATOMIC_SEQ_CST);
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))
1870 #define CMSDK_SEMWORD_SLOT semaphore_impl
1872 #define CMSDK_SEMWORD_SLOT (*(void**)&semaphore)
1886 semaphore_impl = dispatch_semaphore_create(0);
1908 #elif defined(CMSDK_SEMAPHORE_WORD)
1913 CMSDK_SEMWORD_SLOT = SemWordOpen(
name,
this);
1918 semaphore = sem_open(this->name, O_CREAT | O_EXCL, 0666, 1);
1922 semaphore = sem_open(this->name, O_CREAT, 0666, 1);
1941 dispatch_release((dispatch_semaphore_t)semaphore_impl);
1942 semaphore_impl = NULL;
1949 #ifdef CMSDK_SEMAPHORE_WORD
1950 SemWordClose(CMSDK_SEMWORD_SLOT,
this);
1951 CMSDK_SEMWORD_SLOT = NULL;
1960 snprintf(semname,
sizeof(semname),
"/Semaphore_%s",
name);
1961 sem_unlink(semname);
1971 return (WaitForSingleObject(
semaphore, INFINITE) == WAIT_OBJECT_0);
1973 #ifdef CMSDK_SEMAPHORE_WORD
1975 return SemWordWait(CMSDK_SEMWORD_SLOT, 0,
true);
1978 return dispatch_semaphore_wait((dispatch_semaphore_t)semaphore_impl, DISPATCH_TIME_FOREVER) == 0;
1988 return (WaitForSingleObject(
semaphore, timeout) == WAIT_OBJECT_0);
1990 #ifdef CMSDK_SEMAPHORE_WORD
1992 return SemWordWait(CMSDK_SEMWORD_SLOT, timeout,
false);
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;
2008 return (ReleaseSemaphore(
2013 #ifdef CMSDK_SEMAPHORE_WORD
2015 return SemWordSignal(CMSDK_SEMWORD_SLOT);
2018 return dispatch_semaphore_signal((dispatch_semaphore_t)semaphore_impl) != 0;
2066 if (!w)
return false;
2067 uint32_t g = __atomic_load_n(&w->
gen, __ATOMIC_SEQ_CST);
2070 uint32_t sleepUS = 50000;
2075 if (leftMS * 1000 < (int64)sleepUS)
2076 sleepUS = (uint32_t)(leftMS * 1000);
2078 __atomic_fetch_add(&w->
waiters, 1, __ATOMIC_SEQ_CST);
2079 if (__atomic_load_n(&w->
gen, __ATOMIC_SEQ_CST) == g)
2081 __atomic_fetch_sub(&w->
waiters, 1, __ATOMIC_SEQ_CST);
2082 if (__atomic_load_n(&w->
gen, __ATOMIC_SEQ_CST) != g)
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))
2100 event = CreateEvent(
2106 event =
new pthread_cond_t;
2107 pthread_cond_init(
event, NULL);
2109 mutex =
new pthread_mutex_t;
2110 pthread_mutex_init(
mutex, NULL);
2120 event = CreateEvent(
2134 __atomic_store_n(&w->
gen, 0, __ATOMIC_SEQ_CST);
2137 mutex = (pthread_mutex_t*) data;
2150 pthread_cond_destroy(
event);
2152 pthread_mutex_destroy(
mutex);
2167 return (WaitForSingleObject(
event, INFINITE) == WAIT_OBJECT_0);
2171 pthread_mutex_lock(
mutex);
2173 pthread_mutex_unlock(
mutex);
2180 return (WaitForSingleObject(
event, timeout) == WAIT_OBJECT_0);
2184 pthread_mutex_lock(
mutex);
2187 int r = pthread_cond_timedwait(
event,
mutex, &t);
2188 pthread_mutex_unlock(
mutex);
2195 if (!SetEvent(
event))
2203 pthread_mutex_lock(
mutex);
2204 int r = pthread_cond_broadcast(
event);
2205 pthread_mutex_unlock(
mutex);
2237 timers =
new std::map<uint32, Timer*>;
2241 (*timers)[globalID] =
this;
2249 std::map<uint32, TimerSchedule*>::iterator it = schedules.begin();
2250 std::map<uint32, TimerSchedule*>::iterator itEnd = schedules.end();
2256 std::list<TimerSchedule*>::iterator it2 = oldSchedules.begin();
2257 std::list<TimerSchedule*>::iterator it2End = oldSchedules.end();
2258 while (it2 != it2End)
2260 oldSchedules.clear();
2267 if (schedules[
id]) {
2276 schedule->
start = start;
2277 schedule->
end = end;
2279 schedules[id] = schedule;
2282 uint32 firstDelay = 0;
2283 if (start && (start > now))
2284 firstDelay = (uint32)(start - now)/1000;
2288 if (!CreateTimerQueueTimer(&schedule->
handle, NULL,
TimerCallback, schedule, firstDelay, interval, WT_EXECUTEINTIMERTHREAD)) {
2289 schedules[id] = NULL;
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;
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, ^{
2318 dispatch_resume(timer_source);
2320 struct sigaction sa;
2321 struct sigevent timer_event;
2323 sigemptyset(&sa.sa_mask);
2324 sa.sa_flags = SA_SIGINFO;
2326 sigaction(SIGRTMIN, &sa, NULL);
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;
2338 struct itimerspec newtv;
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;
2347 if (timer_settime(schedule->
handle, 0, &newtv, NULL) != 0) {
2348 timer_delete(schedule->
handle);
2349 schedules[id] = NULL;
2354 sigemptyset(&allsigs);
2371 schedules[id] = NULL;
2374 DeleteTimerQueueTimer(NULL, schedule->
handle, NULL);
2377 dispatch_source_cancel(schedule->
handle);
2378 dispatch_release(schedule->
handle);
2380 timer_delete(schedule->
handle);
2384 oldSchedules.push_back(schedule);
2398 trigger->
id = schedule->
id;
2401 triggers.push(trigger);
2404 if ( schedule->
end && ((int32)(schedule->
end - trigger->
time) < (int32)schedule->
interval))
2417 while (!triggers.size()) {
2419 if ( (timeleft = (int32)timeout -
GetTimeAgeMS(start)) <= 0)
2421 semaphore.wait((uint32)timeleft);
2425 trigger = triggers.front();
2428 time = trigger->
time;
2435 void CALLBACK
TimerCallback(PVOID arg, BOOLEAN TimerOrWaitFired) {
2472 if (!timer->
addTimer(1, 1000, now+50000, now+10000000)) {
2477 if (!timer->
addTimer(2, 2000, now+55000, now+15000000)) {
2482 if (!timer->
addTimer(3, 3000, now+60000, now+20000000)) {
2489 uint32 triggers = 0;
2490 double totalLatencyUs = 0;
2494 for (uint32 n = 0; n < 60; n++) {
2498 totalLatencyUs += (double)(now - time);
2499 unittest::detail(
"Timer %u triggered %.3f ms ago",
id, (now - time) / 1000.0);
2510 if (triggers == 0) {
2517 unittest::metric(
"avg_trigger_latency", totalLatencyUs / (
double)triggers,
"us",
false);
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; }
2538 dup2(inPipe[0], STDIN_FILENO);
2539 close(inPipe[0]); close(inPipe[1]);
2540 execl(
"/bin/sh",
"sh",
"-c",
"read x", (
char*)NULL);
2544 uint32 pid = (uint32)child;
2546 bool detected =
false;
2547 for (
int i = 0; i < 40 && !detected; i++) {
2548 if (!
ProbeProcessWait(pid, info)) {
unittest::fail(
"ProbeProcessWait returned false"); kill(child, SIGKILL); close(inPipe[1]); waitpid(child, NULL, 0);
return false; }
2553 unittest::fail(
"stdin-blocked child not detected (alive=%d waitingStdin=%d waitExact=%d)",
2555 kill(child, SIGKILL); close(inPipe[1]); waitpid(child, NULL, 0);
return false;
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; }
2560 kill(child, SIGKILL);
2562 waitpid(child, NULL, 0);
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; }
2576 if (busyFlagged) {
unittest::fail(
"busy child wrongly flagged waitingStdin");
return false; }
2594 pthread_sigmask(SIG_SETMASK, NULL, &before);
2597 const char* paths[] = {
"inline fork",
"die-with-parent launcher", NULL };
2598 for (
int m = 0; paths[m] && ok; m++) {
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; }
2603 kill((pid_t)pid, SIGTERM);
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);
2612 pthread_sigmask(SIG_SETMASK, &before, NULL);
2628#if !defined(WINDOWS)
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];
2637 if (pipe(fds) != 0) {
unittest::fail(
"pipe() failed"); ok =
false;
break; }
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);
2649 if (pid < 0 || read(fds[0], &b, 1) != 1 || b !=
'L') {
2650 unittest::fail(
"child could not take the mutex (%c)", b ? b :
'-');
2655 if (ok && c == 0) waitpid(pid, &st, 0);
2656 if (ok && c == 2) usleep(200000);
2658 bool got =
false, again =
false;
2660 std::thread waiter([&]() {
2661 got = m->
enter(5000,
"ownerdeath parent");
2664 again = m->
enter(1000,
"ownerdeath again");
2665 if (again) m->
leave();
2672 unittest::fail(
"mutex not available %.0f ms after its owner process ended (%s)", tookMS, what);
2675 else if (ok && !again) {
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);
2685 if (pid > 0 && c != 0) waitpid(pid, &st, 0);
2690#if !defined(CMSDK_MUTEX_PID_RECOVERY)
2696 GetCurrentProcessId()
2703 std::thread th([om]() { om->
enter(2000,
"ownerdeath thread"); });
2706 if (!tm->
enter(5000,
"ownerdeath after thread")) {
2736 (uint32)GetCurrentProcessId();
2740 const uint32 MAGIC = 0x5eed1e55;
2746 if (!s) {
unittest::fail(
"could not create segment %s", sname.c_str());
return false; }
2747 *(uint32*)s = MAGIC;
2752 if (!c || *(uint32*)c != MAGIC) {
2753 unittest::fail(
"segment name gone after another user closed it (%s)", c ?
"different memory" :
"open failed");
2760#if !defined(WINDOWS)
2769 if (pid > 0) waitpid(pid, &st, 0);
2771 if (!c || *(uint32*)c != MAGIC) {
2772 unittest::fail(
"segment name gone after a forked child closed it");
2785 unittest::fail(
"segment name still there after its creator (the last user) closed it");
2791 unittest::progress(45,
"mutex: still the same lock after another user deleted its handle");
2798 if (!m->
enter(1000,
"sharednames")) {
unittest::fail(
"could not take the mutex"); ok =
false; }
2801 std::thread th([&]() { got = h2->
enter(300,
"sharednames other");
if (got) h2->
leave(); });
2805 unittest::fail(
"another handle got the mutex while it was held: the name led to a NEW mutex");
2809 std::thread th2([&]() { got = h2->
enter(1000,
"sharednames other 2");
if (got) h2->
leave(); });
2811 if (!got) {
unittest::fail(
"the other handle could not take the mutex once it was free"); ok =
false; }
2816 if (!ok)
return false;
2819 unittest::progress(60,
"semaphore: still the same semaphore after another user deleted its object");
2825 for (
int i = 0; i < 10 && sa->
wait(10); i++) {}
2827 bool woke = sa->
wait(1000);
2831 unittest::fail(
"a signal through a new object did not reach the first: the name led to a NEW semaphore");
2836 unittest::progress(75,
"event: still the same event after another user deleted its object");
2842 volatile bool waiting =
false;
2843 bool signalled =
false;
2844 std::thread tw([&]() { waiting =
true; signalled = ea->
waitNext(2000); });
2852 unittest::fail(
"a signal through a new object did not reach the first: the name led to a NEW event");
2856#if !defined(WINDOWS) && !defined(UT_SHAREDNAMES_OLD)
2858 unittest::progress(90,
"segment: disown keeps the name past its creator, unlink removes it");
2861 if (!s) {
unittest::fail(
"could not create segment %s", dname.c_str());
return false; }
2862 *(uint32*)s = MAGIC;
2866 if (!c || *(uint32*)c != MAGIC) {
2867 unittest::fail(
"a disowned segment's name went with its creator's close");
2874 unittest::fail(
"segment name still there after UnlinkSharedMemorySegment");
2899 const int ITER = 40;
2900 for (
int i = 0; i < ITER; i++) {
2907 if (pid < 0) {
unittest::fail(
"fork failed");
delete s;
return false; }
2908 usleep(2000 + rand() % 8000);
2911 waitpid(pid, &st, 0);
2912 std::atomic<int> state(0);
2913 std::thread th([s, &state]() {
2916 bool got = s->
wait(500);
2917 for (
int k = 0; k < 64 && s->
wait(0); k++) {}
2918 state = got ? 2 : 3;
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");
2930 unittest::fail(
"named semaphore lost a signal after a user process died inside it (kill %d)", i + 1);
2955 unittest::progress(2,
"one signal wakes all waiters; a signal with no waiter is not kept");
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; });
2964 t1.join(); t2.join();
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; }
2971 const int ITER = 40;
2972 for (
int i = 0; i < ITER; i++) {
2979 if (pid < 0) {
unittest::fail(
"fork failed");
delete e;
return false; }
2980 usleep(2000 + rand() % 8000);
2983 waitpid(pid, &st, 0);
2984 std::atomic<int> woke(0);
2985 std::thread tw([e, &woke]() { woke = e->
waitNext(2000) ? 1 : 2; });
2987 std::atomic<bool> signalled(
false);
2988 std::thread ts([e, &woke, &signalled]() {
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");
3015 uint32 slotCount = 350;
3017 char* bitField =
new char[bitFieldSize];
3026 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: false", loc);
3032 unittest::fail(
"GetFirstFreeBitLoc failed: %u, expected: 0", loc);
3037 unittest::fail(
"GetFirstFreeBitLocN failed: %u, expected: 0", loc);
3051 unittest::fail(
"GetFirstFreeBitLoc 2 failed: %u, expected: 0", loc);
3056 unittest::fail(
"GetFirstFreeBitLocN 2 failed: %u, expected: 0", loc);
3063 unittest::fail(
"GetFirstFreeBitLocN 3 failed: %u, expected: 11", loc);
3068 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: 10", loc);
3087 unittest::fail(
"GetFirstFreeBitLoc 4 failed: %u, expected: 1", loc);
3092 unittest::fail(
"GetFirstFreeBitLocN 5 failed: %u, expected: 11", loc);
3097 unittest::fail(
"GetFirstFreeBitLocN 6 failed: %u, expected: 11", loc);
3102 unittest::fail(
"GetFirstFreeBitLocN 7 failed: %u, expected: 150", loc);
3107 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: 149", loc);
3121 unittest::fail(
"GetFirstFreeBitLoc 8 failed: %u, expected: 1", loc);
3126 unittest::fail(
"GetFirstFreeBitLocN 9 failed: %u, expected: 11", loc);
3131 unittest::fail(
"GetFirstFreeBitLocN 10 failed: %u, expected: 11", loc);
3136 unittest::fail(
"GetFirstFreeBitLocN 11 failed: %u, expected: 250", loc);
3141 unittest::fail(
"GetFirstFreeBitLocN 12 failed: %u, expected: false", loc);
3147 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3161 unittest::fail(
"GetFirstFreeBitLoc 13 failed: %u, expected: 1", loc);
3166 unittest::fail(
"GetFirstFreeBitLocN 14 failed: %u, expected: 11", loc);
3171 unittest::fail(
"GetFirstFreeBitLocN 15 failed: %u, expected: 11", loc);
3176 unittest::fail(
"GetFirstFreeBitLocN 16 failed: %u, expected: 11", loc);
3181 unittest::fail(
"GetFirstFreeBitLocN 17 failed: %u, expected: 250", loc);
3186 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3199 unittest::fail(
"GetFirstFreeBitLoc 18 failed: %u, expected: 1", loc);
3204 unittest::fail(
"GetFirstFreeBitLocN 19 failed: %u, expected: 11", loc);
3209 unittest::fail(
"GetFirstFreeBitLocN 20 failed: %u, expected: 11", loc);
3214 unittest::fail(
"GetFirstFreeBitLocN 21 failed: %u, expected: 250", loc);
3219 unittest::fail(
"GetFirstFreeBitLocN 22 failed: %u, expected: 250", loc);
3224 unittest::fail(
"GetFirstFreeBitLocN 23 failed: %u, expected: false", loc);
3229 unittest::fail(
"GetLastOccupiedBitLoc: loc %u, expected: 249", loc);
3256 hMapFile = CreateFileMapping(
3257 INVALID_HANDLE_VALUE,
3260 (uint32)((size >> 32) & 0xffffffff),
3261 (uint32)(size & 0xffffffff),
3272 bool alreadyExisted = (GetLastError() == ERROR_ALREADY_EXISTS);
3274 if (hMapFile == NULL) {
3280 pBuf = (
char*) MapViewOfFile(hMapFile,
3281 FILE_MAP_ALL_ACCESS,
3285 int error = GetLastError();
3286 CloseHandle(hMapFile);
3295 if (force && alreadyExisted)
3296 memset(pBuf, 0, (
size_t)size);
3301 (*SharedMemoryFileHandleMap)[pBuf] = hMapFile;
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);
3318 LogPrint(0,
LOG_SYSTEM,0,
"Couldn't create shared memory: '%s' (err: %d)...", memname, errno);
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);
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);
3345 shm_unlink(memname);
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);
3354 LogPrint(0,
LOG_SYSTEM,0,
"Couldn't create shared memory: '%s' (err: %d)...", memname, errno);
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);
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);
3389 hMapFile = OpenFileMapping(
3390 FILE_MAP_ALL_ACCESS,
3394 if (hMapFile == NULL) {
3400 pBuf = (
char*) MapViewOfFile(hMapFile,
3401 FILE_MAP_ALL_ACCESS,
3408 CloseHandle(hMapFile);
3416 (*SharedMemoryFileHandleMap)[pBuf] = hMapFile;
3423 int fd = open(memname, O_RDWR);
3429 uint64 memSize = size;
3436 if (fstat(fd, &st) == -1 || st.st_size <= 0) {
3441 memSize = (uint64) st.st_size;
3443 pBuf = (
char*)mmap(NULL, memSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3444 if (pBuf == MAP_FAILED) {
3456 int fd = shm_open(memname, O_RDWR, 0666);
3462 uint64 memSize = size;
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);
3474 memSize = (uint64) st.st_size;
3476 pBuf = (
char*)mmap(NULL, memSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3477 if (pBuf == MAP_FAILED) {
3495 UnmapViewOfFile(data);
3504 uint64 mapped = size;
3507 std::map<void*, SharedSegmentInfo>::iterator i =
SharedSegments->find(data);
3509 path = i->second.path;
3510 owned = i->second.creator && (i->second.creator == getpid());
3512 mapped = i->second.size;
3517 munmap(data, mapped);
3518 if (owned && path.length()) {
3520 unlink(path.c_str());
3522 shm_unlink(path.c_str());
3537 std::map<void*, SharedSegmentInfo>::iterator i =
SharedSegments->find(data);
3539 i->second.creator = 0;
3556 std::map<void*, SharedSegmentInfo>::iterator i =
SharedSegments->find(data);
3558 path = i->second.path;
3559 i->second.creator = 0;
3566 unlink(path.c_str());
3568 shm_unlink(path.c_str());
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)
3606static uint32
ClearSegmentsIn(
const char* dir,
const char* prefix,
const char* portstr,
size_t plen) {
3610 size_t preflen = strlen(prefix);
3612 while ((e =
readdir(d)) != NULL) {
3613 if (strncmp(e->
d_name, prefix, preflen) != 0)
3617 std::string path = std::string(dir) +
"/" + e->
d_name;
3618 if (unlink(path.c_str()) == 0)
3633 snprintf(portstr,
sizeof(portstr),
"%u", port);
3634 size_t plen = strlen(portstr);
3640 count +=
ClearSegmentsIn(
"/dev/shm",
"sem.Semaphore_", portstr, plen);
3651 LogPrint(0,
LOG_SYSTEM, 1,
"Cleared %u stale shared segment(s) for port %u...", count, port);
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);
3681 return ((bitsize + 31) >> 5) << 2;
3685 memset(bitfield, 255, bytesize);
3691 uint32* data = (uint32*)bitfield;
3692 uint32* src = (uint32*)data;
3704 const int32 words = (int32)(bytesize >> 2);
3705 while (src - data < words && *src == 0)
3707 if (src - data >= words)
3710 _BitScanForward((DWORD*)&index, *src);
3712 index = ffsl(*src) - 1;
3714 index = ffsl(*src) - 1;
3717 loc = ((uint32)(src-data)*32) + index;
3723 uint32* data = (uint32*)bitfield;
3724 uint32* src = (uint32*)data;
3730 uint32 foundBlock = 0;
3733 const int32 words = (int32)(bytesize >> 2);
3735 while (src - data < words && *src == 0)
3737 if (src - data >= words)
3740 _BitScanForward((DWORD*)&index, *src);
3742 index = ffsl(*src) - 1;
3744 index = ffsl(*src) - 1;
3746 loc = ((uint32)(src - data) * 32) + index;
3759 if ((l >> 5) >= (bytesize >> 2))
3762 uint32* word = (uint32*)bitfield + (l >> 5);
3765 val = (_bittest((
long*)word, n) != 0);
3767 val = (bit)((*word & (
static_cast<uint32
>(1) << n)) != 0);
3769 val = (bit)((*word & (
static_cast<uint32
>(1) << n)) != 0);
3777 if (foundBlock >= num)
3779 if (index % 32 == 0) {
3784 while ((num - foundBlock > 31) && (src - data < words) && (*src ==
MAXVALUINT32)) {
3789 if (src - data >= words)
3791 if ((num - foundBlock > 15) && (*(uint16*)src ==
MAXVALUINT16)) {
3795 if ((num - foundBlock > 7) && (*((
unsigned char*)src+2) == 255)) {
3801 else if ((num - foundBlock > 7) && (*(
unsigned char*)src == 255)) {
3807 if (foundBlock >= num)
3814 if (index % 32 == 0)
3820 if ((l >> 5) >= (bytesize >> 2))
3823 uint32* word = (uint32*)bitfield + (l >> 5);
3826 val = (_bittest((
long*)word, n) != 0);
3828 val = (bit)((*word & (
static_cast<uint32
>(1) << n)) != 0);
3830 val = (bit)((*word & (
static_cast<uint32
>(1) << n)) != 0);
3835 src += (uint32)(index / 32);
3836 if (src - data >= words)
3845bool SetBit(uint32 loc, bit value,
char* bitfield, uint32 bytesize) {
3846 if ((loc + 7) >> 3 > bytesize)
3848 uint32* data = (uint32*)bitfield;
3849 uint32* src = (uint32*)data;
3858 _bittestandset((
long*)src, n);
3860 _bittestandreset((
long*)src, n);
3877bool SetBitN(uint32 loc, uint32 num, bit value,
char* bitfield, uint32 bytesize) {
3878 if ((loc + 7) >> 3 > bytesize)
3880 uint32* data = (uint32*)bitfield;
3881 uint32* src = (uint32*)data;
3888 for (uint32 i = 0; i < num; i++) {
3890 while (num - i > 31) {
3900 *((
unsigned char*)src + 2) = (value ? 255 : 0);
3905 else if (num - i > 7) {
3906 *(
unsigned char*)src = (value ? 255 : 0);
3915 _bittestandset((
long*)src, n);
3917 _bittestandreset((
long*)src, n);
3940bool GetBit(uint32 loc,
const char* bitfield, uint32 bytesize, bit& val) {
3941 if ((loc + 7) >> 3 > bytesize)
3943 uint32* data = (uint32*)bitfield;
3944 uint32* src = (uint32*)data;
3952 val = (_bittest((
long*)src, n) != 0);
3954 uint32 mask =
static_cast<uint32
>( 1 << n ) ;
3955 val = (bit)(mask & *src);
3957 uint32 mask =
static_cast<uint32
>(1 << n);
3958 val = (bit)(mask & *src);
3966 uint32* data = (uint32*)bitfield;
3967 uint32* src = (uint32*)(bitfield + bytesize - 4);
3971 while ((*src == 0xFFFFFFFF)) {
3978 _BitScanReverse((DWORD*)&index, ~(*src));
3980 index = 31 - __builtin_clz(~(*src));
3982 index = 31 - __builtin_clz(~(*src));
3984 loc = ((uint32)(src - data) * 32) + index;
3992 str.reserve(bytesize * 9);
3995 for(i = 0; i < bytesize; i++) {
3996 for(j = 0; j < 8; j++) {
3998 str.push_back((bitfield[i] & (1 << j)) ?
'_' :
'0');
4011 uint32 strSize = (uint32)str.size();
4016 return StringFormat(
"%s [%u]: %s\n", title, size, str.c_str());
4025 while (loc < strSize-1) {
4026 str2 += str.substr(loc, 36) +
"\n";
4030 str2 += str.substr(loc) +
"\n";
4040 return InterlockedIncrement((LONG*)&v);
4043 __sync_add_and_fetch(&v, 1);
4050 return InterlockedIncrement64((LONGLONG*)&v);
4053 __sync_add_and_fetch(&v, 1);
4060 return InterlockedDecrement((LONG*)&v);
4063 __sync_add_and_fetch(&v, -1);
4070 return InterlockedDecrement64((LONGLONG*)&v);
4073 __sync_add_and_fetch(&v, -1);
4089 std::string tracePrint;
4092 std::list<std::string>::iterator i = trace.begin(), e = trace.end();
4096 if ((++line > startLine) && (!endLine || (line <= endLine)))
4097 tracePrint +=
" -" + (*i) +
"\n";
4104 std::list<std::string> trace;
4133 size = backtrace(array, 200);
4134 strings = backtrace_symbols(array, size);
4135 for (i = 0; i < size; i++)
4136 trace.push_back(strings[i]);
4151 (LPTHREAD_START_ROUTINE) func,
4156 if (thread != NULL) {
4157 osID = ::GetThreadId(thread);
4164 pthread_attr_t attr;
4165 pthread_attr_init(&attr);
4167 pthread_attr_setschedpolicy(&attr, SCHED_RR);
4168 pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
4172 if ((res=pthread_create(&thread, &attr, func, args)) != 0)
4175 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
4176 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
4179 pthread_threadid_np(thread, &tid);
4182 osID = (uint32) thread;
4192 int res = WaitForSingleObject(hThread, 0);
4193 if (res != WAIT_OBJECT_0)
4206 return (pthread_kill(hThread, 0) != 0);
4219 return (pthread_kill(hThread, 0) != 0);
4232 CloseHandle(hThread);
4234 pthread_join(hThread, NULL);
4251 if (WaitForSingleObject(hThread, 0) != WAIT_OBJECT_0)
4253 CloseHandle(hThread);
4254 #elif defined __APPLE__
4255 if (pthread_kill(hThread, 0) == 0)
4257 pthread_join(hThread, NULL);
4259 if (pthread_tryjoin_np(hThread, NULL) != 0)
4270 int res = WaitForSingleObject(hThread, timeoutMS ? timeoutMS : INFINITE);
4271 if(res != WAIT_OBJECT_0)
4281 return (pthread_join(hThread, NULL) == 0);
4289 while (pthread_kill(hThread, 0) == 0) {
4290 if (waited >= timeoutMS)
4296 pthread_join(hThread, NULL);
4302 if (pthread_timedjoin_np(hThread, NULL, &ts) != 0)
4308 if (pthread_join(hThread, NULL) != 0)
4325 char* msg =
new char[2048];
4326 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
4327 NULL, GetLastError(), 0, msg,
sizeof(msg), NULL);
4333 CloseHandle(hThread);
4339 pthread_cancel(hThread);
4340 if (pthread_join(hThread, NULL) != 0)
4358 sigaddset(set, SIGINT);
4359 sigaddset(set, SIGTERM);
4360 sigaddset(set, SIGHUP);
4361 sigaddset(set, SIGUSR2);
4375 if (sigwait(&set, &sig) != 0)
4398 return (pthread_sigmask(SIG_BLOCK, &set, NULL) == 0);
4417 pthread_sigmask(SIG_BLOCK, &set, NULL);
4443 return (SuspendThread(hThread) >= 0);
4445 return (pthread_kill(hThread, SIGSTOP) == 0);
4453 while ( (count = ResumeThread(hThread)) > 1);
4454 return (count == 1);
4456 return (pthread_kill(hThread, SIGCONT) == 0);
4467 tid = ::GetCurrentThreadId();
4472 pthread_threadid_np(pthread_self(), &
id);
4475 tid = (uint32) pthread_self();
4483 tid = ::GetCurrentThreadId();
4488 if (pthread_threadid_np(pthread_self(), &
id) != 0)
4492 int id = syscall(SYS_gettid);
4506 thread = pthread_self();
4514 if (!GetExitCodeThread(hThread, &code))
4516 return (code == STILL_ACTIVE);
4529 return (pthread_kill(hThread, 0) == 0);
4536 return (pthread_kill(hThread, 0) == 0);
4545 #if defined RUSAGE_THREAD
4559 uint64 cpuTicks = 0;
4560 LARGE_INTEGER perfFreq;
4561 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4563 if (!QueryThreadCycleTime(hThread, &cpuTicks))
4565 ticks = cpuTicks / (perfFreq.QuadPart / 1000000);
4578 mach_port_t machThread = pthread_mach_thread_np(hThread);
4579 if (machThread == MACH_PORT_NULL)
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)
4585 ticks = (uint64)info.user_time.seconds * 1000000 + info.user_time.microseconds
4586 + (uint64)info.system_time.seconds * 1000000 + info.system_time.microseconds;
4590 if (pthread_getcpuclockid(hThread, &cid) != 0)
4593 if (clock_gettime(cid, &ts) != -1 ) {
4594 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4609 uint64 cpuTicks = 0;
4610 LARGE_INTEGER perfFreq;
4611 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4615 ticks = cpuTicks / (perfFreq.QuadPart / 1000000);
4627 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) != -1 ) {
4628 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4651 HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS,
FALSE, osProcID);
4657 uint64 cpuTicks = 0;
4658 LARGE_INTEGER perfFreq;
4659 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4661 if (!QueryProcessCycleTime(hProcess, &cpuTicks))
4663 ticks = cpuTicks / (perfFreq.QuadPart / 1000000);
4676 if ((pid_t)osProcID != getpid())
4679 if (getrusage(RUSAGE_SELF, &ru) != 0)
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;
4686 if (clock_getcpuclockid(osProcID, &clockid) != 0)
4689 if (clock_gettime(clockid, &ts) != -1 ) {
4690 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4718 uint64 cpuTicks = 0;
4719 LARGE_INTEGER perfFreq;
4720 if (!QueryPerformanceFrequency(&perfFreq) || !perfFreq.QuadPart)
4722 if (!QueryProcessCycleTime(::GetCurrentProcess(), &cpuTicks))
4724 ticks = cpuTicks / (perfFreq.QuadPart / 1000000);
4737 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) != -1 ) {
4738 ticks = ((uint64)ts.tv_sec * 1000000) + (ts.tv_nsec/1000);
4758bool GetProcAndOSCPUUsage(
double& procPercentUse,
double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks) {
4760 return GetProcAndOSCPUUsage(0, procPercentUse, osPercentUse, prevOSTicks, prevOSIdleTicks, prevProcTicks);
4762 return GetProcAndOSCPUUsage(getpid(), procPercentUse, osPercentUse, prevOSTicks, prevOSIdleTicks, prevProcTicks);
4767bool GetProcAndOSCPUUsage(uint32 osProcID,
double& procPercentUse,
double& osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks) {
4768 procPercentUse = osPercentUse = 0;
4770 uint64 totalTicks, kernelTicks, userTicks, idleTicks, procTotalTicks, procUserTicks, procKernelTicks;
4773 FILETIME idleTime, kernelTime, userTime;
4774 if (!GetSystemTimes(&idleTime, &kernelTime, &userTime))
4777 idleTicks = FileTimeToUint64(idleTime);
4778 kernelTicks = FileTimeToUint64(kernelTime);
4779 userTicks = FileTimeToUint64(userTime);
4780 totalTicks = kernelTicks + userTicks;
4782 FILETIME procCreationTime, procExitTime, procKernelTime, procUserTime;
4785 if (!GetProcessTimes(GetCurrentProcess(), &procCreationTime, &procExitTime, &procKernelTime, &procUserTime))
4789 HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS,
FALSE, osProcID);
4793 if (!GetProcessTimes(hProcess, &procCreationTime, &procExitTime, &procKernelTime, &procUserTime))
4797 procKernelTicks = FileTimeToUint64(procKernelTime);
4798 procUserTicks = FileTimeToUint64(procUserTime);
4799 procTotalTicks = procKernelTicks + procUserTicks;
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)
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;
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);
4834 if (procStatFile.is_open())
4835 getline (procStatFile, procStatLine);
4839 if (!statLine.length() || !procStatLine.length())
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]);
4848 for (
int i=0; i<10; i++)
4849 totalTicks += fields[i];
4850 idleTicks = fields[3];
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);
4856 procTotalTicks = utime_ticks + stime_ticks + cutime_ticks + cstime_ticks;
4859 uint64 totalTicksSinceLastTime = totalTicks - prevOSTicks;
4860 uint64 idleTicksSinceLastTime = idleTicks - prevOSIdleTicks;
4861 uint64 procTicksSinceLastTime = procTotalTicks - prevProcTicks;
4863 osPercentUse = 1.0f-((totalTicksSinceLastTime > 0) ? ((double)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4864 procPercentUse = ((totalTicksSinceLastTime > 0) ? ((double)procTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4869 prevOSTicks = totalTicks;
4870 prevOSIdleTicks = idleTicks;
4871 prevProcTicks = procTotalTicks;
4879 static uint64 PreviousTotalTicks = 0;
4880 static uint64 PreviousIdleTicks = 0;
4882 uint64 totalTicks, kernelTicks, userTicks, idleTicks;
4886 FILETIME idleTime, kernelTime, userTime;
4887 if (!GetSystemTimes(&idleTime, &kernelTime, &userTime))
4890 idleTicks = FileTimeToUint64(idleTime);
4891 kernelTicks = FileTimeToUint64(kernelTime);
4892 userTicks = FileTimeToUint64(userTime);
4893 totalTicks = kernelTicks + userTicks;
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)
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];
4903 std::string statLine;
4904 std::ifstream statFile(
"/proc/stat");
4905 if (!statFile.is_open() || !getline(statFile, statLine) || !statLine.length())
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)
4914 for (
int i = 0; i < 10; i++)
4915 totalTicks += fields[i];
4916 idleTicks = fields[3];
4919 uint64 totalTicksSinceLastTime = totalTicks - PreviousTotalTicks;
4920 uint64 idleTicksSinceLastTime = idleTicks - PreviousIdleTicks;
4922 percentUse = 1.0f-((totalTicksSinceLastTime > 0) ? ((double)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
4927 PreviousTotalTicks = totalTicks;
4928 PreviousIdleTicks = idleTicks;
4939 struct sched_param sched;
4942 policy = SCHED_OTHER;
4944 policy = sched_getscheduler(0);
4948 if (pthread_getschedparam(hThread, &policy, &sched) != 0)
4961 struct sched_param sched;
4962 memset(&sched, 0,
sizeof(
struct sched_param));
4964 policy = SCHED_FIFO;
4968 int res = pthread_setschedparam(hThread, policy, &sched);
4980 val = THREAD_PRIORITY_NORMAL;
4982 val = THREAD_PRIORITY_TIME_CRITICAL;
4984 val = THREAD_PRIORITY_HIGHEST;
4986 val = THREAD_PRIORITY_ABOVE_NORMAL;
4988 val = THREAD_PRIORITY_NORMAL;
4990 val = THREAD_PRIORITY_BELOW_NORMAL;
4992 val = THREAD_PRIORITY_LOWEST;
4994 val = THREAD_PRIORITY_IDLE;
5027 case THREAD_PRIORITY_TIME_CRITICAL:
5029 case THREAD_PRIORITY_HIGHEST:
5031 case THREAD_PRIORITY_ABOVE_NORMAL:
5033 case THREAD_PRIORITY_NORMAL:
5035 case THREAD_PRIORITY_BELOW_NORMAL:
5037 case THREAD_PRIORITY_LOWEST:
5068 const HWND hDesktop = GetDesktopWindow();
5070 if (!GetWindowRect(hDesktop, &desktop))
5075 width = (uint32)desktop.right;
5076 height = (uint32)desktop.bottom;
5087 char* oldName =
new char[1024];
5088 if (!GetConsoleTitle(oldName, 1024)) {
5092 char* newName =
StringFormat(size,
"%s - %s", name, oldName);
5093 bool res = (SetConsoleTitle(name) != 0);
5099 return (SetConsoleTitle(name) != 0);
5107 char* consoleName =
new char[1024];
5108 if (!GetConsoleTitle(consoleName, 1024)) {
5109 delete [] consoleName;
5112 HWND handle = FindWindow(NULL, consoleName);
5114 delete [] consoleName;
5118 if (!GetWindowRect(handle, &wRect)) {
5119 delete [] consoleName;
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;
5128 bool res = (MoveWindow(handle, conX, conY, conW, conH,
true) != 0);
5129 delete [] consoleName;
5144 return (uint32)GetCurrentProcessId();
5146 return (uint32)getpid();
5151int RunOSCommand(
const char* cmdline,
const char* initdir, uint32 timeout, std::string& stdoutString, std::string& stderrString) {
5152 if (!cmdline || !strlen(cmdline))
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;
5161 SECURITY_ATTRIBUTES sa;
5163 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
5164 sa.bInheritHandle =
TRUE;
5165 sa.lpSecurityDescriptor = NULL;
5167 if ( ! CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &sa, 0) ) {
5171 if ( ! SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0) ){
5175 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0) ) {
5179 if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ){
5182 PROCESS_INFORMATION piProcInfo;
5183 STARTUPINFO siStartInfo;
5184 bool bSuccess =
FALSE;
5187 ZeroMemory( &piProcInfo,
sizeof(PROCESS_INFORMATION) );
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;
5201 bSuccess = (CreateProcess(NULL,
5211 CloseHandle(g_hChildStd_ERR_Wr);
5212 CloseHandle(g_hChildStd_OUT_Wr);
5224 bSuccess=(ReadFile( g_hChildStd_OUT_Rd, chBuf,
PROCBUFSIZE, &dwRead, NULL) != 0);
5225 if( ! bSuccess || dwRead == 0 )
break;
5226 std::string s(chBuf, dwRead);
5232 bSuccess=(ReadFile( g_hChildStd_ERR_Rd, chBuf,
PROCBUFSIZE, &dwRead, NULL) != 0);
5233 if( ! bSuccess || dwRead == 0 )
break;
5234 std::string s(chBuf, dwRead);
5241 if (GetExitCodeProcess(piProcInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
5242 TerminateProcess(piProcInfo.hProcess, 1);
5244 CloseHandle(g_hChildStd_ERR_Rd);
5245 CloseHandle(g_hChildStd_OUT_Rd);
5246 CloseHandle(piProcInfo.hProcess);
5247 CloseHandle(piProcInfo.hThread);
5252 FILE* runfile = popen(cmdline,
"r");
5253 if (runfile == NULL)
5260 char* buffer =
new char[size+1];
5262 res = fread(buffer, 1, size, runfile);
5264 status = pclose(runfile);
5265 exitcode = WEXITSTATUS(status);
5271 stdoutString += buffer;
5272 }
while (res = fread(buffer, 1, size, runfile));
5274 status = pclose(runfile);
5275 exitcode = WEXITSTATUS(status);
5352 sigprocmask(SIG_SETMASK, &none, NULL);
5356uint32
NewProcess(
const char* cmdline,
const char* initdir,
const char* title, int16 x, int16 y, int16 w, int16 h) {
5358 if (!cmdline || !strlen(cmdline))
5365 ghJob = CreateJobObject(NULL, NULL);
5367 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
5369 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
5370 SetInformationJobObject(ghJob, JobObjectExtendedLimitInformation, &jeli,
sizeof(jeli));
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;
5381 if ( (x>=0) && (y>=0) && (w>=0) && (h>=0) ) {
5382 pData->si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USEPOSITION | STARTF_USESIZE;
5385 pData->si.dwXSize = w;
5386 pData->si.dwYSize = h;
5389 pData->si.dwFlags = STARTF_USESHOWWINDOW;
5394 char* titleCopy = NULL;
5396 size_t tlen = strlen(title);
5397 titleCopy =
new char[tlen + 1];
5398 memcpy(titleCopy, title, tlen + 1);
5399 pData->si.lpTitle = titleCopy;
5402 size_t clen = strlen(cmdline);
5403 char* cmd =
new char[clen + 1];
5404 memcpy(cmd, cmdline, clen + 1);
5408 int res = CreateProcess(NULL, cmd, NULL, NULL,
TRUE, CREATE_NEW_CONSOLE, NULL, initdir, &pData->si, &pData->procInfo);
5409 delete [] titleCopy;
5412 char* msg =
new char[2048];
5413 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
5414 NULL, GetLastError(), 0, msg,
sizeof(msg), NULL);
5423 AssignProcessToJobObject(ghJob, pData->procInfo.hProcess);
5426 return pData->procInfo.dwProcessId;
5446 pid_t ppid_before_fork = getpid();
5454 else if (pid == 0) {
5456 if ( initdir && (chdir(initdir) != 0) ) {
5457 LogPrint(0,
LOG_SYSTEM,0,
"Could not run process '%s' from starup dir '%s'\n", cmdline, initdir);
5462 int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
5463 if (r == -1) { perror(0); exit(1); }
5466 if (getppid() != ppid_before_fork)
5471 execvp(argv[0],argv);
5496 if (GetExitCodeProcess(pData->procInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
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);
5506 if (pData->hJob) CloseHandle(pData->hJob);
5508 returncode = exitcode;
5514 HANDLE hproc = OpenProcess(NULL,
false, (DWORD)proc);
5517 if (GetExitCodeProcess(hproc, &exitcode) && (exitcode == STILL_ACTIVE)) {
5528 int res = waitpid(proc, &status, WNOHANG);
5540 returncode = WEXITSTATUS(status);
5544 else if (res == 0) {
5551#if !defined(WINDOWS)
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);
5585 if (pData->hJob) CloseHandle(pData->hJob);
5591 HANDLE hproc = OpenProcess(NULL, NULL, (DWORD)proc);
5594 if (TerminateProcess(hproc, 1) == 0) {
5604 bool ok = (kill(proc, SIGKILL) == 0);
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;
5650 if (GetExitCodeProcess(h, &code) && code == STILL_ACTIVE)
5654 bool haveTreeCpu =
false;
5655 ProcessData* pd = NULL;
5660 if (pd && pd->hJob) {
5661 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION jbai;
5662 ZeroMemory(&jbai,
sizeof(jbai));
5664 if (QueryInformationJobObject(pd->hJob, JobObjectBasicAccountingInformation,
5665 &jbai,
sizeof(jbai), &retLen)) {
5669 out.cpuTimeMs = (uint64)((jbai.TotalUserTime.QuadPart +
5670 jbai.TotalKernelTime.QuadPart) / 10000ULL);
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);
5702 uint64 firstCpu = out.cpuTimeMs;
5704 uint64 secondCpu = firstCpu;
5705 if (pd && pd->hJob) {
5706 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION j2;
5707 ZeroMemory(&j2,
sizeof(j2));
5709 if (QueryInformationJobObject(pd->hJob, JobObjectBasicAccountingInformation,
5710 &j2,
sizeof(j2), &rl))
5711 secondCpu = (uint64)((j2.TotalUserTime.QuadPart +
5712 j2.TotalKernelTime.QuadPart) / 10000ULL);
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);
5723 out.cpuTimeMs = secondCpu;
5729 out.waitingStdin = (secondCpu == firstCpu);
5734#elif defined(__APPLE__)
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;
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);
5747 int n = proc_pidinfo((
int)pid, PROC_PIDLISTTHREADS, 0, tids,
sizeof(tids));
5748 if (n <= 0)
return true;
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;
5759 struct pipe_fdinfo pfd;
5760 if (proc_pidfdinfo((
int)pid, 0, PROC_PIDFDPIPEINFO, &pfd,
sizeof(pfd)) == (
int)
sizeof(pfd))
5761 out.waitingStdin =
true;
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;
5775 static const long PPW_SYS_read = -1;
5778 static bool ppwReadStat(
const char* path,
char& state,
long& pgrp, uint64& cpuTicks) {
5779 FILE* f = fopen(path,
"r");
5780 if (!f)
return false;
5782 size_t len = fread(buf, 1,
sizeof(buf) - 1, f);
5784 if (!len)
return false;
5786 const char* p = strrchr(buf,
')');
5787 if (!p)
return false;
5789 long ppid = 0;
unsigned long ut = 0, st = 0;
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)
5796 cpuTicks = (uint64)ut + (uint64)st;
5801 static int ppwSyscallIsStdinRead(
const char* path) {
5802 FILE* f = fopen(path,
"r");
5805 size_t len = fread(buf, 1,
sizeof(buf) - 1, f);
5807 if (!len)
return -1;
5809 long nr = 0;
unsigned long arg0 = 0;
5810 if (sscanf(buf,
"%ld %lx", &nr, &arg0) < 1)
5812 if (PPW_SYS_read < 0)
return -1;
5813 return (nr == PPW_SYS_read && arg0 == 0) ? 1 : 0;
5819 if (!pid)
return false;
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;
5824 if (state ==
'Z' || state ==
'X')
return true;
5826 long tck = sysconf(_SC_CLK_TCK);
5827 if (tck <= 0) tck = 100;
5828 uint64 totalTicks = 0;
5829 bool sawUnreadable =
false, sawStdinRead =
false;
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;
5845 snprintf(tdir,
sizeof(tdir),
"/proc/%lu/task", p);
5847 if (!tasks) { sawUnreadable =
true;
continue; }
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')
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;
5863 }
else sawUnreadable =
true;
5864 out.
cpuTimeMs = totalTicks * 1000ULL / (uint64)tck;
5866 else if (!sawUnreadable) out.
waitExact =
true;
5884 const std::map<std::string, std::string>*
env;
5899 pid_t ppid_before_fork = getpid();
5900 (void)ppid_before_fork;
5902 const char* shArgv[4] = {
"sh",
"-c", r.
cmdline, NULL };
5915 int devnull = open(
"/dev/null", O_WRONLY);
5917 dup2(devnull, STDOUT_FILENO);
5918 dup2(devnull, STDERR_FILENO);
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++; }
5943 if (getppid() != ppid_before_fork)
5945 pid_t self = getpid();
5946 pid_t nanny = fork();
5953 bool launcherGone =
true;
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)
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) {
5963 if ((kevent(kq, NULL, 0, &out, 1, NULL) == 1) && ((pid_t)out.ident == self))
5964 launcherGone =
false;
5968 kill(-self, SIGKILL);
5975 if (pres == -1) { perror(0); _exit(1); }
5977 if (getppid() != ppid_before_fork)
6001static std::condition_variable&
gLaunchCv = *
new std::condition_variable;
6007 std::unique_lock<std::mutex> lock(
gLaunchMx);
6022 std::unique_lock<std::mutex> lock(
gLaunchMx);
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))
6048 (void)posixParentDeathSig; (void)posixUseShell;
6051 ghJob = CreateJobObject(NULL, NULL);
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));
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;
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;
6075 if (captureOutput) {
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);
6086 SetHandleInformation(pData->hOutRead, HANDLE_FLAG_INHERIT, 0);
6087 SetHandleInformation(pData->hErrRead, HANDLE_FLAG_INHERIT, 0);
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);
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;
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);
6122 char* envBlock = NULL;
6123 if (env && env->size()) {
6124 std::map<std::string, std::string> merged;
6125 LPCH parentEnv = GetEnvironmentStrings();
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;
6134 FreeEnvironmentStrings(parentEnv);
6136 std::map<std::string, std::string>::const_iterator ei = env->begin();
6137 while (ei != env->end()) { merged[ei->first] = ei->second; ei++; }
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];
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;
6151 DWORD flags = CREATE_NEW_CONSOLE;
6152 if (newProcessGroup)
6153 flags |= CREATE_NEW_PROCESS_GROUP;
6160 char* titleCopy = NULL;
6162 size_t tlen = strlen(title);
6163 titleCopy =
new char[tlen + 1];
6164 memcpy(titleCopy, title, tlen + 1);
6165 pData->si.lpTitle = titleCopy;
6167 size_t clen = strlen(cmdline);
6168 char* cmd =
new char[clen + 1];
6169 memcpy(cmd, cmdline, clen + 1);
6171 int res = CreateProcess(NULL, cmd, NULL, NULL,
TRUE, flags, envBlock, initdir, &pData->si, &pData->procInfo);
6173 delete [] titleCopy;
6175 if (envBlock)
delete [] envBlock;
6180 if (hOutWrite) CloseHandle(hOutWrite);
6181 if (hErrWrite) CloseHandle(hErrWrite);
6182 if (hInRead) CloseHandle(hInRead);
6183 if (hNull) CloseHandle(hNull);
6187 int length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, msg,
sizeof(msg), NULL);
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);
6199 AssignProcessToJobObject(ghJob, pData->procInfo.hProcess);
6206 pData->hJob = CreateJobObject(NULL, NULL);
6208 if (!AssignProcessToJobObject(pData->hJob, pData->procInfo.hProcess)) {
6209 CloseHandle(pData->hJob);
6214 return pData->procInfo.dwProcessId;
6224 (void)title; (void)ignoreOutput;
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);
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]);
6244 if (!posixUseShell) {
6247 if (captureOutput) { close(outPipe[0]); close(outPipe[1]); close(errPipe[0]); close(errPipe[1]); }
6261 req.
pid = -1; req.
done =
false;
6268 if (captureOutput) { close(outPipe[0]); close(outPipe[1]); close(errPipe[0]); close(errPipe[1]); }
6273 if (captureOutput) {
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);
6279 pData->
outFD = outPipe[0];
6280 pData->
errFD = errPipe[0];
6290 if (!data || !len)
return false;
6295 if (!pData->hInWrite)
return false;
6297 while (written < len) {
6299 if (!WriteFile(pData->hInWrite, data + written, (DWORD)(len - written), &n, NULL) || !n) {
6304 written += (uint32)n;
6312 (void)proc; (void)data; (void)len;
6324 if (!pData->hInWrite)
return false;
6325 CloseHandle(pData->hInWrite);
6326 pData->hInWrite = NULL;
6340 HANDLE handles[2] = { pData->hOutRead, pData->hErrRead };
6341 std::string* targets[2] = { &out, &err };
6343 for (
int n = 0; n < 2; n++) {
6344 if (!handles[n])
continue;
6347 while (PeekNamedPipe(handles[n], NULL, 0, NULL, &avail, NULL) && avail) {
6348 DWORD toRead = avail <
sizeof(buf) ? avail : (DWORD)
sizeof(buf);
6350 if (!ReadFile(handles[n], buf, toRead, &got, NULL) || !got)
break;
6351 targets[n]->append(buf, got);
6364 std::string* targets[2] = { &out, &err };
6366 for (
int n = 0; n < 2; n++) {
6367 if (fds[n] < 0)
continue;
6369 while ((got = read(fds[n], buf,
sizeof(buf))) > 0)
6370 targets[n]->append(buf, (
size_t)got);
6381#if !defined(WINDOWS)
6393 const std::map<std::string, std::string>* env,
6394 uint16 cols, uint16 rows) {
6397 (void)cmdline; (void)initdir; (void)env; (void)cols; (void)rows;
6401 if (!cmdline || !*cmdline)
return 0;
6403 int master = posix_openpt(O_RDWR | O_NOCTTY);
6405 LogPrint(0,
LOG_SYSTEM, 0,
"NewProcessTerminal: posix_openpt failed (%d) for '%s'", errno, cmdline);
6408 if (grantpt(master) != 0 || unlockpt(master) != 0) {
6409 LogPrint(0,
LOG_SYSTEM, 0,
"NewProcessTerminal: grantpt/unlockpt failed (%d) for '%s'", errno, cmdline);
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;
6420 if (ptsname_r(master, slaveName,
sizeof(slaveName)) != 0) { close(master);
return 0; }
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);
6429 if (pid < 0) { close(master);
return 0; }
6435 int slave = open(slaveName, O_RDWR);
6436 if (slave < 0) _exit(127);
6438 ioctl(slave, TIOCSCTTY, 0);
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);
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++; }
6450 execl(
"/bin/sh",
"sh",
"-c", cmdline, (
char*)NULL);
6454 fcntl(master, F_SETFL, fcntl(master, F_GETFL, 0) | O_NONBLOCK);
6457 (*TerminalMasterMap)[(uint32)pid] = master;
6465 (void)proc; (void)out;
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; }
6475 if (errno == EINTR)
continue;
6476 if (errno == EAGAIN || errno == EWOULDBLOCK)
break;
6489 (void)proc; (void)data; (void)len;
6492 if (!data || !len)
return false;
6496 while (written < len) {
6497 ssize_t n = write(fd, data + written, len - written);
6499 if (errno == EINTR)
continue;
6500 if (errno == EAGAIN || errno == EWOULDBLOCK) {
Sleep(2);
continue; }
6503 written += (uint32)n;
6511 (void)proc; (void)cols; (void)rows;
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);
6543 return (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, (DWORD)proc) != 0);
6545 return (kill((pid_t)proc, sig) == 0);
6555 if (WaitForSingleObject(pData->procInfo.hProcess, timeout) == WAIT_OBJECT_0) {
6556 if (GetExitCodeProcess(pData->procInfo.hProcess, &exitcode) && (exitcode == STILL_ACTIVE)) {
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);
6566 if (pData->hJob) CloseHandle(pData->hJob);
6568 returncode = exitcode;
6575 HANDLE hproc = OpenProcess(NULL, NULL, (DWORD)proc);
6579 if (WaitForSingleObject(hproc, timeout) == WAIT_OBJECT_0) {
6580 if (GetExitCodeProcess(hproc, &exitcode) && (exitcode == STILL_ACTIVE)) {
6585 returncode = exitcode;
6629 for (n=1; n<argc; n++) {
6632 val = strchr(argv[n],
'=');
6671 if (p1 == std::string::npos) {
6672 if (p2 == std::string::npos)
6677 else if (p2 == std::string::npos)
6694 if (p1 == std::string::npos) {
6695 if (p2 == std::string::npos)
6700 else if (p2 == std::string::npos)
6727 std::map<std::string, std::string>::const_iterator it =
6743 FreeLibrary(handle);
6757 std::string realLibName;
6759 realLibName = filename;
6767 size_t slash = realLibName.find_last_of(
'/');
6768 int32 filenameStart = (slash == std::string::npos) ? 0 : (int32)(slash + 1);
6771 realLibName.insert(filenameStart,
"lib");
6773 if (!filenameStart) {
6775 realLibName.insert(0,
"./");
6777 realLibName.insert(0, path);
6787 std::string errorText;
6794 if (handle == NULL) {
6796 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6797 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
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);
6804 handle = LoadLibrary(filename);
6805 if (handle == NULL) {
6807 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6808 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
6809 (LPTSTR) &lpMsgBuf, 0, NULL);
6810 LogPrint(0,
LOG_SYSTEM, 0,
"Could not find or load library '%s': %s", filename, lpMsgBuf);
6811 LocalFree(lpMsgBuf);
6817 const char* dlErrorText;
6824 std::string debugName = realLibName;
6827 handle = dlopen(debugName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6829 dlErrorText = dlerror();
6831 if (dlErrorText && strlen(dlErrorText) &&
6832 !(strstr(dlErrorText,
"No such file") && strstr(dlErrorText, debugName.c_str())))
6833 errorText = dlErrorText;
6837 if (!handle && !errorText.size()) {
6842 if (strchr(filename,
'/'))
6843 handle = dlopen(realLibName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6845 dlErrorText = dlerror();
6847 if (dlErrorText && strlen(dlErrorText) &&
6848 !(strstr(dlErrorText,
"No such file") && strstr(dlErrorText, realLibName.c_str())))
6849 errorText = dlErrorText;
6853 if (!handle && !errorText.size() && !strchr(filename,
'/')) {
6856 handle = dlopen(realLibName.c_str(), RTLD_NOW | RTLD_GLOBAL);
6858 dlErrorText = dlerror();
6860 if (dlErrorText && strlen(dlErrorText) &&
6861 !(strstr(dlErrorText,
"No such file") && strstr(dlErrorText, realLibName.c_str())))
6862 errorText = dlErrorText;
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());
6880 if (!strlen(funcName))
6891 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
6892 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
6893 (LPTSTR) &lpMsgBuf, 0, NULL);
6894 LogPrint(0,
LOG_SYSTEM, 0,
"Could not find library function: %s: %s", funcName, lpMsgBuf);
6896 LocalFree(lpMsgBuf);
6904 if (errmsg != NULL) {
6905 LogPrint(0,
LOG_SYSTEM, 0,
"Could not find library function: %s: %s", (
char*) funcName, (
char*) errmsg);
6914 if (!lib->
load(libName)) {
6932 char* name =
new char[1024];
6963 std::string outString, errString;
6964 if (!
RunOSCommand(
"uname -n", NULL, 1000, outString, errString)) {
6980 HANDLE hProcess = GetCurrentProcess();
6981 PROCESS_MEMORY_COUNTERS pmc;
6982 if (hProcess == NULL)
6984 if ( GetProcessMemoryInfo( hProcess, &pmc,
sizeof(pmc)) != 0)
6985 return (uint64)pmc.WorkingSetSize;
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;
6998 if ( (fp = fopen(
"/proc/self/statm",
"r" )) == NULL )
7000 if ( fscanf( fp,
"%*s%ld", &rss ) != 1 ) {
7005 return (uint64)rss * (uint64)sysconf( _SC_PAGESIZE);
7012 HANDLE hProcess = GetCurrentProcess();
7013 PROCESS_MEMORY_COUNTERS pmc;
7014 if (hProcess == NULL)
7016 if ( GetProcessMemoryInfo( hProcess, &pmc,
sizeof(pmc)) != 0)
7017 return (uint64)pmc.PeakWorkingSetSize;
7022 struct rusage usage;
7023 getrusage(RUSAGE_SELF, &usage);
7024 return (uint64)usage.ru_maxrss;
7027 struct rusage usage;
7028 getrusage( RUSAGE_SELF, &usage );
7029 return ((uint64)usage.ru_maxrss) * 1024L;
7051 SYSTEM_INFO siSysInfo;
7052 GetSystemInfo(&siSysInfo);
7053 return (uint16) siSysInfo.dwNumberOfProcessors;
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);
7061 long n = sysconf(_SC_NPROCESSORS_ONLN);
7063 return (uint16)(n > 65535 ? 65535 : (uint16)n);
7070 SYSTEM_INFO siSysInfo;
7071 GetSystemInfo(&siSysInfo);
7072 switch(siSysInfo.wProcessorArchitecture) {
7073 case PROCESSOR_ARCHITECTURE_AMD64:
7075 case PROCESSOR_ARCHITECTURE_IA64:
7077 case PROCESSOR_ARCHITECTURE_INTEL:
7083 #if defined(__x86_64__)
7085 #elif defined(__i386__)
7087 #elif defined(__aarch64__)
7093 #if defined(__x86_64__)
7095 #elif defined(__i386__)
7097 #elif defined(__aarch64__)
7129 size_t len =
sizeof(freq);
7130 if (sysctlbyname(
"hw.cpufrequency", &freq, &len, NULL, 0) == 0)
7135 std::ifstream cpuinfo(
"/proc/cpuinfo");
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) {
7142 if (sscanf(line.c_str() + colon + 1,
"%lf", &mhz) == 1 && mhz > 0)
7143 return (uint64)(mhz * 1000000.0);
7154 MEMORYSTATUS memstat;
7155 GlobalMemoryStatus(&memstat);
7156 return (uint64)memstat.dwTotalPhys;
7160 size_t len =
sizeof(memsize);
7161 if (sysctlbyname(
"hw.memsize", &memsize, &len, NULL, 0) == 0)
7165 struct sysinfo info;
7166 if (sysinfo(&info) == 0)
7167 return info.totalram;
7177 MEMORYSTATUSEX memstat;
7178 memset(&memstat, 0,
sizeof(MEMORYSTATUSEX));
7179 memstat.dwLength =
sizeof(MEMORYSTATUSEX);
7180 if (!GlobalMemoryStatusEx(&memstat)) {
7181 int a = GetLastError();
7184 totalRAM = (uint64)memstat.ullTotalPhys;
7185 freeRAM = (uint64)memstat.ullAvailPhys;
7190 size_t len =
sizeof(memsize);
7191 if (sysctlbyname(
"hw.memsize", &memsize, &len, NULL, 0) != 0)
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)
7198 vm_size_t page_size;
7199 if (host_page_size(mach_host_self(), &page_size) != KERN_SUCCESS)
7201 freeRAM = (uint64)vm_stat.free_count * (uint64)page_size;
7204 struct sysinfo info;
7205 if (sysinfo(&info) == 0) {
7206 totalRAM = info.totalram;
7207 freeRAM = info.freeram;
7219 SYSTEM_INFO siSysInfo;
7220 GetSystemInfo(&siSysInfo);
7222 switch(siSysInfo.wProcessorArchitecture) {
7223 case PROCESSOR_ARCHITECTURE_UNKNOWN:
7225 case PROCESSOR_ARCHITECTURE_INTEL:
7226 switch(siSysInfo.wProcessorLevel) {
7252 case PROCESSOR_ARCHITECTURE_MIPS:
7255 case PROCESSOR_ARCHITECTURE_ALPHA:
7258 case PROCESSOR_ARCHITECTURE_PPC:
7261 case PROCESSOR_ARCHITECTURE_IA64:
7264 case PROCESSOR_ARCHITECTURE_AMD64:
7278 if (strlen(
OSName) == 0) {
7314 BOOL bOsVersionInfoEx;
7319 ZeroMemory(&osvi,
sizeof(OSVERSIONINFO));
7320 osvi.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
7322 if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
7324 osvi.dwOSVersionInfoSize =
sizeof (OSVERSIONINFO);
7325 if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
7329 major = osvi.dwMajorVersion;
7330 minor = osvi.dwMinorVersion;
7331 if (strlen((
char*)osvi.szCSDVersion) < textSize)
7335 OSVERSIONINFOEX osvi;
7336 BOOL bOsVersionInfoEx;
7341 ZeroMemory(&osvi,
sizeof(OSVERSIONINFOEX));
7342 osvi.dwOSVersionInfoSize =
sizeof(OSVERSIONINFOEX);
7344 if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
7346 osvi.dwOSVersionInfoSize =
sizeof (OSVERSIONINFO);
7347 if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
7351 switch (osvi.dwPlatformId)
7354 case VER_PLATFORM_WIN32_NT:
7358 if( osvi.dwMajorVersion == 4 &&
7359 lstrcmpi( osvi.szCSDVersion,
"Service Pack 6" ) == 0 )
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 ) {
7371 build = osvi.dwBuildNumber & 0xFFFF;
7375 major = (uint16)osvi.dwMajorVersion;
7376 minor = (uint16)osvi.dwMinorVersion;
7377 build = (uint16)osvi.dwBuildNumber & 0xFFFF;
7378 if (strlen((
char*)osvi.szCSDVersion) < textSize)
7381 RegCloseKey( hKey );
7385 major = (uint16)osvi.dwMajorVersion;
7386 minor = (uint16)osvi.dwMinorVersion;
7387 build = (uint16)osvi.dwBuildNumber & 0xFFFF;
7389 if (strlen((
char*)osvi.szCSDVersion) < textSize)
7456char*
Int2Ascii(int64 value,
char* result, uint16 size, uint8 base) {
7457 if (base < 2 || base > 36) {
7462 char* ptr = result, *ptr1 = result, tmp_char;
7468 *ptr++ =
"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
7483char*
Uint2Ascii(uint64 value,
char* result, uint16 size, uint8 base) {
7484 if (base < 2 || base > 36) {
7489 char* ptr = result, *ptr1 = result, tmp_char;
7495 *ptr++ =
"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
7508 size = (len * 2) + 4;
7509 unsigned char* result =
new unsigned char[size];
7513 const char* src = ascii;
7514 for (uint32 n = 0; n < len; n++) {
7521 size = (len * 2) + 2;
7526bool GetSocketError(
int error,
char* errorString, uint16 errorStringMaxSize,
bool* isRecoverable) {
7528 if (errorStringMaxSize < 128)
7533 if (error == WSANOTINITIALISED) {
7534 utils::strcpyavail(errorString,
"Cannot initialize WinSock!", errorStringMaxSize,
true);
7535 *isRecoverable =
false;
7537 else if (error == WSAENETDOWN) {
7538 utils::strcpyavail(errorString,
"The network subsystem or the associated service provider has failed", errorStringMaxSize,
true);
7539 *isRecoverable =
false;
7541 else if (error == WSAEAFNOSUPPORT) {
7542 utils::strcpyavail(errorString,
"The specified address family is not supported", errorStringMaxSize,
true);
7543 *isRecoverable =
false;
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;
7549 else if (error == WSAEMFILE) {
7550 utils::strcpyavail(errorString,
"No more socket descriptors are available", errorStringMaxSize,
true);
7551 *isRecoverable =
false;
7553 else if (error == WSAENOBUFS) {
7554 utils::strcpyavail(errorString,
"No buffer space is available. The socket cannot be created", errorStringMaxSize,
true);
7555 *isRecoverable =
false;
7557 else if (error == WSAEPROTONOSUPPORT) {
7558 utils::strcpyavail(errorString,
"The specified protocol is not supported", errorStringMaxSize,
true);
7559 *isRecoverable =
false;
7561 else if (error == WSAEPROTOTYPE) {
7562 utils::strcpyavail(errorString,
"The specified protocol is the wrong type for this socket", errorStringMaxSize,
true);
7563 *isRecoverable =
false;
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;
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;
7573 else if (error == WSAEINVAL) {
7574 utils::strcpyavail(errorString,
"The socket has not been bound with bind", errorStringMaxSize,
true);
7575 *isRecoverable =
false;
7577 else if (error == WSAEISCONN) {
7578 utils::strcpyavail(errorString,
"The socket is already connected", errorStringMaxSize,
true);
7579 *isRecoverable =
false;
7581 else if (error == WSAENOTSOCK) {
7582 utils::strcpyavail(errorString,
"The descriptor is not a socket", errorStringMaxSize,
true);
7583 *isRecoverable =
false;
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;
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;
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;
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;
7602 utils::strcpyavail(errorString,
"The socket is marked as nonblocking and no connections are present to be accepted", errorStringMaxSize,
true);
7603 *isRecoverable =
false;
7605 else if (error == WSAETIMEDOUT) {
7606 utils::strcpyavail(errorString,
"Attempt to connect timed out without establishing a connection", errorStringMaxSize,
true);
7607 *isRecoverable =
false;
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;
7613 else if (error == WSAEISCONN) {
7614 utils::strcpyavail(errorString,
"The socket is already connected (connection-oriented sockets only)", errorStringMaxSize,
true);
7615 *isRecoverable =
false;
7617 else if (error == WSAECONNREFUSED) {
7618 utils::strcpyavail(errorString,
"The attempt to connect was forcefully rejected", errorStringMaxSize,
true);
7619 *isRecoverable =
false;
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;
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;
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;
7633 else if (error == WSAECONNRESET) {
7635 *isRecoverable =
false;
7637 else if (error == WSAECONNABORTED) {
7638 utils::strcpyavail(errorString,
"Software caused connection abort", errorStringMaxSize,
true);
7639 *isRecoverable =
false;
7642 snprintf(errorString, errorStringMaxSize,
"TCP error with no description: %d", error);
7643 *isRecoverable =
false;
7649 utils::strcpyavail(errorString,
"Cannot initialise socket", errorStringMaxSize,
true);
7650 *isRecoverable =
false;
7654 *isRecoverable =
false;
7664 int err = WSAGetLastError();
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),
7679 (LPTSTR) &lpMsgBuf, 0, NULL);
7680 std::string str = (
char*)lpMsgBuf;
7681 LocalFree(lpMsgBuf);
7711 ldiv_t d = ldiv(timeout*1000, 1000000);
7717 return( select(maxfd, NULL, &wds, NULL, &tv) > 0);
7743 ldiv_t d = ldiv(timeout*1000, 1000000);
7750 int ret = select(maxfd, &rdds, NULL, NULL, &tv);
7758 #if defined(WINDOWS)
7759 unsigned long parm = 1;
7760 ioctlsocket(s, FIONBIO, &parm);
7762 long parm = fcntl(s, F_GETFL);
7764 fcntl(s, F_SETFL, parm);
7770 #if defined(WINDOWS)
7771 unsigned long parm = 0;
7772 ioctlsocket(s, FIONBIO, &parm);
7774 long parm = fcntl(s, F_GETFL);
7775 parm &= ~O_NONBLOCK;
7776 fcntl(s, F_SETFL, parm);
7783 if ( (name == NULL) || (strlen(name) == 0) )
7799 struct addrinfo hints, *res;
7801 const char *cause = NULL;
7803 memset(&hints, 0,
sizeof(hints));
7806 hints.ai_family = AF_INET;
7807 hints.ai_socktype = SOCK_STREAM;
7808 hints.ai_protocol = IPPROTO_TCP;
7810 error = getaddrinfo(name, NULL, &hints, &res);
7812 __except (EXCEPTION_CONTINUE_EXECUTION) {
7817 memcpy(&address, res->ai_addr->sa_data + 2,
sizeof(address));
7827 struct addrinfo hints, *res;
7829 const char *cause = NULL;
7831 memset(&hints, 0,
sizeof(hints));
7833 hints.ai_family = PF_UNSPEC;
7834 hints.ai_socktype = SOCK_STREAM;
7835 error = getaddrinfo(name, NULL, &hints, &res);
7837 memcpy(&address, res->ai_addr->sa_data+2, 4);
7847 bool IsNetworkInitialised =
false;
7848 bool CheckNetworkInit() {
7849 if (IsNetworkInitialised)
return true;
7851 if (WSAStartup(MAKEWORD(1,1), &info) != 0) {
7855 IsNetworkInitialised =
true;
7862 struct hostent *pHost;
7864 unsigned char* addrChars = (
unsigned char*)&address;
7866 char* addrString =
new char[20];
7867 snprintf(addrString, 20,
"%u.%u.%u.%u", addrChars[0], addrChars[1], addrChars[2], addrChars[3]);
7870 pHost = gethostbyname(addrString);
7871 delete [] addrString;
7872 if (pHost == NULL) {
7875 if (strlen(pHost->h_name) > maxSize-1) {
7883 pHost = gethostbyname(addrString);
7884 delete [] addrString;
7888 if (strlen(pHost->h_name) > maxSize-1)
7895 pHost =
new struct hostent;
7898 gethostbyname_r(addrString, pHost, bf, 2000, &pHost, &er);
7899 delete [] addrString;
7905 if (strlen(pHost->h_name) > maxSize-1)
7917 char* name =
new char[256];
7923 std::string sname = name;
7931 if (gethostname(name, maxSize) == 0)
7992 for (uint32 i=0; i<c; i++) {
7993 if ( (interfaces[i].address != 0) && (interfaces[i].address !=
LOCALHOSTIP) )
7994 address = interfaces[i].
mac;
7996 delete [] interfaces;
7997 return (address != 0);
8005 uint64* addresses =
new uint64[c];
8007 for (uint32 i=0; i<c; i++) {
8008 if ( (interfaces[i].address != 0) && (interfaces[i].address !=
LOCALHOSTIP) )
8009 addresses[p++] = interfaces[i].
mac;
8026 if ((addresses == NULL) || (count == 0)) {
8027 delete [] addresses;
8032 for (n=0; n<count; n++) {
8033 if (addresses[n] == address) {
8034 delete [] addresses;
8038 delete [] addresses;
8046 if ((addresses == NULL) || (count == 0)) {
8047 delete [] addresses;
8052 bool localhostPresent =
false;
8053 for (n=0; n<count; n++) {
8055 if (addresses[n] != 0) {
8056 address = addresses[n];
8057 delete [] addresses;
8062 localhostPresent =
true;
8064 delete [] addresses;
8066 if (localhostPresent) {
8077 uint32 maxSize = 128;
8078 uint32* addresses =
new uint32[maxSize];
8083 char* szHostName =
new char[255];
8085 bool canAskHost =
true;
8086 if( gethostname(szHostName, 255) != 0 ) {
8089 if (err == WSANOTINITIALISED) {
8091 if (WSAStartup(MAKEWORD(1,1), &info) != 0) {
8092 delete [] szHostName;
8096 if( gethostname(szHostName, 255) != 0 )
8107 struct hostent * pHost;
8110 #if !defined(WINDOWS) && !defined(Darwin)
8116 char* hostBuf = NULL;
8117 struct hostent* hostAlloc = NULL;
8124 pHost = gethostbyname(szHostName);
8128 pHost = gethostbyname(szHostName);
8133 hostAlloc =
new struct hostent;
8134 hostBuf =
new char[2000];
8136 struct hostent* hres = NULL;
8137 int res = gethostbyname_r(szHostName, hostAlloc, hostBuf, 2000, &hres, &er);
8144 if ((res != 0) || (hres == NULL))
8151 for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
8154 memcpy(&addr, ((
unsigned char*)pHost->h_addr_list[i]),
sizeof(uint32));
8156 for (j=0; j<count; j++) {
8157 if (addresses[j] == addr) {
8163 addresses[count++] = addr;
8181 for (i=0; i<c; i++) {
8183 if ( (interfaces[i].address != 0) && (interfaces[i].address !=
LOCALHOSTIP) ) {
8184 for (j=0; j<count; j++) {
8185 if (addresses[j] == interfaces[i].address) {
8191 addresses[count++] = interfaces[i].
address;
8194 delete [] interfaces;
8195 delete [] szHostName;
8202 uint32 maxSize = 128;
8215 ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
8218 ULONG family = AF_INET;
8220 LPVOID lpMsgBuf = NULL;
8222 PIP_ADAPTER_ADDRESSES pAddresses = NULL;
8223 ULONG outBufLen = 0;
8224 ULONG Iterations = 0;
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;
8238 pAddresses = (IP_ADAPTER_ADDRESSES *)
MALLOC(outBufLen);
8239 if (pAddresses == NULL)
8243 GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
8245 if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
8254 }
while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < 10));
8257 if (dwRetVal == NO_ERROR) {
8259 pCurrAddresses = pAddresses;
8260 while (pCurrAddresses) {
8261 if ( (pCurrAddresses->OperStatus == IfOperStatusUp) && (pCurrAddresses->IfIndex != 0)) {
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);
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 );
8277 pUnicast = pUnicast->Next;
8282 pCurrAddresses = pCurrAddresses->Next;
8293 struct sockaddr_in *saptr = NULL;
8294 struct if_nameindex *iflist = NULL, *listsave = NULL;
8297 if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
8302 iflist = listsave = if_nameindex();
8304 if (iflist == NULL) {
8312 for(; iflist->if_index != 0; iflist++) {
8314 strncpy(ifreq.ifr_name, iflist->if_name, IF_NAMESIZE);
8316 if(ioctl(sock, SIOCGIFADDR, &ifreq) != 0) {
8321 saptr = (
struct sockaddr_in *)&ifreq.ifr_addr;
8324 memcpy(&(interfaces[count].address), &(saptr->sin_addr.s_addr),
sizeof(uint32));
8327 interfaces[count].
mac = 0;
8330 interfaces[count].
mac = 0;
8331 ioctl(sock, SIOCGIFHWADDR, &ifreq);
8332 memcpy(&(interfaces[count].mac), &(ifreq.ifr_hwaddr.sa_data), 6);
8337 if_freenameindex(listsave);
8349 struct sockaddr_in addr;
8350 addr.sin_family= AF_INET;
8351 addr.sin_addr.s_addr=INADDR_ANY;
8352 bool result =
false;
8354 nextPort = lastPort + 1;
8355 while (nextPort < lastPort + 1000) {
8356 if((socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==
INVALID_SOCKET)
8363 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
char *) &one,
sizeof(one));
8375 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,
sizeof(one));
8378 addr.sin_port=htons(nextPort);
8394 printf(
"Testing Utils...\n\n");
8396 char hostname[1024];
8398 printf(
"Error GetLocalHostname\n");
8401 printf(
"Local Hostname: '%s'\n\n", hostname);
8404 unsigned char* addrChars = (
unsigned char*) &addr;
8406 printf(
"Error GetLocalIPAddress\n");
8409 printf(
"Local IP Address: %u.%u.%u.%u\n\n", addrChars[0], addrChars[1], addrChars[2], addrChars[3]);
8413 if (addresses == NULL) {
8414 printf(
"Error GetLocalIPAddresses\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);
8422 delete [] addresses;
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);
8430 delete [] interfaces;
8435void PrintBinary(
void* p, uint32 size,
bool asInt,
const char* title) {
8437 printf(
"--- %s %u ---\n", title, size);
8439 for (uint32 n=0; n<size; n++) {
8440 c = *(((
unsigned char*)p)+n);
8442 printf(
"[%u] ", (
unsigned int)c);
8445 if ( (n > 0) && ((n+1)%10 == 0) )
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;
8476 for (; *str; str++, n++) {
8481 while ((*a++ | 32) == (*b++ | 32)) {
8484 if (len && (++m > len))
8491uint32
strcpyavail(
char* dst,
const char* src, uint32 maxlen,
bool copyAvailable) {
8492 if ( !dst || ! src || !maxlen )
8494 uint32 len = (uint32)strlen(src);
8495 if (len > maxlen-1) {
8499 memcpy(dst, src, maxlen-1);
8505 memcpy(dst, src, len+1);
8513 for (len = 0; len < size; len++) {
8515 if (str[len] == 13) {
8516 crSize = ( (len < size-1) && (str[len+1] == 10 ) ) ? 2 : 1;
8520 if (str[len] == 10) {
8531 std::string str = text;
8534 std::string::iterator i = str.begin(), e = str.end();
8538 std::transform(i, e, i, ::tolower);
8543 std::string str = text;
8544 std::transform(str.begin(), str.end(), str.begin(), ::toupper);
8549 std::string str = text;
8550 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
8556 std::vector<std::string>::iterator i = lines.begin(), e = lines.end();
8566 uint32 len = (uint32)strlen(text);
8567 if (!len)
return "";
8572 uint32 s = 0, p = 0;
8574 while ( ((text[s] ==
'\n') || (text[s] ==
'\r')) && (s < len))
8577 while ((text[p] <= 32) && (p < len))
8579 std::string indentString = std::string(text+s, p-s);
8580 std::string str = text;
8588 uint32 begin = 0, end = (uint32)strlen(text);
8591 while ((begin < end) && (text[begin] <= 32) || (text[begin] ==
'\"') || (text[begin] ==
'\''))
8595 while ((end > begin) && (text[end-1] <= 32) || (text[end-1] ==
'\"') || (text[end-1] ==
'\''))
8597 return std::string(text+begin, end-begin);
8606 uint32 begin = 0, end = (uint32)strlen(text);
8609 while ((text[begin] <= 32) && (begin < end))
8611 while ((end > begin) && (text[end-1] <= 32))
8613 return std::string(text+begin, end-begin);
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;
8623 if (!text || !outersplit || !innersplit)
8626 const char* pstr = text, *lstr = text;
8627 const char* src = text;
8629 while (pstr = strstr(src, outersplit)) {
8630 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8632 result.insert(Map_String_Pair(
TextTrim(std::string(src, lstr-src).c_str()),
TextTrim(std::string(lstr+1, pstr-lstr-1).c_str())));
8636 pstr = src + strlen(src);
8637 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8639 result.insert(Map_String_Pair(
TextTrim(std::string(src, lstr-src).c_str()),
TextTrim(std::string(lstr+1, pstr-lstr-1).c_str())));
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;
8650 if (!text || !outersplit || !innersplit)
8653 const char* pstr = text, *lstr = text;
8654 const char* src = text;
8656 while (pstr = strstr(src, outersplit)) {
8657 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8659 result.insert(Map_String_Pair(
TextTrim(std::string(src, lstr - src).c_str()),
TextTrim(std::string(lstr + 1, pstr - lstr - 1).c_str())));
8663 pstr = src + strlen(src);
8664 if ((lstr = strstr(src, innersplit)) && (lstr < pstr)) {
8666 result.insert(Map_String_Pair(
TextTrim(std::string(src, lstr - src).c_str()),
TextTrim(std::string(lstr + 1, pstr - lstr - 1).c_str())));
8674 uint32 size = (uint32)args.size();
8678 char** argv =
new char*[size+1];
8680 std::vector<std::string>::iterator i = args.begin(), e = args.end();
8682 argv[c] =
new char[(*i).length()+1];
8683 strcpy(argv[c], (*i).c_str());
8694 uint32 size = (uint32)args.size();
8698 wchar_t** argv =
new wchar_t*[size+1];
8700 std::vector<std::string>::iterator i = args.begin(), e = args.end();
8702 argv[c] =
new wchar_t[(*i).length()+1];
8703 mbstowcs(argv[c], (*i).c_str(), (*i).length() + 1);
8713 for (uint32 n=0; n<(uint32)argc; n++)
8721 bool insideQuotes =
false;
8722 bool lastWasWhiteSpace =
false;
8723 std::vector<std::string> vect;
8724 std::string arg, val, str;
8727 uint32 len = (uint32)strlen(cmdline);
8729 bool keepQuotes =
false;
8731 for (uint32 n=0; n<len; n++) {
8734 if (!insideQuotes) {
8735 if (!lastWasWhiteSpace) {
8737 vect.push_back(str);
8743 lastWasWhiteSpace =
true;
8749 else if (ch ==
'"') {
8750 insideQuotes = !insideQuotes;
8753 lastWasWhiteSpace =
false;
8757 lastWasWhiteSpace =
false;
8761 if (str.length() > 0) {
8762 vect.push_back(str);
8770 if (!text || !strlen(text))
8771 return std::vector<std::string>();
8773 if (strstr(text,
"\r\n"))
8775 else if (strstr(text,
"\n\r"))
8777 else if (strstr(text,
"\n"))
8779 else if (strstr(text,
"\r"))
8782 std::vector<std::string> result;
8783 result.push_back(text);
8788 if (!text || !strlen(text))
8789 return std::vector<std::string>();
8792 std::vector<std::string> result;
8793 uint32 s = 0, n = 0, len = (uint32)strlen(text);
8796 if (text[n] == 13) {
8798 result.push_back(
"");
8800 str = std::string(text + s, n - s);
8801 result.push_back(
TextTrim(str.c_str()));
8803 if ((n < len - 1) && (text[n + 1] == 10))
8809 else if (text[n] == 10) {
8811 result.push_back(
"");
8813 str = std::string(text + s, n - s);
8814 result.push_back(
TextTrim(str.c_str()));
8816 if ((n < len - 1) && (text[n + 1] == 13))
8822 else if ((n-s < maxLineLength) && (text[n] == 32)) {
8825 else if (n - s >= maxLineLength) {
8827 result.push_back(
"");
8833 str = std::string(text + s, p);
8834 result.push_back(
TextTrim(str.c_str()));
8840 str = std::string(text + s, maxLineLength);
8841 result.push_back(
TextTrim(str.c_str()));
8850 str = std::string(text + s, n - s);
8851 result.push_back(
TextTrim(str.c_str()));
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;
8870 if (!count || ((l >= start) && (c < count))) {
8871 if (c++) o << split;
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;
8885 if (!count || ((l >= start) && (c < count))) {
8886 if (c++) o << split;
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();
8900 if (c++) o << outersplit;
8901 if (keyquotes && valquotes)
8902 o <<
"\"" << i->first <<
"\"" << innersplit <<
"\"" << i->second <<
"\"";
8904 o << i->first << innersplit <<
"\"" << i->second <<
"\"";
8906 o << i->first << innersplit << i->second;
8913 std::ostringstream o;
8914 std::map<std::string, std::string>::iterator i = map.begin(), e = map.end();
8928std::string
TextJoinXML(std::map<std::string, std::string> &map,
const char* innernodeName,
const char* outernodeName) {
8929 if (!innernodeName || !strlen(innernodeName))
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";
8939 if (outernodeName && strlen(outernodeName))
8940 o <<
"</" << outernodeName <<
">\n";
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)
8951 uint32 splitLen = (uint32)strlen(split);
8952 const char* pstr = text;
8953 const char* src = text;
8955 while (pstr = strstr(src, split)) {
8956 if (pstr - src || keepEmpty) {
8958 result.push_back(
TextTrim(std::string(src, pstr - src).c_str()));
8960 result.push_back(std::string(src, pstr - src).c_str());
8962 src = pstr + splitLen;
8964 pstr = src + strlen(src);
8967 result.push_back(
TextTrim(std::string(src, pstr - src).c_str()));
8969 result.push_back(std::string(src, pstr - src).c_str());
8976 std::vector<std::string>::iterator i, e;
8977 for (i=vect.begin(), e=vect.end(); i!=e; i++) {
8978 if (allowEmpty || (*i).size()) {
8988 if (strlen(format) == 0) {
8994 va_start(args, format);
9005 int len = _vscprintf(format, orig_args) + 10;
9006 str = (
char*)malloc(len+1);
9008 len = vsnprintf(str, len, format, orig_args);
9010 len = _vsnprintf_s(str, len, len+1, format, orig_args);
9014 size = (uint32)strlen(str);
9021 int len = vasprintf(&str, format, orig_args);
9032 if (!dst || !maxsize)
9034 if (strlen(format) == 0) {
9041 va_start(args, format);
9045 if (len > maxsize) {
9062 if (strlen(format) == 0)
9068 va_start(args, format);
9080 if (!text.size() || !key.size())
9085 uint32 keylen = (uint32)key.size();
9087 while ( (p = text.find(key, p)) != std::string::npos) {
9088 text.replace(p, keylen, value);
9098 if (!text.size() || !map.size())
9103 std::map<std::string, std::string>::iterator it, itEnd;
9104 for (it = map.begin(), itEnd = map.end(); it != itEnd; ++it)
9131uint32
StringScriptReplace(std::string& text, std::string name, std::list<std::map<std::string, std::string> >& list) {
9132 if (!text.size() || !name.size())
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());
9143 size_t a1 = text.find(start);
9144 if (a1 == std::string::npos) {
9149 size_t b1 = text.find(end);
9150 if (b1 == std::string::npos) {
9156 uint32 a2 = (uint32)(a1 + strlen(start));
9157 uint32 b2 = (uint32)(b1 + strlen(end));
9160 std::string section = text.substr(a2, b1-a2);
9164 std::list<std::map<std::string, std::string> >::iterator it, itEnd;
9165 for (it = list.begin(), itEnd = list.end(); it != itEnd; ++it) {
9171 text.replace(a1, b2-a1, result);
9180 unsigned char c = (
unsigned char) strtol(str, NULL, 16);
9188 unsigned char c = (
unsigned char) strtol(str, NULL, 10);
9196 float64 diff = a - b;
9197 if ((diff < std::numeric_limits<float64>::epsilon()) && (-diff < std::numeric_limits<float64>::epsilon()))
9206#define poly 0xEDB88320
9214int CRC32(
const char *addr, uint32 length, int32 crc) {
9216 for (; length>0; length--) {
9217 crc = crc ^ *addr++;
9218 for (i=0; i<8; i++) {
9220 crc = (crc >> 1) ^
poly;
9234 char* data =
ReadAFile(filename.c_str(), length,
false);
9235 if (!data || !length)
9237 std::string dataString = data;
9242char*
ReadAFile(
const char* dir,
const char* filename, uint32& length,
bool binary) {
9243 if (!dir || !filename || strlen(filename) == 0)
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);
9253char*
ReadAFile(
const char* filename, uint32& length,
bool binary) {
9254 if (!filename || strlen(filename) == 0)
9261 file = fopen(filename,
"rb");
9263 file = fopen(filename,
"r");
9269 fseek(file, 0, SEEK_END);
9270 length = ftell(file);
9271 fseek(file, 0, SEEK_SET);
9279 char* data =
new char[length+1];
9281 int res = (int)fread(data, 1, length, file);
9283 if ((res <= 0) || (res != length)) {
9284 int error = ferror(file);
9285 int eof = feof(file);
9289 LogPrint(0,0,0,
"File %s has no data", filename);
9296 length = (uint32)res;
9301bool WriteAFile(
const char* dir,
const char* filename,
const char* data, uint32 length,
bool binary) {
9302 if (!dir || !filename || strlen(filename) == 0)
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);
9312bool WriteAFile(
const char* filename,
const char* data, uint32 length,
bool binary) {
9313 if (!filename || strlen(filename) == 0)
9318 file = fopen(filename,
"wb");
9320 file = fopen(filename,
"w");
9324 int res = (int)fwrite(data, 1, length, file);
9326 return (res == length);
9329bool AppendToAFile(
const char* dir,
const char* filename,
const char* data, uint32 length,
bool binary) {
9330 if (!dir || !filename || strlen(filename) == 0)
9333 char* fullname =
new char[strlen(dir) + strlen(filename) + 5];
9334 snprintf(fullname, strlen(dir) + strlen(filename) + 5,
"%s/%s", dir, filename);
9340bool AppendToAFile(
const char* filename,
const char* data, uint32 length,
bool binary) {
9341 if (!filename || strlen(filename) == 0)
9346 file = fopen(filename,
"ab");
9348 file = fopen(filename,
"a");
9352 int res = (int)fwrite(data, 1, length, file);
9354 return (res == length);
9358 if (!dir || !filename || strlen(filename) == 0)
9361 char* fullname =
new char[strlen(dir) + strlen(filename) + 5];
9362 snprintf(fullname, strlen(dir) + strlen(filename) + 5,
"%s/%s", dir, filename);
9373 if (!filename || strlen(filename) == 0)
9377 return (SetFileAttributes(filename, FILE_ATTRIBUTE_READONLY) != 0);
9379 return (SetFileAttributes(filename, FILE_ATTRIBUTE_NORMAL) != 0);
9382 return (chmod(filename,S_IREAD | S_IWRITE) != 0);
9384 return (chmod(filename,S_IREAD) == 0);
9386 return (chmod(filename,S_IWRITE) == 0);
9388 return (chmod(filename,0) == 0);
9392bool MoveAFile(
const char* oldfilename,
const char* newfilename,
bool force) {
9396 result = (MoveFileEx(oldfilename, newfilename, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != 0);
9398 result = (MoveFileEx(oldfilename, newfilename, MOVEFILE_COPY_ALLOWED) != 0);
9404 if (rename(oldfilename, newfilename) == 0)
9410 delete(newfilename);
9411 if (rename(oldfilename, newfilename) == 0)
9415 if (error == EXDEV) {
9416 if (
CopyAFile(newfilename, oldfilename)) {
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) )
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);
9440bool CopyAFile(
const char* oldfilename,
const char* newfilename,
bool force) {
9443 return (CopyFile(oldfilename, newfilename,
FALSE) != 0);
9445 return (CopyFile(oldfilename, newfilename,
TRUE) != 0);
9453 char* data =
ReadAFile(oldfilename, size,
true);
9454 if (!data || !size) {
9464 if (!
WriteAFile(newfilename, data, size,
true)) {
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) )
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);
9489 if (!dirname || strlen(dirname) == 0)
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)
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] ==
':');
9520 if (CreateDirectory(dirname, NULL) != 0)
9525 if (mkdir(dirname, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
9533 if (!dirname || strlen(dirname) == 0)
9544 if (DeleteFile(dirname) != 0)
9550 if (DeleteFile(dirname) != 0)
9556 if (unlink(dirname) == 0)
9562 if (unlink(dirname) == 0)
9572 if (RemoveDirectory(dirname) != 0)
9578 if (RemoveDirectory(dirname) != 0)
9584 if (rmdir(dirname) == 0)
9590 if (rmdir(dirname) == 0)
9600 if (!dirname || strlen(dirname) == 0)
9609 for (uint32 n = 0; n<count; n++) {
9627 for (uint32 n=0; n<size; n++) {
9628 if (str[n] == find) {
9640 len2 = (int)strlen(str2);
9644 len1 = (int)strlen(str1);
9646 return (strcmp(str1, str2) == 0) ? str1 : 0;
9647 else if (len1 - len2 < 0)
9650 strp = (
char*)(str1 + len1 - len2);
9651 while(strp != str1) {
9652 if(*strp == *str2) {
9653 if(strncmp(strp,str2,len2)==0)
9665 len2 = (int)strlen(str2);
9669 len1 = (int)strlen(str1);
9671 return (
stricmp(str1, str2) == 0) ? str1 : 0;
9672 else if (len1 - len2 < 0)
9675 strp = (
char*)(str1 + len1 - len2);
9676 while(strp != str1) {
9677 if(*strp == *str2) {
9688 return (
laststristr(str, end) == str + strlen(str) - strlen(end));
9690 return (
laststrstr(str, end) == str + strlen(str) - strlen(end));
9695 return (
stristr(str, start) == str);
9697 return (strstr(str, start) == str);
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)
9709 return name.substr(0, p2 + 1);
9711 else if (p2 == std::string::npos)
9712 return name.substr(0, p1 + 1);
9714 return name.substr(0, (p1 > p2) ? p1 + 1 : p2 + 1);
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)
9725 return filename + p2 + 1;
9727 else if (p2 == std::string::npos)
9728 return filename + p1 + 1;
9730 return (p1 > p2) ? filename + p1 + 1 : filename + p2 + 1;
9735 char cCurrentPath[FILENAME_MAX];
9741 cCurrentPath[
sizeof(cCurrentPath) - 1] =
'\0';
9743 return cCurrentPath;
9746char*
GetFileList(
const char* dirname,
const char* ext, uint32& count,
bool fullpath, uint32 maxNameLen) {
9751 uint32 extlen = (ext == NULL) ? 0 : (uint32)strlen(ext);
9752 struct dirent* direntry = NULL;
9754 uint32 tempMaxCount = 50;
9755 uint32 len = (maxNameLen+1)*tempMaxCount;
9756 char* result =
new char[len];
9759 uint32 dirnamelen = (uint32)strlen(dirname);
9760 bool dirslash = (*(dirname + dirnamelen - 1) ==
'/') || (*(dirname + dirnamelen - 1) ==
'\\');
9768 if (direntry->
d_name[0] !=
'\0') {
9770 if ( !strcmp(direntry->
d_name,
".") || !strcmp(direntry->
d_name,
"..") ) {
9781 memset(dst+dirnamelen,
'/', 1);
9791 if (count >= tempMaxCount) {
9793 tmp =
new char[len*2];
9794 memcpy(tmp, result, len);
9818 struct stat statbuf;
9834 if ((fd = _open(filename, O_RDONLY)) == -1) {
9853 result = fstat(fd, &statbuf);
9864 info.
size = statbuf.st_size;
9865 info.
isDirectory = ((statbuf.st_mode & S_IFDIR) != 0);
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);
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);
9887 if (!ascii || (start >= end) || (!(len = (uint32)strlen(ascii))) ) {
9894 copy =
new char[end - start + 2];
9895 memcpy(copy, ascii + start,
9897 copy[end - start + 1] = 0;
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] !=
'.')
9916 if (!ascii || (start > end))
return false;
9919 return _strtoi64(ascii + start, NULL, 10);
9921 return strtoll(ascii + start, NULL, 10);
9925 int64 val = _strtoi64(copy, NULL, 10);
9927 int64 val = strtoll(copy, NULL, 10);
9934 if (!ascii || (start > end))
return false;
9937 return _strtoui64(ascii + start, NULL, 10);
9939 return strtoull(ascii + start, NULL, 10);
9943 uint64 val = _strtoui64(copy, NULL, 10);
9945 uint64 val = strtoull(copy, NULL, 10);
9952 if (!ascii || (start > end))
return false;
9955 return _strtoui64(ascii + start, NULL, 16);
9957 return strtoull(ascii + start, NULL, 16);
9961 uint64 val = _strtoui64(copy, NULL, 16);
9963 uint64 val = strtoull(copy, NULL, 16);
9970 if (!ascii || (start > end))
return false;
9972 return (int32)strtol(ascii + start, NULL, 10);
9974 int32 val = (int32)strtol(copy, NULL, 10);
9980 if (!ascii || (start > end))
return false;
9982 return (uint32)strtoul(ascii + start, NULL, 10);
9984 uint32 val = (uint32)strtoul(copy, NULL, 10);
9990 if (!ascii || (start > end))
return false;
9992 return (uint32)strtoul(ascii + start, NULL, 16);
9994 uint32 val = (uint32)strtoul(copy, NULL, 16);
10000 if (!ascii || (start > end))
return false;
10002 return strtod(ascii + start, NULL);
10004 float64 val = strtod(copy, NULL);
10011 bool isEscaped =
false;
10012 char* tmp =
new char[5];
10014 std::ostringstream o;
10015 std::string::iterator c;
10016 for (c = str.begin(); c != str.end(); 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;
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);
10040 case '\\': isEscaped =
true;
break;
10050 std::ostringstream o;
10051 std::string::iterator c;
10052 for (c = str.begin(); c != str.end(); 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;
10062 if (
'\x00' <= *c && *c <=
'\x1f') {
10064 << std::hex << std::setw(4) << std::setfill(
'0') << (int)*c;
10126 srand( seedvalue ? seedvalue : (uint32)
GetTimeNow());
10133 double t = (1.0/((RAND_MAX + 1.0)*(RAND_MAX + 1.0)*(RAND_MAX + 1.0)));
10135 d = (rand () * ((RAND_MAX + 1.0) * (RAND_MAX + 1.0))
10136 + rand () * (RAND_MAX + 1.0)
10160 uint64 n = (uint64)(r/interval);
10161 double l = r - (n*interval);
10162 if (l >= (0.5*interval))
10163 return from + (n*interval);
10165 return from + ((n+1)*interval);
10169 return (int64)roundl(
RandomValue((
double)from, (
double)to));
10180 double mb = kb*1024;
10181 double gb = mb*1024;
10182 double tb = gb*1024;
10184 char *tmp =
new char[64];
10187 snprintf(tmp, 64,
"%.2f B", val);
10188 else if (val < 512*kb) {
10190 snprintf(tmp, 64,
"%.2f KB", val);
10192 else if (val < 512*mb) {
10194 snprintf(tmp, 64,
"%.2f MB", val);
10196 else if (val < 512*gb) {
10198 snprintf(tmp, 64,
"%.2f GB", val);
10202 snprintf(tmp, 64,
"%.2f TB", val);
10205 std::string result = tmp;
10217 double mb = kb*1024;
10218 double gb = mb*1024;
10219 double tb = gb*1024;
10221 char *tmp =
new char[64];
10222 char *end =
new char[64];
10225 double maximum = ((val1 > val2) ? val1 : val2);
10227 if (maximum < 512) {
10231 else if (maximum < 512*kb) {
10235 else if (maximum < 512*mb) {
10239 else if (maximum < 512*gb) {
10247 snprintf(tmp, 64,
"%.2f / %.2f %s", ((
double)val1)/val, ((
double)val2)/val, (
char*) end);
10249 std::string result = tmp;
10261 char *tmp =
new char[64];
10262 snprintf(tmp, 64,
"%s/sec", (
char*)
BytifySize(val).c_str());
10263 std::string result = tmp;
10273 char *tmp =
new char[64];
10274 snprintf(tmp, 64,
"%s/sec", (
char*)
BytifySizes(val1, val2).c_str());
10275 std::string result = tmp;
10289 HKEY hKeyRoot, hKey;
10290 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10292 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10293 if (err != ERROR_SUCCESS)
10296 DWORD dwType = REG_DWORD;
10298 DWORD dwSize =
sizeof(numVal);
10300 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)&numVal, &dwSize);
10302 if (err != ERROR_SUCCESS)
10308 HKEY hKeyRoot, hKey;
10309 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10311 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10312 if (err != ERROR_SUCCESS)
10315 DWORD dwType = REG_QWORD;
10317 DWORD dwSize =
sizeof(numVal);
10319 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)&numVal, &dwSize);
10321 if (err != ERROR_SUCCESS)
10327 HKEY hKeyRoot, hKey;
10328 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10330 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10331 if (err != ERROR_SUCCESS) {
10335 DWORD dwType = REG_SZ;
10336 DWORD dwSize = 4096;
10337 char* lszValue =
new char[dwSize];
10339 err = RegQueryValueEx(hKey, entry, NULL, &dwType, (LPBYTE)lszValue, &dwSize);
10341 if (err != ERROR_SUCCESS) {
10346 std::string val = lszValue;
10352 DWORD dwDisposition;
10353 HKEY hKeyRoot, hKey;
10354 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
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)
10363 DWORD dwType = REG_DWORD;
10364 err = RegSetValueEx(hKey, entry, 0, dwType, (
const BYTE*)&value,
sizeof(value));
10366 return (err == ERROR_SUCCESS);
10370 DWORD dwDisposition;
10371 HKEY hKeyRoot, hKey;
10372 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
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)
10381 DWORD dwType = REG_QWORD;
10382 err = RegSetValueEx(hKey, entry, 0, dwType, (
const BYTE*)&value,
sizeof(value));
10384 return (err == ERROR_SUCCESS);
10388 DWORD dwDisposition;
10389 HKEY hKeyRoot, hKey;
10390 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
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)
10399 DWORD dwType = REG_SZ;
10400 DWORD dwSize = 4096;
10402 err = RegSetValueEx(hKey, entry, 0, dwType, (LPBYTE)value, (DWORD)(strlen(value) + 1));
10404 return (err == ERROR_SUCCESS);
10408 HKEY hKeyRoot, hKey;
10409 std::string keySubName = GetRegistryKeyInfo(key, hKeyRoot);
10411 uint32 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_SET_VALUE | KEY_WOW64_64KEY, &hKey);
10412 if (err != ERROR_SUCCESS)
10416 err = RegDeleteValue(hKey, entry);
10417 return (err == ERROR_SUCCESS);
10424 std::string keySubName = GetRegistryKeyInfo(entry, hKeyRoot);
10425 uint32 err = RegDeleteKeyEx(hKeyRoot, keySubName.c_str(), KEY_WOW64_64KEY, 0);
10426 return (err == ERROR_SUCCESS);
10430 if (!key || !strlen(key))
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)
10440 err = RegDeleteTree(hKey, key);
10441 return (err == ERROR_SUCCESS);
10453 DWORD dwDisposition;
10460 std::string keySubName = GetRegistryKeyInfo(entry, hKeyRoot);
10461 std::string keySubNewName = GetRegistryKeyInfo(newName, hKeyNewRoot);
10463 err = RegOpenKeyEx(hKeyRoot, keySubName.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
10464 if (err != ERROR_SUCCESS)
10467 err = RegCreateKeyEx(hKeyNewRoot, keySubNewName.c_str(), 0, NULL, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, NULL, &hKeyNew, &dwDisposition);
10468 if (err != ERROR_SUCCESS) {
10473 err = RegCopyTree(hKey, NULL, hKeyNew);
10476 RegCloseKey(hKeyNew);
10478 if (err != ERROR_SUCCESS) {
10479 RegDeleteKeyEx(hKeyNewRoot, keySubNewName.c_str(), KEY_WOW64_64KEY, 0);
10505std::string GetRegistryKeyInfo(
const char* key, HKEY &hKeyRoot) {
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;
10520std::string GetRegistryParentKeyInfo(
const char* key, HKEY &hKeyRoot) {
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;
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");
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");
HTML/URL helper utilities: entity encoding/decoding, MIME type lookup and URL component parsing.
#define PROC_ERROR
Error state.
Object type ids used to tag and verify every binary structure in CMSDK memory.
#define DATAMESSAGEINFOID
Process-wide thread registry and lifecycle manager: the concurrency core of CMSDK.
Small, dependency-free unit test harness used by all CMSDK object tests.
Cross-platform utility toolbox for CMSDK: threading, synchronization, shared memory,...
#define thread_ret_val(ret)
#define THREAD_STATS_ADHOC
#define THREAD_FUNCTION_CALL
THREAD_RET(* THREAD_FUNCTION)(void *)
#define THREAD_STATS_AUTO
RAII guard whose single static instance triggers global utility cleanup at program exit.
CleanShutdown()
Default constructor; no side effects.
~CleanShutdown()
Destroys all lazily-created global utility maps via ClearUtilsMaps().
Callback interface for receiving log entries produced through LogSystem.
Process-wide singleton logging hub with per-topic verbosity/debug levels.
static bool SetLogFileOutput(const char *logfile, bool printOut=true)
Direct log output to a file.
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
static bool LogSystemPrint(uint32 source, uint8 subject, uint8 level, const char *formatstring,...)
printf-style informational logging (usually invoked via the LogPrint macro).
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...
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
static bool SetLogLevelDebug(uint8 level)
Set the debug level threshold for all topics.
static bool SetLogLevelVerbose(uint8 level)
Set the verbose (print) level threshold for all topics.
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()).
static CommandLineInfo * CommandLineInfoSingleton
Auto-reset notification event (condition variable style), optionally named for cross-process use.
bool waitNext()
Block until the next signal() occurs.
Event()
Create an anonymous, process-local event.
bool signal()
Wake all threads currently waiting on this event.
Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen).
LibraryFunction getFunction(const char *funcName)
Resolve an exported function.
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...
bool load(const char *filename)
Load a library.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Mutex()
Create an anonymous, process-local mutex.
void setCancelSafe(bool on)
Make this mutex cancellation-safe (POSIX only; no-op on Windows).
bool leave()
Release the mutex.
bool enter()
Block until the mutex is acquired.
Counting semaphore, optionally named for cross-process use.
Semaphore(uint32 maxCount=100)
Create an anonymous semaphore.
bool signal()
Increment (release) the semaphore, waking one waiter.
bool wait()
Block until the semaphore can be decremented.
Multiplexing timer: schedule many periodic timers and consume their expiries from one queue.
bool addTimer(uint32 id, uint32 interval, uint64 start=0, uint64 end=0)
Register a periodic timer.
static std::map< uint32, Timer * > * timers
Global registry mapping globalID to live Timer instances, used by the OS callbacks.
bool triggerTimer(uint32 id)
Manually inject an expiry for timer id, as if it had fired now.
bool waitForTimer(uint32 timeout, uint32 &id, uint64 &time)
Wait for the next expiry of any registered timer.
bool removeTimer(uint32 id)
Unregister a timer and cancel its OS timer.
uint64 FTime2PsyTime(uint64 t)
Convert an ftime-style value (ms since Unix epoch) to a PsyTime µs timestamp.
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
std::string PrintTimeNowString(bool local=true, bool us=true, bool ms=true)
Format GetTimeNow().
std::string PrintTimeDifString(uint64 t, bool us=true, bool ms=true)
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
bool UnitTest_Utils()
Aggregate self test for miscellaneous utils functionality.
int64 AtomicDecrement64(int64 volatile &v)
Atomically decrement a 64-bit value.
bool ResizeProcessTerminal(uint32 proc, uint16 cols, uint16 rows)
Resize the pseudo-terminal (TIOCSWINSZ + SIGWINCH to the child's group).
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.
bool SetSharedSystemInstance(uint32 inst)
Set the instance number used to namespace shared OS objects, allowing several independent CMSDK syste...
static std::map< uint32, ProcessData * > * ProcessInformationMap
uint32 GetThreadStatColAbility()
Report this platform's capability for per-thread CPU statistics collection.
bool UnitTest_MutexOwnerDeath()
void ReleaseProcessCapture(uint32 proc)
POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captur...
bool WaitForThreadToFinish(ThreadHandle hThread, uint32 timeoutMS=0)
Join a thread.
bool SignalSemaphore(const char *name)
Signal a named global semaphore.
bool GetThreadPriority(ThreadHandle hThread, uint16 priority)
Query a thread's scheduling priority.
bool UnitTest_ChildSignalMask()
Self test: a child launched with the shutdown signals blocked still stops on SIGTERM (POSIX).
std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
int FromOSPriority(int pri)
Map a native OS priority back to the CMSDK priority scale.
bool CloseProcessInput(uint32 proc)
Close a child's stdin, delivering EOF (T1.1 step 2.7c).
bool EndProcess(uint32 proc)
Forcibly terminate a child process.
std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
static Mutex * SharedMemorySemaphoreMapMutex
bool GetLastOccupiedBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the highest set (occupied) bit.
const char * laststrstr(const char *str1, const char *str2)
Find the last occurrence of str2 in str1.
uint32 RemovePortSharedSegments(uint16 port)
Remove every shared-memory/semaphore name for this port (as ClearStaleSharedSegments,...
std::pair< std::string, Event * > SharedMemoryEventMapPair
bool DestroyEvent(const char *name)
Destroy a named global event.
bool WaitForSemaphore(const char *name, uint32 ms, bool autocreate=true)
Wait on a named global semaphore.
static SharedMemoryFileHandleMapType * SharedMemoryFileHandleMap
bool TextStartsWith(const char *str, const char *start, bool caseSensitive=true)
Test whether str starts with start.
bool Sleep(uint32 ms)
Suspend the calling thread.
bool SetThreadPriority(ThreadHandle hThread, uint16 priority)
Set a thread's scheduling priority.
bool ReadProcessTerminal(uint32 proc, std::string &out, bool &eofOut)
Non-blocking read of the merged terminal stream.
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.
bool UnitTest_SemaphoreUserDeath()
bool PauseThread(ThreadHandle hThread)
Suspend a thread's execution.
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...
static std::map< std::string, Event * > * SharedMemoryEventMap
bool MoveConsoleWindow(int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
Move/resize the console window.
bool WriteProcessTerminal(uint32 proc, const char *data, uint32 len)
Write bytes to the child's terminal input (its stdin).
bool IsThreadRunning(ThreadHandle hThread)
Check whether a thread is still alive.
bool CreateThread(THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
Start a new OS thread.
int32 AtomicDecrement32(int32 volatile &v)
Atomically decrement a 32-bit value.
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.
static std::map< uint32, DrumBeatInfo > * DrumBeatMap
bool SignalThread(ThreadHandle hThread, int32 signal)
Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
bool UnitTest_EventUserDeath()
bool BlockShutdownSignals()
Block the graceful-shutdown signals (SIGINT, SIGTERM, SIGHUP) on the CALLING thread.
bool UnitTest_ProbeProcessWait()
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
int64 AtomicIncrement64(int64 volatile &v)
Atomically increment a 64-bit value.
uint32 GetSharedSystemInstance()
Get the current shared-system instance number.
bool StopDrumBeat(uint32 id)
Stop a running drum beat without destroying it.
bool EnterMutex(const char *name, uint32 ms, bool autocreate=true)
Acquire a named global mutex, creating it on first use.
const char * laststristr(const char *str1, const char *str2)
Case-insensitive laststrstr().
bool ProbeProcessWait(uint32 pid, ProcessWaitInfo &out)
Probe whether a child process (group) appears blocked reading stdin (fd 0).
static Mutex * SharedMemoryMutexMapMutex
#define SharedMemoryFileHandleMapType
bool CreateDrumBeat(uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
Create a periodic timer ("drum beat") that calls func every interval ms.
bool ReapThread(ThreadHandle &hThread)
std::string PrintProgramTrace(uint32 startLine=0, uint32 endLine=0)
Format the current call stack as printable text.
bool UnlinkSharedMemorySegment(char *data)
Remove a segment's name now, whoever created it; every existing mapping stays valid.
uint8 GetProcessStatus(uint32 proc, int &returncode)
Poll a child started with NewProcess().
bool(* DrumBeatFunc)(uint32 id, uint32 count)
Callback invoked on every drum-beat tick.
static Mutex * SharedMemoryEventMapMutex
Semaphore * GetSemaphore(const char *name, bool autocreate=true)
Look up (and optionally create) a named semaphore in the global registry.
bool LeaveMutex(const char *name)
Release a named global mutex previously acquired with EnterMutex().
int RunOSCommand(const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
Run a command synchronously and capture its output.
char * CreateSharedMemorySegment(const char *name, uint64 size, bool force=false)
Create a named shared memory segment and map it into this process.
std::string PrintBitFieldString(const char *bitfield, uint32 bytesize, uint32 size, const char *title)
Like GetBitFieldAsString() but prefixed with title and formatted for printing.
std::string GetBitFieldAsString(const char *bitfield, uint32 bytesize, uint32 size)
Render the first size bits as a '0'/'1' string, for debugging.
uint8 WaitForProcess(uint32 proc, uint32 timeout, int &returncode)
Wait for a child to exit.
uint32 GetLocalProcessID()
Get the OS process id of the current process.
bool EndDrumBeat(uint32 id)
Destroy a drum beat and release its OS timer.
bool DestroySemaphore(const char *name)
Destroy a named global semaphore.
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
bool TerminateThread(ThreadHandle hThread)
Forcibly kill a thread.
bool GetFirstFreeBitLocN(const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
Find the first run of num consecutive 0 bits.
bool StartSignalThread(ShutdownSignalCallback cb)
Start the dedicated signal-handling thread (POSIX only).
bool GetCurrentThreadUniqueID(uint32 &tid)
Get a process-unique id for the calling thread.
int32 AtomicIncrement32(int32 volatile &v)
Atomically increment a 32-bit value.
bool GetDesktopSize(uint32 &width, uint32 &height)
Get the primary desktop resolution.
bool CheckForThreadFinished(ThreadHandle hThread)
Non-blocking check whether a thread has terminated.
void(* ShutdownSignalCallback)(int sig, int count)
Callback invoked (on the dedicated signal thread) when a graceful-shutdown signal is caught.
bool DestroyMutex(const char *name)
Destroy a named global mutex and remove it from the registry.
bool UnitTest_SharedNames()
bool ContinueThread(ThreadHandle hThread)
Resume a thread paused with PauseThread().
bool DisownSharedMemorySegment(char *data)
Give up this process's ownership of a segment's name, so closing it here only unmaps.
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
void CloseProcessTerminal(uint32 proc)
Close the master side (terminal hangup: the child's foreground group gets SIGHUP and any blocked term...
std::list< std::string > GetProgramTrace()
Capture the current call stack.
uint64 hton64(const uint64_t *input)
Convert a 64-bit value from host to network byte order.
static uint16 SharedSystemInstance
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'...
void PrintBinary(void *p, uint32 size, bool asInt, const char *title)
Hex/decimal dump a memory region to stdout for debugging.
static std::map< std::string, Mutex * > * SharedMemoryMutexMap
bool GetFirstFreeBitLoc(const char *bitfield, uint32 bytesize, uint32 &loc)
Find the first 0 (free) bit.
bool SignalEvent(const char *name)
Signal a named global event.
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).
bool GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
bool GetNextLineEnd(const char *str, uint32 size, uint32 &len, uint32 &crSize)
Find the end of the current line.
bool GetBit(uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
Read bit loc.
uint64 ntoh64(const uint64 *input)
Convert a 64-bit value from network to host byte order.
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
bool ReadProcessOutput(uint32 proc, std::string &out, std::string &err)
Read any pending captured stdout/stderr from a child launched with captureOutput=true.
int ToOSPriority(int pri)
Map a CMSDK priority value to the platform's native priority scale.
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap
bool StopSignalThread()
Stop the dedicated signal thread and join it.
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...
bool SetBitN(uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
Set num consecutive bits starting at loc to value.
bool Reset32BitField(char *bitfield, uint32 bytesize)
Zero the whole bitfield, marking every bit as free.
bool StartDrumBeat(uint32 id)
Start (or resume) a previously created drum beat.
bool TextEndsWith(const char *str, const char *end, bool caseSensitive=true)
Test whether str ends with end.
bool UnitTest_Timer()
Self test for the Timer class.
bool SetBit(uint32 loc, bit value, char *bitfield, uint32 bytesize)
Set bit loc to value.
bool GetCurrentThread(ThreadHandle &thread)
Get the handle of the calling thread.
bool RenameConsoleWindow(const char *name, bool prepend=false)
Set the console window title.
bool TryReapThread(ThreadHandle &hThread)
bool UtilsTest()
Run the built-in self test of the utils module.
uint32 Calc32BitFieldSize(uint32 bitsize)
Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
uint32 TextReplaceCharsInPlace(char *str, uint32 size, char find, char replace)
Replace every occurrence of a character, in place.
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
void ClearStaleSharedSegments(uint16 port)
Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.
std::pair< uint32, ProcessData * > Proc_Pair
bool GetOSCPUUsage(double &percentUse)
Get the instantaneous total OS CPU usage.
bool GetCurrentThreadOSID(uint32 &tid)
Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
std::string EncodeHTML(std::string str)
Encode a plain string for safe embedding in HTML (e.g.
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
bool SeedRandomValues(uint32 seedvalue=0)
Seed the pseudo-random generator.
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
static THREAD_RET THREAD_FUNCTION_CALL SignalThreadMain(THREAD_ARG arg)
std::string GetLastOSErrorMessage()
Get the last OS error as human-readable text.
static bool AnyCancelSafeMutexes()
std::vector< std::string > TextListBreakLines(const char *text, uint32 maxLineLength=80)
Word-wrap text into lines no longer than maxLineLength.
int8 CompareFloats(float64 a, float64 b)
Compare two doubles with epsilon tolerance.
uint32 * GetLocalIPAddresses(uint32 &count)
List all local IPv4 addresses.
std::string EncodeJSON(std::string str)
Escape text for embedding as a JSON string value.
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).
uint64 GetProcessMemoryUsage()
Current resident memory usage of this process.
char ** SplitCommandline(const char *cmdline, int &argc)
Split a command line into a malloc'ed argv array.
uint64 ReadRegistryQWORD(const char *key, const char *entry)
Read a 64-bit registry value.
static std::map< uint32, int > * TerminalMasterMap
std::string GetCommandLineArg(uint16 n)
Get the n-th positional command line item.
static void RegisterSharedSegment(void *data, const char *path, uint64 size, bool created)
bool CreateADir(const char *dirname)
Create a directory (parents included where supported).
std::string BytifyRates(double val1, double val2)
Format two byte rates as "x / y" with matching units.
bool CopyAFile(const char *oldfilename, const char *newfilename, bool force=false)
Copy a file.
bool DeleteFilesInADir(const char *dirname, bool force)
Delete all files inside a directory, leaving the directory itself.
uint32 GetCommandLineArgCount()
Number of positional command line items (excluding the executable).
uint16 GetCPUArchitecture()
CPU architecture id.
char OSLocalHostName[1024]
char OSArchitectureName[1024]
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
static uint32 g_shutdownSignalCount
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
static void SetSemaphoreOwnsName(const void *sem, bool owns)
std::string TextUppercase(const char *text)
Convert to upper case (ASCII/current locale).
static std::condition_variable & gLaunchCv
int CRC32(const char *addr, uint32 length, int32 crc=0)
Compute (or continue) a CRC-32 checksum.
static pthread_mutex_t g_cancelSafeSetLock
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
uint64 * GetLocalMACAddresses(uint32 &count)
List all local MAC addresses.
bool WaitForNextEvent(const char *name, uint32 ms, bool autocreate)
static volatile int g_cancelSafeCount
const char * GetSystemArchitecture()
Architecture name string, e.g.
std::string TextTrim(const char *text)
Strip leading and trailing whitespace.
std::string GetCommandLinePath()
Get the directory portion of the executable path.
static bool EventWordWait(void *data, uint32 timeoutMS, bool infinite)
bool HasCommandLineArg(const char *key, std::string &value)
Test for a 'key=value' argument without mutating the argument map.
bool SetSocketBlockingMode(SOCKET s)
Put a socket into blocking mode.
uint32 Ascii2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit decimal integer from a substring.
uint64 GetCPUSpeed()
Nominal CPU clock speed.
wchar_t ** SplitCommandlineW(const char *cmdline, int &argc)
Wide-character variant of SplitCommandline() (for Windows APIs).
std::string TextVectorConcat(std::vector< std::string >, const char *sep, bool allowEmpty=true)
Concatenate vector entries with sep.
bool AppendToAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Append to a file, creating it if missing.
std::string TextIndent(const char *text, const char *indent)
Prefix every line of text with indent.
unsigned char Dec2Char(const char *str)
Parse up to three decimal digits into a byte.
static std::map< void *, SharedSegmentInfo > * SharedSegments
char * GetFileList(const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
List files in a directory matching an extension.
bool GetNextAvailableLocalPort(uint16 lastPort, uint16 &nextPort)
Find the next free TCP port above lastPort.
static std::map< const void *, bool > * g_cancelSafeSet
static std::map< const void *, pid_t > * SharedSemaphoreCreators
static void ResetChildSignalMask()
static std::mutex & gLaunchMx
bool MoveAFile(const char *oldfilename, const char *newfilename, bool force=false)
Move/rename a file.
uint32 StringMultiReplace(std::string &text, std::map< std::string, std::string > &map, bool onlyFirst)
Apply many key→value replacements in one pass.
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
bool IsTextNumeric(const char *ascii, uint32 start=0, uint32 end=0)
Test whether a (sub)string is a valid number.
uint16 GetCPUCount()
Number of logical CPU cores.
char * Uint2Ascii(uint64 value, char *result, uint16 size, uint8 base)
Render an unsigned integer as text in an arbitrary base.
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).
uint64 GetPeakProcessMemoryUsage()
Peak resident memory usage of this process.
bool DeleteCommandline(char **argv, int argc)
Free an argv array produced by SplitCommandline().
uint32 AsciiHex2Uint32(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 32-bit hexadecimal integer from a substring.
bool DeleteRegistryKey(const char *key)
Delete a (leaf) registry key.
bool GetLocalHostname(char *name, uint32 maxSize)
Local hostname into a caller buffer.
std::string TextUnindent(const char *text)
Remove one level of leading indentation from every line.
bool GetSystemOSVersion(uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
Detailed OS version.
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...
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.
bool SetCommandLine(int argc, char *argv[])
Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
uint32 StringSingleReplace(std::string &text, std::string key, std::string value, bool onlyFirst)
Replace occurrences of key with value in text.
uint64 GetSystemMemorySize()
Total physical RAM installed.
uint32 ReadRegistryDWORD(const char *key, const char *entry)
Read a 32-bit registry value.
static bool TerminalMasterFind(uint32 proc, int &fd)
static ShutdownSignalCallback g_shutdownCallback
bool GetLocalMACAddress(uint64 &address)
Get the primary local MAC address.
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
FileDetails GetFileDetails(const char *filename)
Stat a file.
double RandomValue()
Uniform random double in [0,1).
bool GetSocketError(int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
Translate a socket error code into text and classify it.
std::string GetCommandLineExecutableOnly()
Get just the executable filename without path.
static volatile sig_atomic_t g_signalThreadStop
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).
bool RenameRegistryTree(const char *entry, const char *newName)
static bool ContainsPortToken(const char *name, const char *portstr, size_t plen)
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
bool LookupHostname(uint32 address, char *name, uint32 maxSize)
Reverse-resolve an IPv4 address to a hostname.
char * TextSubstringCopy(const char *ascii, uint32 start, uint32 end)
Copy the substring [start,end) into a new NUL-terminated buffer.
static bool EventWordSignal(void *data)
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
static uint32 ClearSegmentsIn(const char *dir, const char *prefix, const char *portstr, size_t plen)
char * Int2Ascii(int64 value, char *result, uint16 size, uint8 base)
Render a signed integer as text in an arbitrary base.
std::string GetLocalHostnameString()
Local hostname as std::string.
static pid_t DoPosixForkExec(PosixLaunchRequest &r)
int32 Ascii2Int32(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 32-bit decimal integer from a substring.
bool DoesAFileExist(const char *filename)
Test whether a regular file exists.
NetworkInterfaces * GetLocalInterfaces(uint32 &count)
Enumerate local network interfaces with address, MAC and names.
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
unsigned char Hex2Char(const char *str)
Parse two hex digits into a byte.
bool DeleteAFile(const char *filename, bool force)
Delete a file.
bool ChangeAFileAttr(const char *filename, bool read, bool write)
Change read/write permission attributes of a file.
static bool MutexIsCancelSafe(const void *m)
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
std::string GetCommandLineExecutable()
Get the full executable path as invoked.
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
std::vector< std::string > TextListSplitLines(const char *text, bool keepEmpty=true, bool autoTrim=false)
Split text into lines, handling both \n and \r\n.
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
std::string GetCurrentDir()
Current working directory.
std::string GetCommandLine()
Get the full original command line as one string.
static bool SharedSegmentIsOwned(void *data)
bool CalcTimeout(struct timespec &timeout, uint32 ms)
static std::mutex gLaunchSerialMx
std::string ReadRegistryString(const char *key, const char *entry)
Read a string registry value.
std::vector< std::string > TextCommandlineSplit(const char *cmdline)
Split a command line into arguments, honouring quoting rules.
static void SharedNamesWait(volatile bool *flag, uint32 ms)
bool DoesADirExist(const char *dirname)
Test whether a directory exists.
bool DeleteRegistryEntry(const char *key, const char *entry)
Delete a single value from a key.
static bool gLauncherStarted
std::string StringFormat(const char *format,...)
printf into a std::string.
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
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.
static __thread int g_savedCancelState
uint64 Ascii2Uint64(const char *ascii, uint32 start=0, uint32 end=0)
Parse an unsigned 64-bit decimal integer from a substring.
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.
const char * GetFileBasename(const char *filename)
Filename portion of a path.
static PosixLaunchRequest * gLaunchReq
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
bool WriteRegistryString(const char *key, const char *entry, const char *value)
Write a string registry value.
static void DrumBeatCallback(union sigval p)
bool GetSystemMemoryUsage(uint64 &totalRAM, uint64 &freeRAM)
Query total and free physical memory.
static THREAD_RET THREAD_FUNCTION_CALL ProcessLauncherRun(THREAD_ARG)
int64 Ascii2Int64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a signed 64-bit decimal integer from a substring.
static pid_t SubmitLaunchRequest(PosixLaunchRequest &req)
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).
bool CopyRegistryTree(const char *entry, const char *newName)
Recursively copy a registry subtree.
static bool g_signalThreadRunning
int(* LibraryFunction)()
Signature of a plain function exported from a dynamically loaded library.
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).
std::string DecodeJSON(std::string str)
Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
const char * GetComputerName()
Get this machine's hostname.
std::string GetFilePath(const char *filename)
Directory portion of a path.
static bool TakeSemaphoreOwnsName(const void *sem)
static void SignalShutdownSigset(sigset_t *set)
const char * GetSystemOSName()
OS name string, e.g.
std::string BytifySizes(double val1, double val2)
Format two byte counts as "x / y" with matching units.
bool IsLocalIPAddress(const char *addr)
Test whether a textual address refers to this machine (loopback or a local interface).
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
std::string TextJoin(std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
Join vector elements with split.
static pthread_t g_signalThread
int64 RandomInt(int64 from=0, int64 to=100)
Uniform random integer in [from,to].
std::string BytifyRate(double val)
Format a byte rate, e.g.
CleanShutdown CleanShutdownInstance
struct dirent * readdir(DIR *)
static void InitSharedMutexObject(pthread_mutex_t *m)
static void SharedLockWakeOne(volatile uint32_t *addr)
static bool Test_ChildSignalMask()
DIR * opendir(const char *)
bool ClearUtilsMaps()
Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps).
static bool Test_MutexOwnerDeath()
static bool Test_ProbeProcessWait()
uint32 CleanShutdownInstanceCount
static bool Test_SharedNames()
static void SharedLockWait(volatile uint32_t *addr, uint32_t value, uint32_t timeoutUS)
void Register_Utils_Tests()
uint32 GetDataTypeID(const char *typeName)
Inverse of GetDataTypeName(): look up the numeric datatype id for a type name.
static void SharedLockWakeAll(volatile uint32_t *addr)
static bool Test_SemaphoreUserDeath()
static bool Test_EventUserDeath()
std::string GetDataTypeName(uint32 datatype)
Translate a CMSDK datatype id (e.g.
Wire/storage layout of one log record: fixed header immediately followed by the message text.
std::string toJSON()
Serialize the entry (header fields + text) as a JSON object string.
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
const char * getText(uint32 &len)
Access the text payload stored after the header.
std::string toXML()
Serialize the entry as an XML fragment.
Bookkeeping record for one periodic "drum beat" timer.
Existence, type, permission and timestamp information for one file, as returned by GetFileDetails().
Description of one local network interface (IPv4 address, MAC and names).
char friendlyName[MAXKEYNAMELEN+1]
char name[MAXKEYNAMELEN+1]
const std::map< std::string, std::string > * env
POSIX capture bookkeeping for children started via NewProcessEx(captureOutput).
int errFD
Parent read-end of the child's stderr (-1 = not captured).
int outFD
Parent read-end of the child's stdout (-1 = not captured).
Snapshot from ProbeProcessWait(): is the child (group) alive, is it blocked reading stdin,...
uint64 cpuTimeMs
cumulative user+sys CPU across the process group, in ms
bool waitingStdin
blocked reading fd 0 (exact on Linux; best-effort composite elsewhere)
bool alive
process (or group) still exists
bool waitExact
true only when the OS reported the exact blocking syscall (Linux /proc/<pid>/syscall)
volatile uint32_t waiters
One scheduled entry inside a Timer: id, active window and platform timer handle.
A single timer expiry: which timer fired and when.