loslib.c (11851B)
1 /* 2 ** $Id: loslib.c $ 3 ** Standard Operating System library 4 ** See Copyright Notice in lua.h 5 */ 6 7 #define loslib_c 8 #define LUA_LIB 9 10 #include "lprefix.h" 11 12 13 #include <errno.h> 14 #include <locale.h> 15 #include <stdlib.h> 16 #include <string.h> 17 #include <time.h> 18 19 #include "lua.h" 20 21 #include "lauxlib.h" 22 #include "lualib.h" 23 #include "llimits.h" 24 25 26 /* 27 ** {================================================================== 28 ** List of valid conversion specifiers for the 'strftime' function; 29 ** options are grouped by length; group of length 2 start with '||'. 30 ** =================================================================== 31 */ 32 #if !defined(LUA_STRFTIMEOPTIONS) /* { */ 33 34 #if defined(LUA_USE_WINDOWS) 35 #define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYzZ%" \ 36 "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */ 37 #elif defined(LUA_USE_C89) /* ANSI C 89 (only 1-char options) */ 38 #define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYZ%" 39 #else /* C99 specification */ 40 #define LUA_STRFTIMEOPTIONS "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ 41 "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ 42 #endif 43 44 #endif /* } */ 45 /* }================================================================== */ 46 47 48 /* 49 ** {================================================================== 50 ** Configuration for time-related stuff 51 ** =================================================================== 52 */ 53 54 /* 55 ** type to represent time_t in Lua 56 */ 57 #if !defined(LUA_NUMTIME) /* { */ 58 59 #define l_timet lua_Integer 60 #define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) 61 #define l_gettime(L,arg) luaL_checkinteger(L, arg) 62 63 #else /* }{ */ 64 65 #define l_timet lua_Number 66 #define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t)) 67 #define l_gettime(L,arg) luaL_checknumber(L, arg) 68 69 #endif /* } */ 70 71 72 #if !defined(l_gmtime) /* { */ 73 /* 74 ** By default, Lua uses gmtime/localtime, except when POSIX is available, 75 ** where it uses gmtime_r/localtime_r 76 */ 77 78 #if defined(LUA_USE_POSIX) /* { */ 79 80 #define l_gmtime(t,r) gmtime_r(t,r) 81 #define l_localtime(t,r) localtime_r(t,r) 82 83 #else /* }{ */ 84 85 /* ISO C definitions */ 86 #define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t)) 87 #define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t)) 88 89 #endif /* } */ 90 91 #endif /* } */ 92 93 /* }================================================================== */ 94 95 96 /* 97 ** {================================================================== 98 ** Configuration for 'tmpnam': 99 ** By default, Lua uses tmpnam except when POSIX is available, where 100 ** it uses mkstemp. 101 ** =================================================================== 102 */ 103 #if !defined(lua_tmpnam) /* { */ 104 105 #if defined(LUA_USE_POSIX) /* { */ 106 107 #include <unistd.h> 108 109 #define LUA_TMPNAMBUFSIZE 32 110 111 #if !defined(LUA_TMPNAMTEMPLATE) 112 #define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX" 113 #endif 114 115 #define lua_tmpnam(b,e) { \ 116 strcpy(b, LUA_TMPNAMTEMPLATE); \ 117 e = mkstemp(b); \ 118 if (e != -1) close(e); \ 119 e = (e == -1); } 120 121 #else /* }{ */ 122 123 /* ISO C definitions */ 124 #define LUA_TMPNAMBUFSIZE L_tmpnam 125 #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } 126 127 #endif /* } */ 128 129 #endif /* } */ 130 /* }================================================================== */ 131 132 133 #if !defined(l_system) 134 #if defined(LUA_USE_IOS) 135 /* Despite claiming to be ISO C, iOS does not implement 'system'. */ 136 #define l_system(cmd) ((cmd) == NULL ? 0 : -1) 137 #else 138 #define l_system(cmd) system(cmd) /* default definition */ 139 #endif 140 #endif 141 142 143 static int os_execute (lua_State *L) { 144 const char *cmd = luaL_optstring(L, 1, NULL); 145 int stat; 146 errno = 0; 147 stat = l_system(cmd); 148 if (cmd != NULL) 149 return luaL_execresult(L, stat); 150 else { 151 lua_pushboolean(L, stat); /* true if there is a shell */ 152 return 1; 153 } 154 } 155 156 157 static int os_remove (lua_State *L) { 158 const char *filename = luaL_checkstring(L, 1); 159 errno = 0; 160 return luaL_fileresult(L, remove(filename) == 0, filename); 161 } 162 163 164 static int os_rename (lua_State *L) { 165 const char *fromname = luaL_checkstring(L, 1); 166 const char *toname = luaL_checkstring(L, 2); 167 errno = 0; 168 return luaL_fileresult(L, rename(fromname, toname) == 0, NULL); 169 } 170 171 172 static int os_tmpname (lua_State *L) { 173 char buff[LUA_TMPNAMBUFSIZE]; 174 int err; 175 lua_tmpnam(buff, err); 176 if (l_unlikely(err)) 177 return luaL_error(L, "unable to generate a unique filename"); 178 lua_pushstring(L, buff); 179 return 1; 180 } 181 182 183 static int os_getenv (lua_State *L) { 184 lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ 185 return 1; 186 } 187 188 189 static int os_clock (lua_State *L) { 190 lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); 191 return 1; 192 } 193 194 195 /* 196 ** {====================================================== 197 ** Time/Date operations 198 ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, 199 ** wday=%w+1, yday=%j, isdst=? } 200 ** ======================================================= 201 */ 202 203 /* 204 ** About the overflow check: an overflow cannot occur when time 205 ** is represented by a lua_Integer, because either lua_Integer is 206 ** large enough to represent all int fields or it is not large enough 207 ** to represent a time that cause a field to overflow. However, if 208 ** times are represented as doubles and lua_Integer is int, then the 209 ** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900 210 ** to compute the year. 211 */ 212 static void setfield (lua_State *L, const char *key, int value, int delta) { 213 #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX) 214 if (l_unlikely(value > LUA_MAXINTEGER - delta)) 215 luaL_error(L, "field '%s' is out-of-bound", key); 216 #endif 217 lua_pushinteger(L, (lua_Integer)value + delta); 218 lua_setfield(L, -2, key); 219 } 220 221 222 static void setboolfield (lua_State *L, const char *key, int value) { 223 if (value < 0) /* undefined? */ 224 return; /* does not set field */ 225 lua_pushboolean(L, value); 226 lua_setfield(L, -2, key); 227 } 228 229 230 /* 231 ** Set all fields from structure 'tm' in the table on top of the stack 232 */ 233 static void setallfields (lua_State *L, struct tm *stm) { 234 setfield(L, "year", stm->tm_year, 1900); 235 setfield(L, "month", stm->tm_mon, 1); 236 setfield(L, "day", stm->tm_mday, 0); 237 setfield(L, "hour", stm->tm_hour, 0); 238 setfield(L, "min", stm->tm_min, 0); 239 setfield(L, "sec", stm->tm_sec, 0); 240 setfield(L, "yday", stm->tm_yday, 1); 241 setfield(L, "wday", stm->tm_wday, 1); 242 setboolfield(L, "isdst", stm->tm_isdst); 243 } 244 245 246 static int getboolfield (lua_State *L, const char *key) { 247 int res; 248 res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1); 249 lua_pop(L, 1); 250 return res; 251 } 252 253 254 static int getfield (lua_State *L, const char *key, int d, int delta) { 255 int isnum; 256 int t = lua_getfield(L, -1, key); /* get field and its type */ 257 lua_Integer res = lua_tointegerx(L, -1, &isnum); 258 if (!isnum) { /* field is not an integer? */ 259 if (l_unlikely(t != LUA_TNIL)) /* some other value? */ 260 return luaL_error(L, "field '%s' is not an integer", key); 261 else if (l_unlikely(d < 0)) /* absent field; no default? */ 262 return luaL_error(L, "field '%s' missing in date table", key); 263 res = d; 264 } 265 else { 266 if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res)) 267 return luaL_error(L, "field '%s' is out-of-bound", key); 268 res -= delta; 269 } 270 lua_pop(L, 1); 271 return (int)res; 272 } 273 274 275 static const char *checkoption (lua_State *L, const char *conv, 276 ptrdiff_t convlen, char *buff) { 277 const char *option = LUA_STRFTIMEOPTIONS; 278 unsigned oplen = 1; /* length of options being checked */ 279 for (; *option != '\0' && oplen <= convlen; option += oplen) { 280 if (*option == '|') /* next block? */ 281 oplen++; /* will check options with next length (+1) */ 282 else if (memcmp(conv, option, oplen) == 0) { /* match? */ 283 memcpy(buff, conv, oplen); /* copy valid option to buffer */ 284 buff[oplen] = '\0'; 285 return conv + oplen; /* return next item */ 286 } 287 } 288 luaL_argerror(L, 1, 289 lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv)); 290 return conv; /* to avoid warnings */ 291 } 292 293 294 static time_t l_checktime (lua_State *L, int arg) { 295 l_timet t = l_gettime(L, arg); 296 luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); 297 return (time_t)t; 298 } 299 300 301 /* maximum size for an individual 'strftime' item */ 302 #define SIZETIMEFMT 250 303 304 305 static int os_date (lua_State *L) { 306 size_t slen; 307 const char *s = luaL_optlstring(L, 1, "%c", &slen); 308 time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); 309 const char *se = s + slen; /* 's' end */ 310 struct tm tmr, *stm; 311 if (*s == '!') { /* UTC? */ 312 stm = l_gmtime(&t, &tmr); 313 s++; /* skip '!' */ 314 } 315 else 316 stm = l_localtime(&t, &tmr); 317 if (stm == NULL) /* invalid date? */ 318 return luaL_error(L, 319 "date result cannot be represented in this installation"); 320 if (strcmp(s, "*t") == 0) { 321 lua_createtable(L, 0, 9); /* 9 = number of fields */ 322 setallfields(L, stm); 323 } 324 else { 325 char cc[4]; /* buffer for individual conversion specifiers */ 326 luaL_Buffer b; 327 cc[0] = '%'; 328 luaL_buffinit(L, &b); 329 while (s < se) { 330 if (*s != '%') /* not a conversion specifier? */ 331 luaL_addchar(&b, *s++); 332 else { 333 size_t reslen; 334 char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); 335 s++; /* skip '%' */ 336 s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ 337 reslen = strftime(buff, SIZETIMEFMT, cc, stm); 338 luaL_addsize(&b, reslen); 339 } 340 } 341 luaL_pushresult(&b); 342 } 343 return 1; 344 } 345 346 347 static int os_time (lua_State *L) { 348 time_t t; 349 if (lua_isnoneornil(L, 1)) /* called without args? */ 350 t = time(NULL); /* get current time */ 351 else { 352 struct tm ts; 353 luaL_checktype(L, 1, LUA_TTABLE); 354 lua_settop(L, 1); /* make sure table is at the top */ 355 ts.tm_year = getfield(L, "year", -1, 1900); 356 ts.tm_mon = getfield(L, "month", -1, 1); 357 ts.tm_mday = getfield(L, "day", -1, 0); 358 ts.tm_hour = getfield(L, "hour", 12, 0); 359 ts.tm_min = getfield(L, "min", 0, 0); 360 ts.tm_sec = getfield(L, "sec", 0, 0); 361 ts.tm_isdst = getboolfield(L, "isdst"); 362 t = mktime(&ts); 363 setallfields(L, &ts); /* update fields with normalized values */ 364 } 365 if (t != (time_t)(l_timet)t || t == (time_t)(-1)) 366 return luaL_error(L, 367 "time result cannot be represented in this installation"); 368 l_pushtime(L, t); 369 return 1; 370 } 371 372 373 static int os_difftime (lua_State *L) { 374 time_t t1 = l_checktime(L, 1); 375 time_t t2 = l_checktime(L, 2); 376 lua_pushnumber(L, (lua_Number)difftime(t1, t2)); 377 return 1; 378 } 379 380 /* }====================================================== */ 381 382 383 static int os_setlocale (lua_State *L) { 384 static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, 385 LC_NUMERIC, LC_TIME}; 386 static const char *const catnames[] = {"all", "collate", "ctype", "monetary", 387 "numeric", "time", NULL}; 388 const char *l = luaL_optstring(L, 1, NULL); 389 int op = luaL_checkoption(L, 2, "all", catnames); 390 lua_pushstring(L, setlocale(cat[op], l)); 391 return 1; 392 } 393 394 395 static int os_exit (lua_State *L) { 396 int status; 397 if (lua_isboolean(L, 1)) 398 status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); 399 else 400 status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); 401 if (lua_toboolean(L, 2)) 402 lua_close(L); 403 if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ 404 return 0; 405 } 406 407 408 static const luaL_Reg syslib[] = { 409 {"clock", os_clock}, 410 {"date", os_date}, 411 {"difftime", os_difftime}, 412 {"execute", os_execute}, 413 {"exit", os_exit}, 414 {"getenv", os_getenv}, 415 {"remove", os_remove}, 416 {"rename", os_rename}, 417 {"setlocale", os_setlocale}, 418 {"time", os_time}, 419 {"tmpname", os_tmpname}, 420 {NULL, NULL} 421 }; 422 423 /* }====================================================== */ 424 425 426 427 LUAMOD_API int luaopen_os (lua_State *L) { 428 luaL_newlib(L, syslib); 429 return 1; 430 } 431