Coverage Report

Created: 2026-02-26 07:19

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
140k
#define L_MODEEXT "b"
36
#endif
37
38
/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
39
140k
static int l_checkmode (const char *mode) {
40
140k
  return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
41
140k
         (*mode != '+' || ((void)(++mode), 1)) &&  /* skip if char is '+' */
42
140k
         (strspn(mode, L_MODEEXT) == strlen(mode)));  /* check extensions */
43
140k
}
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
#define l_popen(L,c,m)    (fflush(NULL), popen(c,m))
59
#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
24
    ((void)c, (void)m, \
77
24
    luaL_error(L, "'popen' not supported"), \
78
24
    (FILE*)0)
79
0
#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
#define l_getc(f)   getc_unlocked(f)
98
#define l_lockfile(f)   flockfile(f)
99
#define l_unlockfile(f)   funlockfile(f)
100
#else
101
7.62M
#define l_getc(f)   getc(f)
102
136k
#define l_lockfile(f)   ((void)0)
103
136k
#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
#define l_fseek(f,o,w)    fseeko(f,o,w)
122
#define l_ftell(f)    ftello(f)
123
#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
18.6k
#define l_fseek(f,o,w)    fseek(f,o,w)
137
18.4k
#define l_ftell(f)    ftell(f)
138
18.6k
#define l_seeknum   long
139
140
#endif        /* } */
141
142
#endif        /* } */
143
144
/* }====================================================== */
145
146
147
148
6.58M
#define IO_PREFIX "_IO_"
149
2.00k
#define IOPREF_LEN  (sizeof(IO_PREFIX)/sizeof(char) - 1)
150
412k
#define IO_INPUT  (IO_PREFIX "input")
151
6.17M
#define IO_OUTPUT (IO_PREFIX "output")
152
153
154
typedef luaL_Stream LStream;
155
156
157
2.36M
#define tolstream(L)  ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
158
159
1.10M
#define isclosed(p) ((p)->closef == NULL)
160
161
162
11.3k
static int io_type (lua_State *L) {
163
11.3k
  LStream *p;
164
11.3k
  luaL_checkany(L, 1);
165
11.3k
  p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
166
11.3k
  if (p == NULL)
167
8.68k
    luaL_pushfail(L);  /* not a file */
168
2.63k
  else if (isclosed(p))
169
43
    lua_pushliteral(L, "closed file");
170
2.59k
  else
171
2.59k
    lua_pushliteral(L, "file");
172
11.3k
  return 1;
173
11.3k
}
174
175
176
112
static int f_tostring (lua_State *L) {
177
112
  LStream *p = tolstream(L);
178
112
  if (isclosed(p))
179
111
    lua_pushliteral(L, "file (closed)");
180
1
  else
181
1
    lua_pushfstring(L, "file (%p)", p->f);
182
112
  return 1;
183
112
}
184
185
186
624k
static FILE *tofile (lua_State *L) {
187
624k
  LStream *p = tolstream(L);
188
624k
  if (l_unlikely(isclosed(p)))
189
2.56k
    luaL_error(L, "attempt to use a closed file");
190
624k
  lua_assert(p->f);
191
624k
  return p->f;
192
624k
}
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
418k
static LStream *newprefile (lua_State *L) {
201
418k
  LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
202
418k
  p->closef = NULL;  /* mark file handle as 'closed' */
203
418k
  luaL_setmetatable(L, LUA_FILEHANDLE);
204
418k
  return p;
205
418k
}
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
660k
static int aux_close (lua_State *L) {
214
660k
  LStream *p = tolstream(L);
215
660k
  volatile lua_CFunction cf = p->closef;
216
660k
  p->closef = NULL;  /* mark stream as closed */
217
660k
  return (*cf)(L);  /* close it */
218
660k
}
219
220
221
260k
static int f_close (lua_State *L) {
222
260k
  tofile(L);  /* make sure argument is an open stream */
223
260k
  return aux_close(L);
224
260k
}
225
226
227
258k
static int io_close (lua_State *L) {
228
258k
  if (lua_isnone(L, 1))  /* no argument? */
229
257k
    lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use default output */
230
258k
  return f_close(L);
231
258k
}
232
233
234
419k
static int f_gc (lua_State *L) {
235
419k
  LStream *p = tolstream(L);
236
419k
  if (!isclosed(p) && p->f != NULL)
237
399k
    aux_close(L);  /* ignore closed and incompletely open files */
238
419k
  return 0;
239
419k
}
240
241
242
/*
243
** function to close regular files
244
*/
245
364k
static int io_fclose (lua_State *L) {
246
364k
  LStream *p = tolstream(L);
247
364k
  errno = 0;
248
364k
  return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
249
364k
}
250
251
252
378k
static LStream *newfile (lua_State *L) {
253
378k
  LStream *p = newprefile(L);
254
378k
  p->f = NULL;
255
378k
  p->closef = &io_fclose;
256
378k
  return p;
257
378k
}
258
259
260
238k
static void opencheck (lua_State *L, const char *fname, const char *mode) {
261
238k
  LStream *p = newfile(L);
262
238k
  p->f = fopen(fname, mode);
263
238k
  if (l_unlikely(p->f == NULL))
264
3
    luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
265
238k
}
266
267
268
141k
static int io_open (lua_State *L) {
269
141k
  const char *filename = luaL_checkstring(L, 1);
270
141k
  const char *mode = luaL_optstring(L, 2, "r");
271
141k
  LStream *p = newfile(L);
272
141k
  const char *md = mode;  /* to traverse/check mode */
273
141k
  luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
274
141k
  errno = 0;
275
141k
  p->f = fopen(filename, mode);
276
141k
  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
277
141k
}
278
279
280
/*
281
** function to close 'popen' files
282
*/
283
0
static int io_pclose (lua_State *L) {
284
0
  LStream *p = tolstream(L);
285
0
  errno = 0;
286
0
  return luaL_execresult(L, l_pclose(L, p->f));
287
0
}
288
289
290
24
static int io_popen (lua_State *L) {
291
24
  const char *filename = luaL_checkstring(L, 1);
292
24
  const char *mode = luaL_optstring(L, 2, "r");
293
24
  LStream *p = newprefile(L);
294
24
  luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
295
24
  errno = 0;
296
24
  p->f = l_popen(L, filename, mode);
297
24
  p->closef = &io_pclose;
298
24
  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
299
24
}
300
301
302
17
static int io_tmpfile (lua_State *L) {
303
17
  LStream *p = newfile(L);
304
17
  errno = 0;
305
17
  p->f = tmpfile();
306
17
  return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
307
17
}
308
309
310
5.86M
static FILE *getiofile (lua_State *L, const char *findex) {
311
5.86M
  LStream *p;
312
5.86M
  lua_getfield(L, LUA_REGISTRYINDEX, findex);
313
5.86M
  p = (LStream *)lua_touserdata(L, -1);
314
5.86M
  if (l_unlikely(isclosed(p)))
315
2.00k
    luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
316
5.86M
  return p->f;
317
5.86M
}
318
319
320
174k
static int g_iofile (lua_State *L, const char *f, const char *mode) {
321
174k
  if (!lua_isnoneornil(L, 1)) {
322
144k
    const char *filename = lua_tostring(L, 1);
323
144k
    if (filename)
324
120k
      opencheck(L, filename, mode);
325
24.7k
    else {
326
24.7k
      tofile(L);  /* check that it's a valid file handle */
327
24.7k
      lua_pushvalue(L, 1);
328
24.7k
    }
329
144k
    lua_setfield(L, LUA_REGISTRYINDEX, f);
330
144k
  }
331
  /* return current value */
332
174k
  lua_getfield(L, LUA_REGISTRYINDEX, f);
333
174k
  return 1;
334
174k
}
335
336
337
130k
static int io_input (lua_State *L) {
338
130k
  return g_iofile(L, IO_INPUT, "r");
339
130k
}
340
341
342
43.9k
static int io_output (lua_State *L) {
343
43.9k
  return g_iofile(L, IO_OUTPUT, "w");
344
43.9k
}
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
376k
static void aux_lines (lua_State *L, int toclose) {
366
376k
  int n = lua_gettop(L) - 1;  /* number of arguments to read */
367
376k
  luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
368
376k
  lua_pushvalue(L, 1);  /* file */
369
376k
  lua_pushinteger(L, n);  /* number of arguments to read */
370
376k
  lua_pushboolean(L, toclose);  /* close/not close file when finished */
371
376k
  lua_rotate(L, 2, 3);  /* move the three values to their positions */
372
376k
  lua_pushcclosure(L, io_readline, 3 + n);
373
376k
}
374
375
376
1.01k
static int f_lines (lua_State *L) {
377
1.01k
  tofile(L);  /* check that it's a valid file handle */
378
1.01k
  aux_lines(L, 0);
379
1.01k
  return 1;
380
1.01k
}
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
376k
static int io_lines (lua_State *L) {
389
376k
  int toclose;
390
376k
  if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */
391
376k
  if (lua_isnil(L, 1)) {  /* no file name? */
392
258k
    lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */
393
258k
    lua_replace(L, 1);  /* put it at index 1 */
394
258k
    tofile(L);  /* check that it's a valid file handle */
395
258k
    toclose = 0;  /* do not close it after iteration */
396
258k
  }
397
118k
  else {  /* open a new file */
398
118k
    const char *filename = luaL_checkstring(L, 1);
399
118k
    opencheck(L, filename, "r");
400
118k
    lua_replace(L, 1);  /* put file at index 1 */
401
118k
    toclose = 1;  /* close it after iteration */
402
118k
  }
403
376k
  aux_lines(L, toclose);  /* push iteration function */
404
376k
  if (toclose) {
405
118k
    lua_pushnil(L);  /* state */
406
118k
    lua_pushnil(L);  /* control */
407
118k
    lua_pushvalue(L, 1);  /* file is the to-be-closed variable (4th result) */
408
118k
    return 4;
409
118k
  }
410
258k
  else
411
258k
    return 1;
412
376k
}
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
777
static int nextc (RN *rn) {
441
777
  if (l_unlikely(rn->n >= L_MAXLENNUM)) {  /* buffer overflow? */
442
0
    rn->buff[0] = '\0';  /* invalidate result */
443
0
    return 0;  /* fail */
444
0
  }
445
777
  else {
446
777
    rn->buff[rn->n++] = cast_char(rn->c);  /* save current char */
447
777
    rn->c = l_getc(rn->f);  /* read next one */
448
777
    return 1;
449
777
  }
450
777
}
451
452
453
/*
454
** Accept current char if it is in 'set' (of size 2)
455
*/
456
11.5k
static int test2 (RN *rn, const char *set) {
457
11.5k
  if (rn->c == set[0] || rn->c == set[1])
458
50
    return nextc(rn);
459
11.5k
  else return 0;
460
11.5k
}
461
462
463
/*
464
** Read a sequence of (hex)digits
465
*/
466
3.85k
static int readdigits (RN *rn, int hex) {
467
3.85k
  int count = 0;
468
4.58k
  while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
469
727
    count++;
470
3.85k
  return count;
471
3.85k
}
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
3.83k
static int read_number (lua_State *L, FILE *f) {
480
3.83k
  RN rn;
481
3.83k
  int count = 0;
482
3.83k
  int hex = 0;
483
3.83k
  char decp[2];
484
3.83k
  rn.f = f; rn.n = 0;
485
3.83k
  decp[0] = lua_getlocaledecpoint();  /* get decimal point from locale */
486
3.83k
  decp[1] = '.';  /* always accept a dot */
487
3.83k
  l_lockfile(rn.f);
488
4.98k
  do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */
489
3.83k
  test2(&rn, "-+");  /* optional sign */
490
3.83k
  if (test2(&rn, "00")) {
491
2
    if (test2(&rn, "xX")) hex = 1;  /* numeral is hexadecimal */
492
2
    else count = 1;  /* count initial '0' as a valid digit */
493
2
  }
494
3.83k
  count += readdigits(&rn, hex);  /* integral part */
495
3.83k
  if (test2(&rn, decp))  /* decimal point? */
496
13
    count += readdigits(&rn, hex);  /* fractional part */
497
3.83k
  if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) {  /* exponent mark? */
498
14
    test2(&rn, "-+");  /* exponent sign */
499
14
    readdigits(&rn, 0);  /* exponent digits */
500
14
  }
