factor/native/misc.c

98 lines
1.6 KiB
C
Raw Normal View History

2004-08-04 03:12:55 -04:00
#include "factor.h"
void *safe_malloc(size_t size)
{
void *ptr = malloc(size);
if(ptr == 0)
fatal_error("malloc() failed", 0);
return ptr;
}
2004-08-04 03:12:55 -04:00
void primitive_exit(void)
{
exit(to_fixnum(dpop()));
2004-08-04 03:12:55 -04:00
}
void primitive_os_env(void)
{
char *name, *value;
2005-06-16 18:50:49 -04:00
maybe_gc(0);
name = pop_c_string();
value = getenv(name);
2004-08-04 03:12:55 -04:00
if(value == NULL)
2004-09-19 17:39:28 -04:00
dpush(F);
2004-08-04 03:12:55 -04:00
else
2004-09-19 17:39:28 -04:00
box_c_string(getenv(name));
2004-08-04 03:12:55 -04:00
}
void primitive_eq(void)
{
2004-11-08 22:36:51 -05:00
box_boolean(dpop() == dpop());
2004-08-04 03:12:55 -04:00
}
2004-12-10 21:39:45 -05:00
#ifdef WIN32
2005-03-21 20:59:30 -05:00
s64 current_millis(void)
2004-12-10 21:39:45 -05:00
{
FILETIME t;
GetSystemTimeAsFileTime(&t);
2005-03-21 20:59:30 -05:00
return (((s64)t.dwLowDateTime | (s64)t.dwHighDateTime<<32) - EPOCH_OFFSET)
2004-12-11 15:02:34 -05:00
/ 10000;
2004-12-10 21:39:45 -05:00
}
#else
2005-03-21 20:59:30 -05:00
s64 current_millis(void)
2004-08-04 03:12:55 -04:00
{
struct timeval t;
gettimeofday(&t,NULL);
2005-03-21 20:59:30 -05:00
return (s64)t.tv_sec * 1000 + t.tv_usec/1000;
2004-11-22 19:15:14 -05:00
}
2004-12-10 21:39:45 -05:00
#endif
2004-11-22 19:15:14 -05:00
void primitive_millis(void)
{
2005-06-16 18:50:49 -04:00
maybe_gc(0);
dpush(tag_bignum(s48_long_long_to_bignum(current_millis())));
2004-08-04 03:12:55 -04:00
}
2004-12-17 12:22:16 -05:00
#ifdef WIN32
// frees memory allocated by win32 api calls
char *buffer_to_c_string(char *buffer)
{
int capacity = strlen(buffer);
F_STRING *_c_str = allot_string(capacity / CHARS + 1);
BYTE *c_str = (BYTE*)(_c_str + 1);
2005-10-05 00:24:19 -04:00
strcpy(c_str, buffer);
LocalFree(buffer);
return (char*)c_str;
}
F_STRING *get_error_message()
{
DWORD id = GetLastError();
return from_c_string(error_message(id));
}
char *error_message(DWORD id)
2004-12-17 12:22:16 -05:00
{
char *buffer;
int index;
2004-12-17 12:22:16 -05:00
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
id,
2004-12-17 12:22:16 -05:00
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &buffer,
0, NULL);
// strip whitespace from end
index = strlen(buffer) - 1;
while(index >= 0 && isspace(buffer[index]))
buffer[index--] = 0;
return buffer_to_c_string(buffer);
2004-12-17 12:22:16 -05:00
}
#endif