X-Git-Url: https://wimlib.net/git/?p=wimlib;a=blobdiff_plain;f=src%2Futil.c;h=928a0368668ce06bd4a3236018c707148ffe4068;hp=242280961d634fbcee28def2272df4ef64dec741;hb=f3c7a16f6cdb32b04ead31581d5461e3f80ed044;hpb=3de1ec66f778edda19865482d685bc6f4e17faf7 diff --git a/src/util.c b/src/util.c index 24228096..928a0368 100644 --- a/src/util.c +++ b/src/util.c @@ -23,12 +23,19 @@ # include "config.h" #endif +#include #include #include #include +#ifdef HAVE_SYS_SYSCTL_H +# include +# include +#endif +#include #include "wimlib.h" #include "wimlib/assert.h" +#include "wimlib/error.h" #include "wimlib/timestamp.h" #include "wimlib/util.h" #include "wimlib/xml.h" @@ -84,28 +91,14 @@ wimlib_calloc(size_t nmemb, size_t size) char * wimlib_strdup(const char *str) { - size_t size; - char *p; - - size = strlen(str); - p = MALLOC(size + 1); - if (p) - p = memcpy(p, str, size + 1); - return p; + return memdup(str, strlen(str) + 1); } #ifdef __WIN32__ wchar_t * wimlib_wcsdup(const wchar_t *str) { - size_t size; - wchar_t *p; - - size = wcslen(str); - p = MALLOC((size + 1) * sizeof(wchar_t)); - if (p) - p = wmemcpy(p, str, size + 1); - return p; + return memdup(str, (wcslen(str) + 1) * sizeof(wchar_t)); } #endif @@ -205,3 +198,41 @@ randomize_byte_array(u8 *p, size_t n) while (n--) *p++ = rand(); } + +#ifndef __WIN32__ +unsigned +get_available_cpus(void) +{ + long n = sysconf(_SC_NPROCESSORS_ONLN); + if (n < 1 || n >= UINT_MAX) { + WARNING("Failed to determine number of processors; assuming 1."); + return 1; + } + return n; +} +#endif /* !__WIN32__ */ + +#ifndef __WIN32__ +u64 +get_available_memory(void) +{ +#if defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) + long page_size = sysconf(_SC_PAGESIZE); + long num_pages = sysconf(_SC_PHYS_PAGES); + if (page_size <= 0 || num_pages <= 0) + goto default_size; + return ((u64)page_size * (u64)num_pages); +#else + int mib[2] = {CTL_HW, HW_MEMSIZE}; + u64 memsize; + size_t len = sizeof(memsize); + if (sysctl(mib, ARRAY_LEN(mib), &memsize, &len, NULL, 0) < 0 || len != 8) + goto default_size; + return memsize; +#endif + +default_size: + WARNING("Failed to determine available memory; assuming 1 GiB"); + return (u64)1 << 30; +} +#endif /* !__WIN32__ */