501
3.83k
  ungetc(rn.c, rn.f);  /* unread look-ahead char */
502
3.83k
  l_unlockfile(rn.f);
503
3.83k
  rn.buff[rn.n] = '\0';  /* finish string */
504
3.83k
  if (l_likely(lua_stringtonumber(L, rn.buff)))
505
64
    return 1;  /* ok, it is a valid number */
506
3.76k
  else {  /* invalid format */
507
3.76k
   lua_pushnil(L);  /* "result" to be removed */
508
3.76k
   return 0;  /* read fails */
509
3.76k
  }
510
3.83k
}
511
512
513
170
static int test_eof (lua_State *L, FILE *f) {
514
170
  int c = getc(f);
515
170
  ungetc(c, f);  /* no-op when c == EOF */
516
170
  lua_pushliteral(L, "");
517
170
  return (c != EOF);
518
170
}
519
520
521
125k
static int read_line (lua_State *L, FILE *f, int chop) {
522
125k
  luaL_Buffer b;
523
125k
  int c;
524
125k
  luaL_buffinit(L, &b);
525
132k
  do {  /* may need to read several chunks to get whole line */
526
132k
    char *buff = luaL_prepbuffer(&b);  /* preallocate buffer space */
527
132k
    unsigned i = 0;
528
132k
    l_lockfile(f);  /* no memory errors can happen inside the lock */
529
7.62M
    while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
530
7.49M
      buff[i++] = cast_char(c);  /* read up to end of line or buffer limit */
531
132k
    l_unlockfile(f);
532
132k
    luaL_addsize(&b, i);
533
132k
  } while (c != EOF && c != '\n');  /* repeat until end of line */
534
125k
  if (!chop && c == '\n')  /* want a newline and have one? */
535
3
    luaL_addchar(&b, '\n');  /* add ending newline to result */
536
125k
  luaL_pushresult(&b);  /* close buffer */
537
  /* return ok if read something (either a newline or something else) */
538
125k
  return (c == '\n' || lua_rawlen(L, -1) > 0);
539
125k
}
540
541
542
4.23k
static void read_all (lua_State *L, FILE *f) {
543
4.23k
  size_t nr;
544
4.23k
  luaL_Buffer b;
545
4.23k
  luaL_buffinit(L, &b);
546
10.2k
  do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */
547
10.2k
    char *p = luaL_prepbuffer(&b);
548
10.2k
    nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
549
10.2k
    luaL_addsize(&b, nr);
550
10.2k
  } while (nr == LUAL_BUFFERSIZE);
