1 /*
2 * *****************************************************************************
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 *
6 * Copyright (c) 2018-2024 Gavin D. Howard and contributors.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
13 *
14 * * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 *
30 * *****************************************************************************
31 *
32 * Code for implementing buffered I/O on my own terms.
33 *
34 */
35
36 #include <assert.h>
37 #include <errno.h>
38 #include <string.h>
39
40 #ifndef _WIN32
41 #include <unistd.h>
42 #endif // _WIN32
43
44 #include <file.h>
45 #include <vm.h>
46
47 #if !BC_ENABLE_LINE_LIB
48
49 /**
50 * Translates an integer into a string.
51 * @param val The value to translate.
52 * @param buf The return parameter.
53 */
54 static void
bc_file_ultoa(unsigned long long val,char buf[BC_FILE_ULL_LENGTH])55 bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH])
56 {
57 char buf2[BC_FILE_ULL_LENGTH];
58 size_t i, len;
59
60 // We need to make sure the entire thing is zeroed.
61 // NOLINTNEXTLINE
62 memset(buf2, 0, BC_FILE_ULL_LENGTH);
63
64 // The i = 1 is to ensure that there is a null byte at the end.
65 for (i = 1; val; ++i)
66 {
67 unsigned long long mod = val % 10;
68
69 buf2[i] = ((char) mod) + '0';
70 val /= 10;
71 }
72
73 len = i;
74
75 // Since buf2 is reversed, reverse it into buf.
76 for (i = 0; i < len; ++i)
77 {
78 buf[i] = buf2[len - i - 1];
79 }
80 }
81
82 /**
83 * Output to the file directly.
84 * @param fd The file descriptor.
85 * @param buf The buffer of data to output.
86 * @param n The number of bytes to output.
87 * @return A status indicating error or success. We could have a fatal I/O
88 * error or EOF.
89 */
90 static BcStatus
bc_file_output(int fd,const char * buf,size_t n)91 bc_file_output(int fd, const char* buf, size_t n)
92 {
93 size_t bytes = 0;
94 sig_atomic_t lock;
95
96 BC_SIG_TRYLOCK(lock);
97
98 // While the number of bytes written is less than intended...
99 while (bytes < n)
100 {
101 // Write.
102 ssize_t written = write(fd, buf + bytes, n - bytes);
103
104 // Check for error and return, if any.
105 if (BC_ERR(written == -1))
106 {
107 BC_SIG_TRYUNLOCK(lock);
108
109 return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL;
110 }
111
112 bytes += (size_t) written;
113 }
114
115 BC_SIG_TRYUNLOCK(lock);
116
117 return BC_STATUS_SUCCESS;
118 }
119
120 #endif // !BC_ENABLE_LINE_LIB
121
122 BcStatus
bc_file_flushErr(BcFile * restrict f,BcFlushType type)123 bc_file_flushErr(BcFile* restrict f, BcFlushType type)
124 {
125 BcStatus s;
126
127 BC_SIG_ASSERT_LOCKED;
128
129 #if BC_ENABLE_LINE_LIB
130
131 // Just flush and propagate the error.
132 if (fflush(f->f) == EOF) s = BC_STATUS_ERROR_FATAL;
133 else s = BC_STATUS_SUCCESS;
134
135 #else // BC_ENABLE_LINE_LIB
136
137 // If there is stuff to output...
138 if (f->len)
139 {
140 #if BC_ENABLE_HISTORY
141
142 // If history is enabled...
143 if (BC_TTY)
144 {
145 // If we have been told to save the extras, and there *are*
146 // extras...
147 if (f->buf[f->len - 1] != '\n' &&
148 (type == BC_FLUSH_SAVE_EXTRAS_CLEAR ||
149 type == BC_FLUSH_SAVE_EXTRAS_NO_CLEAR))
150 {
151 size_t i;
152
153 // Look for the last newline.
154 for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i)
155 {
156 continue;
157 }
158
159 i += 1;
160
161 // Save the extras.
162 bc_vec_string(&vm->history.extras, f->len - i, f->buf + i);
163 }
164 // Else clear the extras if told to.
165 else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR)
166 {
167 bc_vec_popAll(&vm->history.extras);
168 }
169 }
170 #endif // BC_ENABLE_HISTORY
171
172 // Actually output.
173 s = bc_file_output(f->fd, f->buf, f->len);
174 f->len = 0;
175 }
176 else s = BC_STATUS_SUCCESS;
177
178 #endif // BC_ENABLE_LINE_LIB
179
180 return s;
181 }
182
183 void
bc_file_flush(BcFile * restrict f,BcFlushType type)184 bc_file_flush(BcFile* restrict f, BcFlushType type)
185 {
186 BcStatus s;
187 sig_atomic_t lock;
188
189 BC_SIG_TRYLOCK(lock);
190
191 s = bc_file_flushErr(f, type);
192
193 // If we have an error...
194 if (BC_ERR(s))
195 {
196 // For EOF, set it and jump.
197 if (s == BC_STATUS_EOF)
198 {
199 vm->status = (sig_atomic_t) s;
200 BC_SIG_TRYUNLOCK(lock);
201 BC_JMP;
202 }
203 // Make sure to handle non-fatal I/O properly.
204 else if (!f->errors_fatal)
205 {
206 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
207 }
208 // Blow up on fatal error. Okay, not blow up, just quit.
209 else exit(BC_STATUS_ERROR_FATAL);
210 }
211
212 BC_SIG_TRYUNLOCK(lock);
213 }
214
215 #if !BC_ENABLE_LINE_LIB
216
217 void
bc_file_write(BcFile * restrict f,BcFlushType type,const char * buf,size_t n)218 bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n)
219 {
220 sig_atomic_t lock;
221
222 BC_SIG_TRYLOCK(lock);
223
224 // If we have enough to flush, do it.
225 if (n > f->cap - f->len)
226 {
227 bc_file_flush(f, type);
228 assert(!f->len);
229 }
230
231 // If the output is large enough to flush by itself, just output it.
232 // Otherwise, put it into the buffer.
233 if (BC_UNLIKELY(n > f->cap - f->len))
234 {
235 BcStatus s = bc_file_output(f->fd, buf, n);
236
237 if (BC_ERR(s))
238 {
239 // For EOF, set it and jump.
240 if (s == BC_STATUS_EOF)
241 {
242 vm->status = (sig_atomic_t) s;
243 BC_SIG_TRYUNLOCK(lock);
244 BC_JMP;
245 }
246 // Make sure to handle non-fatal I/O properly.
247 else if (!f->errors_fatal)
248 {
249 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
250 }
251 // Blow up on fatal error. Okay, not blow up, just quit.
252 else exit(BC_STATUS_ERROR_FATAL);
253 }
254 }
255 else
256 {
257 // NOLINTNEXTLINE
258 memcpy(f->buf + f->len, buf, n);
259 f->len += n;
260 }
261
262 BC_SIG_TRYUNLOCK(lock);
263 }
264
265 #endif // BC_ENABLE_LINE_LIB
266
267 void
bc_file_printf(BcFile * restrict f,const char * fmt,...)268 bc_file_printf(BcFile* restrict f, const char* fmt, ...)
269 {
270 va_list args;
271 sig_atomic_t lock;
272
273 BC_SIG_TRYLOCK(lock);
274
275 va_start(args, fmt);
276 bc_file_vprintf(f, fmt, args);
277 va_end(args);
278
279 BC_SIG_TRYUNLOCK(lock);
280 }
281
282 void
bc_file_vprintf(BcFile * restrict f,const char * fmt,va_list args)283 bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args)
284 {
285 BC_SIG_ASSERT_LOCKED;
286
287 #if BC_ENABLE_LINE_LIB
288
289 {
290 int r;
291
292 // This mess is to silence a warning.
293 #if BC_CLANG
294 #pragma clang diagnostic push
295 #pragma clang diagnostic ignored "-Wformat-nonliteral"
296 #endif // BC_CLANG
297 r = vfprintf(f->f, fmt, args);
298 #if BC_CLANG
299 #pragma clang diagnostic pop
300 #endif // BC_CLANG
301
302 // Just print and propagate the error.
303 if (BC_ERR(r < 0))
304 {
305 // Make sure to handle non-fatal I/O properly.
306 if (!f->errors_fatal)
307 {
308 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
309 }
310 else
311 {
312 exit(BC_STATUS_ERROR_FATAL);
313 }
314 }
315 }
316
317 #else // BC_ENABLE_LINE_LIB
318
319 {
320 char* percent;
321 const char* ptr = fmt;
322 char buf[BC_FILE_ULL_LENGTH];
323
324 // This is a poor man's printf(). While I could look up algorithms to
325 // make it as fast as possible, and should when I write the standard
326 // library for a new language, for bc, outputting is not the bottleneck.
327 // So we cheese it for now.
328
329 // Find each percent sign.
330 while ((percent = strchr(ptr, '%')) != NULL)
331 {
332 char c;
333
334 // If the percent sign is not where we are, write what's inbetween
335 // to the buffer.
336 if (percent != ptr)
337 {
338 size_t len = (size_t) (percent - ptr);
339 bc_file_write(f, bc_flush_none, ptr, len);
340 }
341
342 c = percent[1];
343
344 // We only parse some format specifiers, the ones bc uses. If you
345 // add more, you need to make sure to add them here.
346 if (c == 'c')
347 {
348 uchar uc = (uchar) va_arg(args, int);
349
350 bc_file_putchar(f, bc_flush_none, uc);
351 }
352 else if (c == 's')
353 {
354 char* s = va_arg(args, char*);
355
356 bc_file_puts(f, bc_flush_none, s);
357 }
358 #if BC_DEBUG
359 // We only print signed integers in debug code.
360 else if (c == 'd')
361 {
362 int d = va_arg(args, int);
363
364 // Take care of negative. Let's not worry about overflow.
365 if (d < 0)
366 {
367 bc_file_putchar(f, bc_flush_none, '-');
368 d = -d;
369 }
370
371 // Either print 0 or translate and print.
372 if (!d) bc_file_putchar(f, bc_flush_none, '0');
373 else
374 {
375 bc_file_ultoa((unsigned long long) d, buf);
376 bc_file_puts(f, bc_flush_none, buf);
377 }
378 }
379 #endif // BC_DEBUG
380 else
381 {
382 unsigned long long ull;
383
384 // These are the ones that it expects from here. Fortunately,
385 // all of these are unsigned types, so they can use the same
386 // code, more or less.
387 assert((c == 'l' || c == 'z') && percent[2] == 'u');
388
389 if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
390 else ull = (unsigned long long) va_arg(args, unsigned long);
391
392 // Either print 0 or translate and print.
393 if (!ull) bc_file_putchar(f, bc_flush_none, '0');
394 else
395 {
396 bc_file_ultoa(ull, buf);
397 bc_file_puts(f, bc_flush_none, buf);
398 }
399 }
400
401 // Increment to the next spot after the specifier.
402 ptr = percent + 2 + (c == 'l' || c == 'z');
403 }
404
405 // If we get here, there are no more percent signs, so we just output
406 // whatever is left.
407 if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
408 }
409
410 #endif // BC_ENABLE_LINE_LIB
411 }
412
413 void
bc_file_puts(BcFile * restrict f,BcFlushType type,const char * str)414 bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str)
415 {
416 #if BC_ENABLE_LINE_LIB
417 // This is used because of flushing issues with using bc_file_write() when
418 // bc is using a line library. It's also using printf() because puts()
419 // writes a newline.
420 bc_file_printf(f, "%s", str);
421 #else // BC_ENABLE_LINE_LIB
422 bc_file_write(f, type, str, strlen(str));
423 #endif // BC_ENABLE_LINE_LIB
424 }
425
426 void
bc_file_putchar(BcFile * restrict f,BcFlushType type,uchar c)427 bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c)
428 {
429 sig_atomic_t lock;
430
431 BC_SIG_TRYLOCK(lock);
432
433 #if BC_ENABLE_LINE_LIB
434
435 if (BC_ERR(fputc(c, f->f) == EOF))
436 {
437 // This is here to prevent a stack overflow from unbounded recursion.
438 if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL);
439
440 bc_err(BC_ERR_FATAL_IO_ERR);
441 }
442
443 #else // BC_ENABLE_LINE_LIB
444
445 if (f->len == f->cap) bc_file_flush(f, type);
446
447 assert(f->len < f->cap);
448
449 f->buf[f->len] = (char) c;
450 f->len += 1;
451
452 #endif // BC_ENABLE_LINE_LIB
453
454 BC_SIG_TRYUNLOCK(lock);
455 }
456
457 #if BC_ENABLE_LINE_LIB
458
459 void
bc_file_init(BcFile * f,FILE * file,bool errors_fatal)460 bc_file_init(BcFile* f, FILE* file, bool errors_fatal)
461 {
462 BC_SIG_ASSERT_LOCKED;
463 f->f = file;
464 f->errors_fatal = errors_fatal;
465 }
466
467 #else // BC_ENABLE_LINE_LIB
468
469 void
bc_file_init(BcFile * f,int fd,char * buf,size_t cap,bool errors_fatal)470 bc_file_init(BcFile* f, int fd, char* buf, size_t cap, bool errors_fatal)
471 {
472 BC_SIG_ASSERT_LOCKED;
473
474 f->fd = fd;
475 f->buf = buf;
476 f->len = 0;
477 f->cap = cap;
478 f->errors_fatal = errors_fatal;
479 }
480
481 #endif // BC_ENABLE_LINE_LIB
482
483 void
bc_file_free(BcFile * f)484 bc_file_free(BcFile* f)
485 {
486 BC_SIG_ASSERT_LOCKED;
487 bc_file_flush(f, bc_flush_none);
488 }
489