Coverage Report

Created: 2025-10-10 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/testdir/build/lua-master/source/liolib.c
Line
Count
Source
1
/*
2
** $Id: liolib.c $
3
** Standard I/O (and system) library
4
** See Copyright Notice in lua.h
5
*/
6
7
#define liolib_c
8
#define LUA_LIB
9
10
#include "lprefix.h"
11
12
13
#include <ctype.h>
14
#include <errno.h>
15
#include <locale.h>
16
#include <stdio.h>
17
#include <stdlib.h>
18
#include <string.h>
19
20
#include "lua.h"
21
22
#include "lauxlib.h"
23
#include "lualib.h"
24
#include "llimits.h"
25
26
27
/*
28
** Change this macro to accept other modes for 'fopen' besides
29
** the standard ones.
30
*/
31
#if !defined(l_checkmode)
32
33
/* accepted extensions to 'mode' in 'fopen' */
34
#if !defined(L_MODEEXT)
35
622k
#define L_MODEEXT "b"
36
#endif
37
38
/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
39
622k
static int l_checkmode (const char *mode) {
40
622k
  return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
41
622k
         (*mode != '+' || ((void)(++mode), 1)) &&  /* skip if char is '+' */
42
622k
         (strspn(mode, L_MODEEXT) == strlen(mode)));  /* check extensions */