551
4.23k
  luaL_pushresult(&b);  /* close buffer */
552
4.23k
}
553
554
555
148k
static int read_chars (lua_State *L, FILE *f, size_t n) {
556
148k
  size_t nr;  /* number of chars actually read */
557
148k
  char *p;
558
148k
  luaL_Buffer b;
559
148k
  luaL_buffinit(L, &b);
560
148k
  p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */
561
148k
  nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */
562
148k
  luaL_addsize(&b, nr);
563
148k
  luaL_pushresult(&b);  /* close buffer */
564
148k
  return (nr > 0);  /* true iff read something */
565
148k
}
566
567
568
283k
static int g_read (lua_State *L, FILE *f, int first) {
569
283k
  int nargs = lua_gettop(L) - 1;
570
283k
  int n, success;
571
283k
  clearerr(f);
572
283k
  errno = 0;
573
283k
  if (nargs == 0) {  /* no arguments? */
574
122k
    success = read_line(L, f, 1);
575
122k
    n = first + 1;  /* to return 1 result */
576
122k
  }
577
160k
  else {
578
    /* ensure stack space for all results and for auxlib's buffer */
579
160k
    luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
580
160k
    success = 1;
581
320k
    for (n = first; nargs-- && success; n++) {
582
160k
      if (lua_type(L, n) == LUA_TNUMBER) {
583
149k
        size_t l = (size_t)luaL_checkinteger(L, n);
584
149k
        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
585
149k
      }
586
10.8k
      else {
587
10.8k
        const char *p = luaL_checkstring(L, n);
588
10.8k
        if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
589
10.8k
        switch (*p) {
590
3.83k
          case 'n':  /* number */
591
3.83k
            success = read_number(L, f);
592
3.83k
            break;
593
422
          case 'l':  /* line */
594
422
            success = read_line(L, f, 1);
595
422
            break;
596
2.34k
          case 'L':  /* line with end-of-line */
597
2.34k
            success = read_line(L, f, 0);
598
2.34k
            break;
599
4.23k
          case 'a':  /* file */
600
4.23k
            read_all(L, f);  /* read entire file */
601
4.23k
            success = 1; /* always success */
602
4.23k
            break;
603
33
          default:
604
33
            return luaL_argerror(L, n, "invalid format");
605
10.8k
        }
606
10.8k
      }
607
160k
    }
608
160k
  }
609
283k
  if (ferror(f))
610
1.52k
    return luaL_fileresult(L, 0, NULL);
611
281k
  if (!success) {
612
261k
    lua_pop(L, 1);  /* remove last result */
613
261k
    luaL_pushfail(L);  /* push nil instead */
614
261k
  }
615
281k
  return n - first;
616
283k
}
617
618
619
10.2k
static int io_read (lua_State *L) {
620
10.2k
  return g_read(L, getiofile(L, IO_INPUT), 1);
621
10.2k
}
622
623
624
7.71k
static int f_read (lua_State *L) {
625
7.71k
  return g_read(L, tofile(L), 2);
626
7.71k
}
627
628
629
/*
630
** Iteration function for 'lines'.
631
*/
632
266k
static int io_readline (lua_State *L) {
633
266k
  LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
634
266k
  int i;
635
266k
  int n = (int)lua_tointeger(L, lua_upvalueindex(2));
636
266k
  if (isclosed(p))  /* file is already closed? */
637
407
    return luaL_error(L, "file is already closed");
638
265k
  lua_settop(L , 1);
639
265k
  luaL_checkstack(L, n, "too many arguments");
640
429k
  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
641
163k
    lua_pushvalue(L, lua_upvalueindex(3 + i));
642
265k
  n = g_read(L, p->f, 2);  /* 'n' is number of results */
643
265k
  lua_assert(n > 0);  /* should return at least a nil */
644
265k
  if (lua_toboolean(L, -n))  /* read at least one value? */
645
7.52k
    return n;  /* return them */
646
252k
  else {  /* first result is false: EOF or error */
647
252k
    if (n > 1) {  /* is there error information? */
648
      /* 2nd result is error message */
649
551
      return luaL_error(L, "%s", lua_tostring(L, -n + 1));
650
551
    }
651
252k
    if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */
652
1.43k
      lua_settop(L, 0);  /* clear stack */
653
1.43k
      lua_pushvalue(L, lua_upvalueindex(1));  /* push file at index 1 */
654
1.43k
      aux_close(L);  /* close it */
655
1.43k
    }
656
252k
    return 0;
657
252k
  }
