loslib.c 12 KB

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