43
622k
}
44
45
#endif
46
47
/*
48
** {======================================================
49
** l_popen spawns a new process connected to the current
50
** one through the file streams.
51
** =======================================================
52
*/
53
54
#if !defined(l_popen)   /* { */
55
56
#if defined(LUA_USE_POSIX)  /* { */
57
58
9.34k
#define l_popen(L,c,m)    (fflush(NULL), popen(c,m))
59
9.34k
#define l_pclose(L,file)  (pclose(file))
60
61
#elif defined(LUA_USE_WINDOWS)  /* }{ */
62
63
#define l_popen(L,c,m)    (_popen(c,m))
64
#define l_pclose(L,file)  (_pclose(file))
65
66
#if !defined(l_checkmodep)
67
/* Windows accepts "[rw][bt]?" as valid modes */
68
#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
69
  (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
70
#endif
71
72
#else       /* }{ */
73
74
/* ISO C definitions */
75
#define l_popen(L,c,m)  \
76
    ((void)c, (void)m, \
77
    luaL_error(L, "'popen' not supported"), \
78
    (FILE*)0)
79
#define l_pclose(L,file)    ((void)L, (void)file, -1)
80
81
#endif        /* } */
82
83
#endif        /* } */
84
85
86
#if !defined(l_checkmodep)
87
/* By default, Lua accepts only "r" or "w" as valid modes */
88
#define l_checkmodep(m)        ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
89
#endif
90
91
/* }====================================================== */
92
93
94
#if !defined(l_getc)    /* { */
95
96
#if defined(LUA_USE_POSIX)
97
14.7M
#define l_getc(f)   getc_unlocked(f)
98
141k
#define l_lockfile(f)   flockfile(f)
99
141k
#define l_unlockfile(f)   funlockfile(f)
100
#else
101
#define l_getc(f)   getc(f)
102
#define l_lockfile(f)   ((void)0)
103
#define l_unlockfile(f)   ((void)0)
104
#endif
105
106
#endif        /* } */
107
108
109
/*
110
** {======================================================
111
** l_fseek: configuration for longer offsets
112
** =======================================================
113
*/
114
115
#if !defined(l_fseek)   /* { */
116
117
#if defined(LUA_USE_POSIX) || defined(LUA_USE_OFF_T)  /* { */
118
119
#include <sys/types.h>
120
121
16.5k
#define l_fseek(f,o,w)    fseeko(f,o,w)
122
16.2k
#define l_ftell(f)    ftello(f)
123
16.5k
#define l_seeknum   off_t
124
125
#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
126
   && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
127
128
/* Windows (but not DDK) and Visual C++ 2005 or higher */
129
#define l_fseek(f,o,w)    _fseeki64(f,o,w)
130
#define l_ftell(f)    _ftelli64(f)
131
#define l_seeknum   __int64
132
133
#else       /* }{ */
134
135
/* ISO C definitions */
136
#define l_fseek(f,o,w)    fseek(f,o,w)
137
#define l_ftell(f)    ftell(f)
138
#define l_seeknum   long
139
140
#endif        /* } */
141
142
#endif        /* } */
143
144
/* }====================================================== */
145
146
147
148
10.2M
#define IO_PREFIX "_IO_"
149
416
#define IOPREF_LEN  (sizeof(IO_PREFIX)/sizeof(char) - 1)
150
326k
#define IO_INPUT  (IO_PREFIX "input")
151
9.97M
#define IO_OUTPUT (IO_PREFIX "output")
152
153
154
typedef luaL_Stream LStream;
155
156
157
4.42M
#define tolstream(L)  ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
158
159
3.04M
#define isclosed(p) ((p)->closef == NULL)
160
161
162
131k
static int io_type (lua_State *L) {
163
131k
  LStream *p;
164
131k
  luaL_checkany(L, 1);
165
131k
  p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
166
131k
  if (p == NULL)
167
117k
    luaL_pushfail(L);  /* not a file */
168
14.2k
  else if (isclosed(p))
169
98
    lua_pushliteral(L, "closed file");
170
14.1k
  else
171
14.1k
    lua_pushliteral(L, "file");
172
131k
  return 1;
173
131k
}
174
175
176
7.38k
static int f_tostring (lua_State *L) {
177
7.38k
  LStream *p = tolstream(L);
178
7.38k
  if (isclosed(p))
179
137
    lua_pushliteral(L, "file (closed)");
180
7.24k
  else
181
7.24k
    lua_pushfstring(L, "file (%p)", p->f);
182
7.38k
  return 1;
183
7.38k
}
184
185
186
391k
static FILE *tofile (lua_State *L) {
187
391k
  LStream *p = tolstream(L);
188
391k
  if (l_unlikely(isclosed(p)))
189
1.77k
    luaL_error(L, "attempt to use a closed file");
190
391k
  lua_assert(p->f);
191
391k
  return p->f;
192
391k
}
193
194
195
/*
196
** When creating file handles, always creates a 'closed' file handle
197
** before opening the actual file; so, if there is a memory error, the
198
** handle is in a consistent state.
199
*/
200
1.41M
static LStream *newprefile (lua_State *L) {
201
1.41M
  LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
202
1.41M
  p->closef = NULL;  /* mark file handle as 'closed' */
203
1.41M
  luaL_setmetatable(L, LUA_FILEHANDLE);
204
1.41M
  return p;
205
1.41M
}
206
207
208
/*
209
** Calls the 'close' function from a file handle. The 'volatile' avoids
210
** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
211
** 32 bits).
212
*/
213
1.29M
static int aux_close (lua_State *L) {
214
1.29M
  LStream *p = tolstream(L);
215
1.29M
  volatile lua_CFunction cf = p->closef;
216
1.29M
  p->closef = NULL;  /* mark stream as closed */
217
1.29M
  return (*cf)(L);  /* close it */
218
1.29M
}
219
220
221
273k
static int f_close (lua_State *L) {
222
273k
  tofile(L);  /* make sure argument is an open stream */
223
273k
  return aux_close(L);
224
273k
}
225
226
227
272k
static int io_close (lua_State *L) {
228
272k
  if (lua_isnone(L, 1))  /* no argument? */
229
269k
    lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use default output */
230
272k
  return f_close(L);
231
272k
}
232
233
234
1.43M
static int f_gc (lua_State *L) {
235
1.43M
  LStream *p = tolstream(L);
236
1.43M
  if (!isclosed(p) && p->f != NULL)
237
998k
    aux_close(L);  /* ignore closed and incompletely open files */
238
1.43M
  return 0;
239
1.43M
}
240
241
242
/*
243
** function to close regular files
244
*/
245
941k
static int io_fclose (lua_State *L) {
246
941k
  LStream *p = tolstream(L);
247
941k
  errno = 0;
248
941k
  return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
249
941k
}
250
251
252
1.32M
static LStream *newfile (lua_State *L) {
253
1.32M
  LStream *p = newprefile(L);
254
1.32M
  p->f = NULL;
255
1.32M
  p->closef = &io_fclose;
256
1.32M
  return p;
257
1.32M
}
258
259
260
701k
static void opencheck (lua_State *L, const char *fname, const char *mode) {
261
701k
  LStream *p = newfile(L);
262
701k
  p->f = fopen(fname, mode);
263
701k
  if (l_unlikely(p->f == NULL))
264
1.23k
    luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
265
701k
}
266
267
268
622k
static int io_open (lua_State *L) {
269
622k
  const char *filename = luaL_checkstring(L, 1);
270
622k
  const char *mode = luaL_optstring(L, 2, "r");
271
622k
  LStream *p = newfile(L);
272
622k
  const char *md = mode;  /* to traverse/check mode */
273
622k
  luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
274
622k
  errno = 0;
275
622k
  p->f = fopen(filename, mode);
276
622k
  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
277
622k
}
278
279
280
/*
281
** function to close 'popen' files
282
*/
283
9.34k
static int io_pclose (lua_State *L) {
284
9.34k
  LStream *p = tolstream(L);
285
9.34k
  errno = 0;
286
9.34k
  return luaL_execresult(L, l_pclose(L, p->f));
287
9.34k
}
288
289
290
9.34k
static int io_popen (lua_State *L) {
291
9.34k
  const char *filename = luaL_checkstring(L, 1);
292
9.34k
  const char *mode = luaL_optstring(L, 2, "r");
293
9.34k
  LStream *p = newprefile(L);
294
9.34k
  luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
295
9.34k
  errno = 0;
296
9.34k
  p->f = l_popen(L, filename, mode);
297
9.34k
  p->closef = &io_pclose;
298
9.34k
  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
299
9.34k
}
300
301
302
4.46k
static int io_tmpfile (lua_State *L) {
303
4.46k
  LStream *p = newfile(L);
304
4.46k
  errno = 0;
305
4.46k
  p->f = tmpfile();
306
4.46k
  return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
307
4.46k
}
308
309
310
9.36M
static FILE *getiofile (lua_State *L, const char *findex) {
311
9.36M
  LStream *p;
312
9.36M
  lua_getfield(L, LUA_REGISTRYINDEX, findex);
313
9.36M
  p = (LStream *)lua_touserdata(L, -1);
314
9.36M
  if (l_unlikely(isclosed(p)))
315
416
    luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
316
9.36M
  return p->f;
317
9.36M
}
318
319
320
568k
static int g_iofile (lua_State *L, const char *f, const char *mode) {
321
568k
  if (!lua_isnoneornil(L, 1)) {
322
510k
    const char *filename = lua_tostring(L, 1);
323
510k
    if (filename)
324
458k
      opencheck(L, filename, mode);
325
52.2k
    else {
326
52.2k
      tofile(L);  /* check that it's a valid file handle */
327
52.2k
      lua_pushvalue(L, 1);
328
52.2k
    }
329
510k
    lua_setfield(L, LUA_REGISTRYINDEX, f);
330
510k
  }
331
  /* return current value */
332
568k
  lua_getfield(L, LUA_REGISTRYINDEX, f);
333
568k
  return 1;
334
568k
}
335
336
337
254k
static int io_input (lua_State *L) {
338
254k
  return g_iofile(L, IO_INPUT, "r");
339
254k
}
340
341
342
313k
static int io_output (lua_State *L) {
343
313k
  return g_iofile(L, IO_OUTPUT, "w");
344
313k
}
345
346
347
static int io_readline (lua_State *L);
348
349
350
/*
351
** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
352
** in the limit for upvalues of a closure)
353
*/
354
#define MAXARGLINE  250
355
356
/*
357
** Auxiliary function to create the iteration function for 'lines'.
358
** The iteration function is a closure over 'io_readline', with
359
** the following upvalues:
360
** 1) The file being read (first value in the stack)
361
** 2) the number of arguments to read
362
** 3) a boolean, true iff file has to be closed when finished ('toclose')
363
** *) a variable number of format arguments (rest of the stack)
364
*/
365
284k
static void aux_lines (lua_State *L, int toclose) {
366
284k
  int n = lua_gettop(L) - 1;  /* number of arguments to read */
367
284k
  luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
368
284k
  lua_pushvalue(L, 1);  /* file */
369
284k
  lua_pushinteger(L, n);  /* number of arguments to read */
370
284k
  lua_pushboolean(L, toclose);  /* close/not close file when finished */
371
284k
  lua_rotate(L, 2, 3);  /* move the three values to their positions */
372
284k
  lua_pushcclosure(L, io_readline, 3 + n);
373
284k
}
374
375
376
328
static int f_lines (lua_State *L) {
377
328
  tofile(L);  /* check that it's a valid file handle */
378
328
  aux_lines(L, 0);
379
328
  return 1;
380
328
}
381
382
383
/*
384
** Return an iteration function for 'io.lines'. If file has to be
385
** closed, also returns the file itself as a second result (to be
386
** closed as the state at the exit of a generic for).
387
*/
388
284k
static int io_lines (lua_State *L) {
389
284k
  int toclose;
390
284k
  if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */
391
284k
  if (lua_isnil(L, 1)) {  /* no file name? */
392
42.1k
    lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */
393
42.1k
    lua_replace(L, 1);  /* put it at index 1 */
394
42.1k
    tofile(L);  /* check that it's a valid file handle */
395
42.1k
    toclose = 0;  /* do not close it after iteration */
396
42.1k
  }
397
242k
  else {  /* open a new file */
398
242k
    const char *filename = luaL_checkstring(L, 1);
399
242k
    opencheck(L, filename, "r");
400
242k
    lua_replace(L, 1);  /* put file at index 1 */
401
242k
    toclose = 1;  /* close it after iteration */
402
242k
  }
403
284k
  aux_lines(L, toclose);  /* push iteration function */
404
284k
  if (toclose) {
405
242k
    lua_pushnil(L);  /* state */
406
242k
    lua_pushnil(L);  /* control */
407
242k
    lua_pushvalue(L, 1);  /* file is the to-be-closed variable (4th result) */
408
242k
    return 4;
409
242k
  }
410
42.2k
  else
411
42.2k
    return 1;
412
284k
}
413
414
415
/*
416
** {======================================================
417
** READ
418
** =======================================================
419
*/
420
421
422
/* maximum length of a numeral */
423
#if !defined (L_MAXLENNUM)
424
#define L_MAXLENNUM     200
425
#endif
426
427
428
/* auxiliary structure used by 'read_number' */
429
typedef struct {
430
  FILE *f;  /* file being read */
431
  int c;  /* current character (look ahead) */
432
  int n;  /* number of elements in buffer 'buff' */
433
  char buff[L_MAXLENNUM + 1];  /* +1 for ending '\0' */
434
} RN;
435
436
437
/*
438
** Add current char to buffer (if not out of space) and read next one
439
*/
440
7.60k
static int nextc (RN *rn) {
441
7.60k
  if (l_unlikely(rn->n >= L_MAXLENNUM)) {  /* buffer overflow? */
442
6
    rn->buff[0] = '\0';  /* invalidate result */
443
6
    return 0;  /* fail */
444
6
  }
445
7.59k
  else {
446
7.59k
    rn->buff[rn->n++] = cast_char(rn->c);  /* save current char */
447
7.59k
    rn->c = l_getc(rn->f);  /* read next one */
448
7.59k
    return 1;
449
7.59k
  }
450
7.60k
}
451
452
453
/*
454
** Accept current char if it is in 'set' (of size 2)
455
*/
456
1.35k
static int test2 (RN *rn, const char *set) {
457
1.35k
  if (rn->c == set[0] || rn->c == set[1])
458
158
    return nextc(rn);
459
1.19k
  else return 0;
460
1.35k
}
461
462
463
/*
464
** Read a sequence of (hex)digits
465
*/
466
463
static int readdigits (RN *rn, int hex) {
467
463
  int count = 0;
468
7.90k
  while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
469
7.44k
    count++;
470
463
  return count;
471
463
}
472
473
474
/*
475
** Read a number: first reads a valid prefix of a numeral into a buffer.
476
** Then it calls 'lua_stringtonumber' to check whether the format is
477
** correct and to convert it to a Lua number.
478
*/
479
383
static int read_number (lua_State *L, FILE *f) {
480
383
  RN rn;
481
383
  int count = 0;
482
383
  int hex = 0;
483
383
  char decp[2];
484
383
  rn.f = f; rn.n = 0;
485
383
  decp[0] = lua_getlocaledecpoint();  /* get decimal point from locale */
486
383
  decp[1] = '.';  /* always accept a dot */
487
383
  l_lockfile(rn.f);
488
1.02k
  do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */
489
383
  test2(&rn, "-+");  /* optional sign */
490
383
  if (test2(&rn, "00")) {
491
19
    if (test2(&rn, "xX")) hex = 1;  /* numeral is hexadecimal */
492
3
    else count = 1;  /* count initial '0' as a valid digit */
493
19
  }
494
383
  count += readdigits(&rn, hex);  /* integral part */
495
383
  if (test2(&rn, decp))  /* decimal point? */
496
53
    count += readdigits(&rn, hex);  /* fractional part */
497
383
  if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) {  /* exponent mark? */
498
27
    test2(&rn, "-+");  /* exponent sign */
499
27
    readdigits(&rn, 0);  /* exponent digits */
500
27
  }
501
383
  ungetc(rn.c, rn.f);  /* unread look-ahead char */
502
383
  l_unlockfile(rn.f);
503
383
  rn.buff[rn.n] = '\0';  /* finish string */
504
383
  if (l_likely(lua_stringtonumber(L, rn.buff)))
505
151
    return 1;  /* ok, it is a valid number */
506
232
  else {  /* invalid format */
507
232
   lua_pushnil(L);  /* "result" to be removed */
508
232
   return 0;  /* read fails */
509
232
  }
510
383
}
511
512
513
5.69k
static int test_eof (lua_State *L, FILE *f) {
514
5.69k
  int c = getc(f);
515
5.69k
  ungetc(c, f);  /* no-op when c == EOF */
516
5.69k
  lua_pushliteral(L, "");
517
5.69k
  return (c != EOF);
518
5.69k
}
519
520
521
127k
static int read_line (lua_State *L, FILE *f, int chop) {
522
127k
  luaL_Buffer b;
523
127k
  int c;
524
127k
  luaL_buffinit(L, &b);
525
141k
  do {  /* may need to read several chunks to get whole line */
526
141k
    char *buff = luaL_prepbuffer(&b);  /* preallocate buffer space */
527
141k
    unsigned i = 0;
528
141k
    l_lockfile(f);  /* no memory errors can happen inside the lock */
529
14.7M
    while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
530
14.6M
      buff[i++] = cast_char(c);  /* read up to end of line or buffer limit */
531
141k
    l_unlockfile(f);
532
141k
    luaL_addsize(&b, i);
533
141k
  } while (c != EOF && c != '\n');  /* repeat until end of line */
534
127k
  if (!chop && c == '\n')  /* want a newline and have one? */
535
2
    luaL_addchar(&b, '\n');  /* add ending newline to result */
536
127k
  luaL_pushresult(&b);  /* close buffer */
537
  /* return ok if read something (either a newline or something else) */
538
127k
  return (c == '\n' || lua_rawlen(L, -1) > 0);
539
127k
}
540
541
542
660
static void read_all (lua_State *L, FILE *f) {
543
660
  size_t nr;
544
660
  luaL_Buffer b;
545
660
  luaL_buffinit(L, &b);
546
2.73k
  do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */
547
2.73k
    char *p = luaL_prepbuffer(&b);
548
2.73k
    nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
549
2.73k
    luaL_addsize(&b, nr);
550
2.73k
  } while (nr == LUAL_BUFFERSIZE);
