ref: 12c9d2fc728b51aa1eb9a70d0d331eb9464912d9
dir: /src/posix/sys.c/
#include "sl.h"
#include "timefuncs.h"
#include <sys/mman.h>
static usize pagesize = 4096;
#define PAGEALIGNED(x) (((x) + pagesize-1) & ~(pagesize-1))
void *
sl_segalloc(usize sz)
{
sz = PAGEALIGNED(sz);
void *s = mmap(nil, sz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
if(s == (void*)-1)
s = nil;
return s;
}
void
sl_segfree(void *s, usize sz)
{
if(s == nil)
return;
sz = PAGEALIGNED(sz);
if(munmap(s, sz) != 0)
abort();
}
void
sl_segused(void *s, usize sz, usize used)
{
sz = PAGEALIGNED(sz);
used = PAGEALIGNED(used);
// it's fine if this fails
posix_madvise((u8int*)s+used, sz-used, POSIX_MADV_DONTNEED);
}
double
sec_realtime(void)
{
struct timespec now;
if(clock_gettime(CLOCK_REALTIME, &now) != 0)
return 0;
return (double)now.tv_sec + (double)now.tv_nsec/1.0e9;
}
u64int
nanosec_monotonic(void)
{
static s64int z;
struct timespec now;
if(clock_gettime(CLOCK_MONOTONIC, &now) != 0)
return 0;
if(z == 0){
z = now.tv_sec*1000000000LL + now.tv_nsec;
return 0;
}
return now.tv_sec*1000000000LL + now.tv_nsec - z;
}
void
timestring(double s, char *buf, int sz)
{
time_t tme = (time_t)s;
struct tm tm;
*buf = 0;
if(localtime_r(&tme, &tm) != nil)
strftime(buf, sz, "%a %b %e %H:%M:%S %Y", &tm);
}
double
parsetime(const char *s)
{
char *res;
time_t t;
struct tm tm;
res = strptime(s, "%c", &tm);
if(res != nil){
/* Not set by strptime(); tells mktime() to determine
* whether daylight saving time is in effect
*/
tm.tm_isdst = -1;
t = mktime(&tm);
if(t == (time_t)-1)
return -1;
return (double)t;
}
return -1;
}
void
sleep_ms(int ms)
{
if(ms != 0){
struct timeval timeout;
timeout.tv_sec = ms/1000;
timeout.tv_usec = (ms % 1000) * 1000;
select(0, nil, nil, nil, &timeout);
}
}
static const u8int boot[] = {
#include "sl.boot.h"
};
char *os_version;
#include <sys/utsname.h>
int
main(int argc, char **argv)
{
setlocale(LC_NUMERIC, "C");
struct utsname u;
os_version = strdup(uname(&u) == 0 ? u.release : "");
long p = sysconf(_SC_PAGE_SIZE);
if(p > 0)
pagesize = p;
slmain(boot, sizeof(boot), argc, argv);
}