forked from gbdev/rgbds
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfstack.c
400 lines (348 loc) · 11 KB
/
fstack.c
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "asm/fstack.h"
#include "asm/macro.h"
#include "asm/main.h"
#include "asm/symbol.h"
#include "asm/warning.h"
#include "platform.h" /* S_ISDIR (stat macro) */
#ifdef LEXER_DEBUG
#define dbgPrint(...) fprintf(stderr, "[lexer] " __VA_ARGS__)
#else
#define dbgPrint(...)
#endif
struct Context {
struct Context *parent;
struct Context *child;
struct LexerState *lexerState;
uint32_t uniqueID;
char const *fileName;
char *fileNameBuf;
uint32_t lineNo; /* Line number at which the context was EXITED */
struct Symbol const *macro;
struct MacroArgs *macroArgs; /* Macro args are *saved* here */
uint32_t nbReptIters; /* If zero, this isn't a REPT block */
size_t reptDepth;
uint32_t reptIters[];
};
static struct Context *contextStack;
static struct Context *topLevelContext;
static unsigned int contextDepth = 0;
unsigned int nMaxRecursionDepth;
static unsigned int nbIncPaths = 0;
static char const *includePaths[MAXINCPATHS];
void fstk_AddIncludePath(char const *path)
{
if (path[0] == '\0')
return;
if (nbIncPaths >= MAXINCPATHS) {
yyerror("Too many include directories passed from command line");
return;
}
size_t len = strlen(path);
size_t allocSize = len + (path[len - 1] != '/') + 1;
char *str = malloc(allocSize);
if (!str) {
/* Attempt to continue without that path */
yyerror("Failed to allocate new include path: %s", strerror(errno));
return;
}
memcpy(str, path, len);
char *end = str + len - 1;
if (*end++ != '/')
*end++ = '/';
*end = '\0';
includePaths[nbIncPaths++] = str;
}
static void printDep(char const *path)
{
if (dependfile) {
fprintf(dependfile, "%s: %s\n", tzTargetFileName, path);
if (oGeneratePhonyDeps)
fprintf(dependfile, "%s:\n", path);
}
}
static bool isPathValid(char const *path)
{
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return false;
/* Reject directories */
return !S_ISDIR(statbuf.st_mode);
}
bool fstk_FindFile(char const *path, char **fullPath, size_t *size)
{
if (!*size) {
*size = 64; /* This is arbitrary, really */
*fullPath = realloc(*fullPath, *size);
if (!*fullPath)
yyerror("realloc error during include path search: %s",
strerror(errno));
}
if (*fullPath) {
for (size_t i = 0; i <= nbIncPaths; ++i) {
char const *incPath = i ? includePaths[i - 1] : "";
int len = snprintf(*fullPath, *size, "%s%s", incPath, path);
/* Oh how I wish `asnprintf` was standard... */
if (len >= *size) { /* `len` doesn't include the terminator, `size` does */
*size = len + 1;
*fullPath = realloc(*fullPath, *size);
if (!*fullPath) {
yyerror("realloc error during include path search: %s",
strerror(errno));
break;
}
len = sprintf(*fullPath, "%s%s", incPath, path);
}
if (len < 0) {
yyerror("snprintf error during include path search: %s",
strerror(errno));
} else if (isPathValid(*fullPath)) {
printDep(*fullPath);
return true;
}
}
}
errno = ENOENT;
if (oGeneratedMissingIncludes)
printDep(path);
return false;
}
bool yywrap(void)
{
if (contextStack->nbReptIters) { /* The context is a REPT block, which may loop */
contextStack->reptIters[contextStack->reptDepth - 1]++;
/* If this wasn't the last iteration, wrap instead of popping */
if (contextStack->reptIters[contextStack->reptDepth - 1]
<= contextStack->nbReptIters) {
lexer_RestartRept(contextStack->parent->lineNo);
contextStack->uniqueID = macro_UseNewUniqueID();
return false;
}
} else if (!contextStack->parent) {
return true;
}
dbgPrint("Popping context\n");
/* Free an `INCLUDE`'s path */
if (contextStack->fileNameBuf)
free(contextStack->fileNameBuf);
contextStack = contextStack->parent;
contextDepth--;
lexer_DeleteState(contextStack->child->lexerState);
/* Restore args if a macro (not REPT) saved them */
if (contextStack->child->nbReptIters == 0 && contextStack->child->macro) {
dbgPrint("Restoring macro args %p\n", contextStack->macroArgs);
macro_UseNewArgs(contextStack->macroArgs);
}
/* Free the entry and make its parent the current entry */
free(contextStack->child);
contextStack->child = NULL;
lexer_SetState(contextStack->lexerState);
macro_SetUniqueID(contextStack->uniqueID);
return false;
}
static void newContext(uint32_t reptDepth)
{
if (++contextDepth >= nMaxRecursionDepth)
fatalerror("Recursion limit (%u) exceeded", nMaxRecursionDepth);
contextStack->child = malloc(sizeof(*contextStack->child)
+ reptDepth * sizeof(contextStack->reptIters[0]));
if (!contextStack->child)
fatalerror("Failed to allocate memory for new context: %s", strerror(errno));
contextStack->lineNo = lexer_GetLineNo();
/* Link new entry to its parent so it's reachable later */
contextStack->child->parent = contextStack;
contextStack = contextStack->child;
contextStack->child = NULL;
contextStack->reptDepth = reptDepth;
}
void fstk_RunInclude(char const *path)
{
dbgPrint("Including path \"%s\"\n", path);
char *fullPath = NULL;
size_t size = 0;
if (!fstk_FindFile(path, &fullPath, &size)) {
free(fullPath);
if (oGeneratedMissingIncludes)
oFailedOnMissingInclude = true;
else
yyerror("Unable to open included file '%s': %s", path, strerror(errno));
return;
}
dbgPrint("Full path: \"%s\"\n", fullPath);
newContext(0);
contextStack->lexerState = lexer_OpenFile(fullPath);
if (!contextStack->lexerState)
fatalerror("Failed to set up lexer for file include");
lexer_SetStateAtEOL(contextStack->lexerState);
/* We're back at top-level, so most things are reset */
contextStack->uniqueID = 0;
macro_SetUniqueID(0);
contextStack->fileName = fullPath;
contextStack->fileNameBuf = fullPath;
contextStack->macro = NULL;
contextStack->nbReptIters = 0;
}
void fstk_RunMacro(char *macroName, struct MacroArgs *args)
{
dbgPrint("Running macro \"%s\"\n", macroName);
struct Symbol *macro = sym_FindSymbol(macroName);
if (!macro) {
yyerror("Macro \"%s\" not defined", macroName);
return;
}
if (macro->type != SYM_MACRO) {
yyerror("\"%s\" is not a macro", macroName);
return;
}
contextStack->macroArgs = macro_GetCurrentArgs();
newContext(0);
/* Line minus 1 because buffer begins with a newline */
contextStack->lexerState = lexer_OpenFileView(macro->macro,
macro->macroSize, macro->fileLine - 1);
if (!contextStack->lexerState)
fatalerror("Failed to set up lexer for macro invocation");
lexer_SetStateAtEOL(contextStack->lexerState);
contextStack->uniqueID = macro_UseNewUniqueID();
contextStack->fileName = macro->fileName;
contextStack->fileNameBuf = NULL;
contextStack->macro = macro;
contextStack->nbReptIters = 0;
macro_UseNewArgs(args);
}
void fstk_RunRept(uint32_t count, int32_t nReptLineNo, char *body, size_t size)
{
dbgPrint("Running REPT(%" PRIu32 ")\n", count);
if (count == 0)
return;
uint32_t reptDepth = contextStack->reptDepth;
newContext(reptDepth + 1);
contextStack->lexerState = lexer_OpenFileView(body, size, nReptLineNo);
if (!contextStack->lexerState)
fatalerror("Failed to set up lexer for macro invocation");
lexer_SetStateAtEOL(contextStack->lexerState);
contextStack->uniqueID = macro_UseNewUniqueID();
contextStack->fileName = contextStack->parent->fileName;
contextStack->fileNameBuf = NULL;
contextStack->macro = contextStack->parent->macro; /* Inherit */
contextStack->nbReptIters = count;
/* Copy all of parent's iters, and add ours */
if (reptDepth)
memcpy(contextStack->reptIters, contextStack->parent->reptIters,
sizeof(contextStack->reptIters[0]) * reptDepth);
contextStack->reptIters[reptDepth] = 1;
/* Correct our parent's line number, which currently points to the `ENDR` line */
contextStack->parent->lineNo = nReptLineNo;
}
static void printContext(FILE *stream, struct Context const *context)
{
fprintf(stream, "%s", context->fileName);
if (context->macro)
fprintf(stream, "::%s", context->macro->name);
for (size_t i = 0; i < context->reptDepth; i++)
fprintf(stream, "::REPT~%" PRIu32, context->reptIters[i]);
fprintf(stream, "(%" PRId32 ")", context->lineNo);
}
static void dumpToStream(FILE *stream)
{
struct Context *context = topLevelContext;
while (context != contextStack) {
printContext(stream, context);
fprintf(stream, " -> ");
context = context->child;
}
contextStack->lineNo = lexer_GetLineNo();
printContext(stream, contextStack);
}
void fstk_Dump(void)
{
dumpToStream(stderr);
}
char *fstk_DumpToStr(void)
{
char *str;
size_t size;
/* `open_memstream` is specified to always include a '\0' at the end of the buffer! */
FILE *stream = open_memstream(&str, &size);
if (!stream)
fatalerror("Failed to dump file stack to string: %s", strerror(errno));
dumpToStream(stream);
fclose(stream);
return str;
}
char const *fstk_GetFileName(void)
{
/* FIXME: this is awful, but all callees copy the buffer anyways */
static char fileName[_MAX_PATH + 1];
size_t remainingChars = _MAX_PATH + 1;
char *dest = fileName;
char const *src = contextStack->fileName;
#define append(...) do { \
int nbChars = snprintf(dest, remainingChars, __VA_ARGS__); \
\
if (nbChars >= remainingChars) \
fatalerror("File stack entry too large"); \
remainingChars -= nbChars; \
dest += nbChars; \
} while (0)
while (*src && --remainingChars) /* Leave room for terminator */
*dest++ = *src++;
if (remainingChars && contextStack->macro)
append("::%s", contextStack->macro->name);
for (size_t i = 0; i < contextStack->reptDepth; i++)
append("::REPT~%" PRIu32, contextStack->reptIters[i]);
*dest = '\0';
return fileName;
}
uint32_t fstk_GetLine(void)
{
return lexer_GetLineNo();
}
void fstk_Init(char *mainPath, uint32_t maxRecursionDepth)
{
topLevelContext = malloc(sizeof(*topLevelContext));
if (!topLevelContext)
fatalerror("Failed to allocate memory for initial context: %s", strerror(errno));
topLevelContext->parent = NULL;
topLevelContext->child = NULL;
topLevelContext->lexerState = lexer_OpenFile(mainPath);
if (!topLevelContext->lexerState)
fatalerror("Failed to open main file!");
lexer_SetState(topLevelContext->lexerState);
topLevelContext->uniqueID = 0;
macro_SetUniqueID(0);
topLevelContext->fileName = lexer_GetFileName();
topLevelContext->fileNameBuf = NULL;
topLevelContext->macro = NULL;
topLevelContext->nbReptIters = 0;
topLevelContext->reptDepth = 0;
contextStack = topLevelContext;
#if 0
if (maxRecursionDepth
> (SIZE_MAX - sizeof(*contextStack)) / sizeof(contextStack->reptIters[0])) {
#else
/* If this holds, then GCC raises a warning about the `if` above being dead code */
static_assert(UINT32_MAX
<= (SIZE_MAX - sizeof(*contextStack)) / sizeof(contextStack->reptIters[0]),
"Please enable recursion depth capping");
if (0) {
#endif
yyerror("Recursion depth may not be higher than %zu, defaulting to 64",
(SIZE_MAX - sizeof(*contextStack)) / sizeof(contextStack->reptIters[0]));
nMaxRecursionDepth = 64;
} else {
nMaxRecursionDepth = maxRecursionDepth;
}
}