551
660
  luaL_pushresult(&b);  /* close buffer */
552
660
}
553
554
555
22.4k
static int read_chars (lua_State *L, FILE *f, size_t n) {
556
22.4k
  size_t nr;  /* number of chars actually read */
557
22.4k
  char *p;
558
22.4k
  luaL_Buffer b;
559
22.4k
  luaL_buffinit(L, &b);
560
22.4k
  p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */
561
22.4k
  nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */
562
22.4k
  luaL_addsize(&b, nr);
563
22.4k
  luaL_pushresult(&b);  /* close buffer */
564
22.4k
  return (nr > 0);  /* true iff read something */
565
22.4k
}
566
567
568
159k
static int g_read (lua_State *L, FILE *f, int first) {
569
159k
  int nargs = lua_gettop(L) - 1;
570
159k
  int n, success;
571
159k
  clearerr(f);
572
159k
  errno = 0;
573
159k
  if (nargs == 0) {  /* no arguments? */
574
127k
    success = read_line(L, f, 1);
575
127k
    n = first + 1;  /* to return 1 result */
576
127k
  }
577
32.5k
  else {
578
    /* ensure stack space for all results and for auxlib's buffer */
579
32.5k
    luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
580
32.5k
    success = 1;
581
65.2k
    for (n = first; nargs-- && success; n++) {
582
32.8k
      if (lua_type(L, n) == LUA_TNUMBER) {
583
30.8k
        size_t l = (size_t)luaL_checkinteger(L, n);
584
30.8k
        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
585
30.8k
      }
586
2.00k
      else {
587
2.00k
        const char *p = luaL_checkstring(L, n);
588
2.00k
        if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
589
2.00k
        switch (*p) {
590
383
          case 'n':  /* number */
591
383
            success = read_number(L, f);
592
383
            break;
593
604
          case 'l':  /* line */
594
604
            success = read_line(L, f, 1);
595
604
            break;
596
150
          case 'L':  /* line with end-of-line */
597
150
            success = read_line(L, f, 0);
598
150
            break;
599
660
          case 'a':  /* file */
600
660
            read_all(L, f);  /* read entire file */
601
660
            success = 1; /* always success */
602
660
            break;
603
171
          default:
604
171
            return luaL_argerror(L, n, "invalid format");
605
2.00k
        }
606
2.00k
      }
607
32.8k
    }
608
32.5k
  }
609
159k
  if (ferror(f))
610
2.80k
    return luaL_fileresult(L, 0, NULL);
611
156k
  if (!success) {
612
58.8k
    lua_pop(L, 1);  /* remove last result */
613
58.8k
    luaL_pushfail(L);  /* push nil instead */
614
58.8k
  }
615
156k
  return n - first;
616
159k
}
617
618
619
2.78k
static int io_read (lua_State *L) {
620
2.78k
  return g_read(L, getiofile(L, IO_INPUT), 1);
621
2.78k
}
622
623
624
3.34k
static int f_read (lua_State *L) {
625
3.34k
  return g_read(L, tofile(L), 2);
626
3.34k
}
627
628
629
/*
630
** Iteration function for 'lines'.
631
*/
632
156k
static int io_readline (lua_State *L) {
633
156k
  LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
634
156k
  int i;
635
156k
  int n = (int)lua_tointeger(L, lua_upvalueindex(2));
636
156k
  if (isclosed(p))  /* file is already closed? */
637
3.20k
    return luaL_error(L, "file is already closed");
638
153k
  lua_settop(L , 1);
639
153k
  luaL_checkstack(L, n, "too many arguments");
640
206k
  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
641
52.5k
    lua_pushvalue(L, lua_upvalueindex(3 + i));
642
153k
  n = g_read(L, p->f, 2);  /* 'n' is number of results */
643
153k
  lua_assert(n > 0);  /* should return at least a nil */
644
153k
  if (lua_toboolean(L, -n))  /* read at least one value? */
645
89.0k
    return n;  /* return them */
646
57.6k
  else {  /* first result is false: EOF or error */
647
57.6k
    if (n > 1) {  /* is there error information? */
648
      /* 2nd result is error message */
649
5
      return luaL_error(L, "%s", lua_tostring(L, -n + 1));
650
5
    }
651
57.6k
    if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */
652
27.9k
      lua_settop(L, 0);  /* clear stack */
653
27.9k
      lua_pushvalue(L, lua_upvalueindex(1));  /* push file at index 1 */
654
27.9k
      aux_close(L);  /* close it */
655
27.9k
    }
656
57.6k
    return 0;
657
57.6k
  }
