1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
/* generated output implementation
*
* This file is part of nsgenbind.
* Licensed under the MIT License,
* http://www.opensource.org/licenses/mit-license.php
* Copyright 2019 Vincent Sanders <vince@netsurf-browser.org>
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "output.h"
struct opctx {
char *filename;
FILE *outf;
unsigned int lineno;
};
int output_open(const char *filename, struct opctx **opctx_out)
{
struct opctx *opctx;
opctx = malloc(sizeof(struct opctx));
if (opctx == NULL) {
return -1;
}
opctx->filename = strdup(filename);
if (opctx->filename == NULL) {
free(opctx);
return -1;
}
/* open output file */
opctx->outf = genb_fopen_tmp(opctx->filename);
if (opctx->outf == NULL) {
free(opctx->filename);
free(opctx);
return -1;
}
opctx->lineno = 2;
*opctx_out = opctx;
return 0;
}
int output_close(struct opctx *opctx)
{
int res;
res = genb_fclose_tmp(opctx->outf, opctx->filename);
free(opctx->filename);
free(opctx);
return res;
}
/**
* buffer to hold formatted output so newlines can be counted
*/
static char output_buffer[128*1024];
int outputf(struct opctx *opctx, const char *fmt, ...)
{
va_list ap;
int res;
int idx;
va_start(ap, fmt);
res = vsnprintf(output_buffer, sizeof(output_buffer), fmt, ap);
va_end(ap);
/* account for newlines in output */
for (idx = 0; idx < res; idx++) {
if (output_buffer[idx] == '\n') {
opctx->lineno++;
}
}
fwrite(output_buffer, 1, res, opctx->outf);
return res;
}
int outputc(struct opctx *opctx, int c)
{
if (c == '\n') {
opctx->lineno++;
}
fputc(c, opctx->outf);
return 0;
}
int output_line(struct opctx *opctx)
{
int res;
res = fprintf(opctx->outf,
"#line %d \"%s\"\n",
opctx->lineno, opctx->filename);
opctx->lineno++;
return res;
}
|