658
260k
}
659
660
/* }====================================================== */
661
662
663
5.90M
static int g_write (lua_State *L, FILE *f, int arg) {
664
5.90M
  int nargs = lua_gettop(L) - arg;
665
5.90M
  size_t totalbytes = 0;  /* total number of bytes written */
666
5.90M
  errno = 0;
667
35.0M
  for (; nargs--; arg++) {  /* for each argument */
668
29.1M
    char buff[LUA_N2SBUFFSZ];
669
29.1M
    const char *s;
670
29.1M
    size_t numbytes;  /* bytes written in one call to 'fwrite' */
671
29.1M
    size_t len = lua_numbertocstring(L, arg, buff);  /* try as a number */
672
29.1M
    if (len > 0) {  /* did conversion work (value was a number)? */
673
11.6M
      s = buff;
674
11.6M
      len--;
675
11.6M
    }
676
17.5M
    else  /* must be a string */
677
17.5M
      s = luaL_checklstring(L, arg, &len);
678
29.1M
    numbytes = fwrite(s, sizeof(char), len, f);
679
29.1M
    totalbytes += numbytes;
680
29.1M
    if (numbytes < len) {  /* write error? */
681
2.09k
      int n = luaL_fileresult(L, 0, NULL);
682
2.09k
      lua_pushinteger(L, cast_st2S(totalbytes));
683
2.09k
      return n + 1;  /* return fail, error msg., error code, and counter */
684
2.09k
    }
685
29.1M
  }
686
5.90M
  return 1;  /* no errors; file handle already on stack top */
687
5.90M
}
688
689
690
5.85M
static int io_write (lua_State *L) {
691
5.85M
  return g_write(L, getiofile(L, IO_OUTPUT), 1);
692
5.85M
}
693
694
695
49.3k
static int f_write (lua_State *L) {
696
49.3k
  FILE *f = tofile(L);
697
49.3k
  lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */
698
49.3k
  return g_write(L, f, 2);
699
49.3k
}
700
701
702
18.6k
static int f_seek (lua_State *L) {
703
18.6k
  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
704
18.6k
  static const char *const modenames[] = {"set", "cur", "end", NULL};
705
18.6k
  FILE *f = tofile(L);
706
18.6k
  int op = luaL_checkoption(L, 2, "cur", modenames);
707
18.6k
  lua_Integer p3 = luaL_optinteger(L, 3, 0);
708
18.6k
  l_seeknum offset = (l_seeknum)p3;
709
18.6k
  luaL_argcheck(L, (lua_Integer)offset == p3, 3,
710
18.6k
                  "not an integer in proper range");
711
18.6k
  errno = 0;
712
18.6k
  op = l_fseek(f, offset, mode[op]);
713
18.6k
  if (l_unlikely(op))
714
216
    return luaL_fileresult(L, 0, NULL);  /* error */
715
18.4k
  else {
716
18.4k
    lua_pushinteger(L, (lua_Integer)l_ftell(f));
717
18.4k
    return 1;
718
18.4k
  }
719
18.6k
}
720
721
722
4.11k
static int f_setvbuf (lua_State *L) {
723
4.11k
  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
724
4.11k
  static const char *const modenames[] = {"no", "full", "line", NULL};
725
4.11k
  FILE *f = tofile(L);
726
4.11k
  int op = luaL_checkoption(L, 2, NULL, modenames);
727
4.11k
  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
728
4.11k
  int res;
729
4.11k
  errno = 0;
730
4.11k
  res = setvbuf(f, NULL, mode[op], (size_t)sz);
731
4.11k
  return luaL_fileresult(L, res == 0, NULL);
732
4.11k
}
733
734
735
259
static int aux_flush (lua_State *L, FILE *f) {
736
259
  errno = 0;
737
259
  return luaL_fileresult(L, fflush(f) == 0, NULL);
738
259
}
739
740
741
12
static int f_flush (lua_State *L) {
742
12
  return aux_flush(L, tofile(L));
743
12
}
744
745
746
247
static int io_flush (lua_State *L) {
747
247
  return aux_flush(L, getiofile(L, IO_OUTPUT));
748
247
}
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
13.0k
static void createmeta (lua_State *L) {
798
13.0k
  luaL_newmetatable(L, LUA_FILEHANDLE);  /* metatable for file handles */
799
13.0k
  luaL_setfuncs(L, metameth, 0);  /* add metamethods to new metatable */
800
13.0k
  luaL_newlibtable(L, meth);  /* create method table */
801
13.0k
  luaL_setfuncs(L, meth, 0);  /* add file methods to method table */
802
13.0k
  lua_setfield(L, -2, "__index");  /* metatable.__index = method table */
803
13.0k
  lua_pop(L, 1);  /* pop metatable */
804
13.0k
}
805
806
807
/*
808
** function to (not) close the standard files stdin, stdout, and stderr
809
*/
810
295k
static int io_noclose (lua_State *L) {
811
295k
  LStream *p = tolstream(L);
812
295k
  p->closef = &io_noclose;  /* keep file opened */
813
295k
  luaL_pushfail(L);
814
295k
  lua_pushliteral(L, "cannot close standard file");
815
295k
  return 2;
816
295k
}
817
818
819
static void createstdfile (lua_State *L, FILE *f, const char *k,
820
39.1k
                           const char *fname) {
821
39.1k
  LStream *p = newprefile(L);
822
39.1k
  p->f = f;
823
39.1k
  p->closef = &io_noclose;
824
39.1k
  if (k != NULL) {
825
26.0k
    lua_pushvalue(L, -1);
826
26.0k
    lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */
827
26.0k
  }
828
39.1k
  lua_setfield(L, -2, fname);  /* add file to module */
829
39.1k
}
830
831
832
13.0k
LUAMOD_API int luaopen_io (lua_State *L) {
833
13.0k
  luaL_newlib(L, iolib);  /* new module */
834
13.0k
  createmeta(L);
835
  /* create (and set) default files */
836
13.0k
  createstdfile(L, stdin, IO_INPUT, "stdin");
837
13.0k
  createstdfile(L, stdout, IO_OUTPUT, "stdout");
838
13.0k
  createstdfile(L, stderr, NULL, "stderr");
839
13.0k
  return 1;
840
13.0k
}
841