658
146k
}
659
660
/* }====================================================== */
661
662
663
9.36M
static int g_write (lua_State *L, FILE *f, int arg) {
664
9.36M
  int nargs = lua_gettop(L) - arg;
665
9.36M
  size_t totalbytes = 0;  /* total number of bytes written */
666
9.36M
  errno = 0;
667
55.1M
  for (; nargs--; arg++) {  /* for each argument */
668
45.7M
    char buff[LUA_N2SBUFFSZ];
669
45.7M
    const char *s;
670
45.7M
    size_t numbytes;  /* bytes written in one call to 'fwrite' */
671
45.7M
    size_t len = lua_numbertocstring(L, arg, buff);  /* try as a number */
672
45.7M
    if (len > 0) {  /* did conversion work (value was a number)? */
673
18.1M
      s = buff;
674
18.1M
      len--;
675
18.1M
    }
676
27.5M
    else  /* must be a string */
677
27.5M
      s = luaL_checklstring(L, arg, &len);
678
45.7M
    numbytes = fwrite(s, sizeof(char), len, f);
679
45.7M
    totalbytes += numbytes;
680
45.7M
    if (numbytes < len) {  /* write error? */
681
1.97k
      int n = luaL_fileresult(L, 0, NULL);
682
1.97k
      lua_pushinteger(L, cast_st2S(totalbytes));
683
1.97k
      return n + 1;  /* return fail, error msg., error code, and counter */
684
1.97k
    }
685
45.7M
  }
686
9.36M
  return 1;  /* no errors; file handle already on stack top */
687
9.36M
}
688
689
690
9.36M
static int io_write (lua_State *L) {
691
9.36M
  return g_write(L, getiofile(L, IO_OUTPUT), 1);
692
9.36M
}
693
694
695
3.20k
static int f_write (lua_State *L) {
696
3.20k
  FILE *f = tofile(L);
697
3.20k
  lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */
698
3.20k
  return g_write(L, f, 2);
699
3.20k
}
700
701
702
16.5k
static int f_seek (lua_State *L) {
703
16.5k
  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
704
16.5k
  static const char *const modenames[] = {"set", "cur", "end", NULL};
705
16.5k
  FILE *f = tofile(L);
706
16.5k
  int op = luaL_checkoption(L, 2, "cur", modenames);
707
16.5k
  lua_Integer p3 = luaL_optinteger(L, 3, 0);
708
16.5k
  l_seeknum offset = (l_seeknum)p3;
709
16.5k
  luaL_argcheck(L, (lua_Integer)offset == p3, 3,
710
16.5k
                  "not an integer in proper range");
711
16.5k
  errno = 0;
712
16.5k
  op = l_fseek(f, offset, mode[op]);
713
16.5k
  if (l_unlikely(op))
714
258
    return luaL_fileresult(L, 0, NULL);  /* error */
715
16.2k
  else {
716
16.2k
    lua_pushinteger(L, (lua_Integer)l_ftell(f));
717
16.2k
    return 1;
718
16.2k
  }
719
16.5k
}
720
721
722
262
static int f_setvbuf (lua_State *L) {
723
262
  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
724
262
  static const char *const modenames[] = {"no", "full", "line", NULL};
725
262
  FILE *f = tofile(L);
726
262
  int op = luaL_checkoption(L, 2, NULL, modenames);
727
262
  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
728
262
  int res;
729
262
  errno = 0;
730
262
  res = setvbuf(f, NULL, mode[op], (size_t)sz);
731
262
  return luaL_fileresult(L, res == 0, NULL);
732
262
}
733
734
735
629
static int aux_flush (lua_State *L, FILE *f) {
736
629
  errno = 0;
737
629
  return luaL_fileresult(L, fflush(f) == 0, NULL);
738
629
}
739
740
741
20
static int f_flush (lua_State *L) {
742
20
  return aux_flush(L, tofile(L));
743
20
}
744
745
746
610
static int io_flush (lua_State *L) {
747
610
  return aux_flush(L, getiofile(L, IO_OUTPUT));
748
610
}
749
750
751
/*
752
** functions for 'io' library
753
*/
754
static const luaL_Reg iolib[] = {
755
  {"close", io_close},
756
  {"flush", io_flush},
757
  {"input", io_input},
758
  {"lines", io_lines},
759
  {"open", io_open},
760
  {"output", io_output},
761
  {"popen", io_popen},
762
  {"read", io_read},
763
  {"tmpfile", io_tmpfile},
764
  {"type", io_type},
765
  {"write", io_write},
766
  {NULL, NULL}
767
};
768
769
770
/*
771
** methods for file handles
772
*/
773
static const luaL_Reg meth[] = {
774
  {"read", f_read},
775
  {"write", f_write},
776
  {"lines", f_lines},
777
  {"flush", f_flush},
778
  {"seek", f_seek},
779
  {"close", f_close},
780
  {"setvbuf", f_setvbuf},
781
  {NULL, NULL}
782
};
783
784
785
/*
786
** metamethods for file handles
787
*/
788
static const luaL_Reg metameth[] = {
789
  {"__index", NULL},  /* placeholder */
790
  {"__gc", f_gc},
791
  {"__close", f_gc},
792
  {"__tostring", f_tostring},
793
  {NULL, NULL}
794
};
795
796
797
26.8k
static void createmeta (lua_State *L) {
798
26.8k
  luaL_newmetatable(L, LUA_FILEHANDLE);  /* metatable for file handles */
799
26.8k
  luaL_setfuncs(L, metameth, 0);  /* add metamethods to new metatable */
800
26.8k
  luaL_newlibtable(L, meth);  /* create method table */
801
26.8k
  luaL_setfuncs(L, meth, 0);  /* add file methods to method table */
802
26.8k
  lua_setfield(L, -2, "__index");  /* metatable.__index = method table */
803
26.8k
  lua_pop(L, 1);  /* pop metatable */
804
26.8k
}
805
806
807
/*
808
** function to (not) close the standard files stdin, stdout, and stderr
809
*/
810
344k
static int io_noclose (lua_State *L) {
811
344k
  LStream *p = tolstream(L);
812
344k
  p->closef = &io_noclose;  /* keep file opened */
813
344k
  luaL_pushfail(L);
814
344k
  lua_pushliteral(L, "cannot close standard file");
815
344k
  return 2;
816
344k
}
817
818
819
static void createstdfile (lua_State *L, FILE *f, const char *k,
820
80.4k
                           const char *fname) {
821
80.4k
  LStream *p = newprefile(L);
822
80.4k
  p->f = f;
823
80.4k
  p->closef = &io_noclose;
824
80.4k
  if (k != NULL) {
825
53.6k
    lua_pushvalue(L, -1);
826
53.6k
    lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */
827
53.6k
  }
828
80.4k
  lua_setfield(L, -2, fname);  /* add file to module */
829
80.4k
}
830
831
832
26.8k
LUAMOD_API int luaopen_io (lua_State *L) {
833
26.8k
  luaL_newlib(L, iolib);  /* new module */
834
26.8k
  createmeta(L);
835
  /* create (and set) default files */
836
26.8k
  createstdfile(L, stdin, IO_INPUT, "stdin");
837
26.8k
  createstdfile(L, stdout, IO_OUTPUT, "stdout");
838
26.8k
  createstdfile(L, stderr, NULL, "stderr");
839
26.8k
  return 1;
840
26.8k
}
841