aboutsummaryrefslogtreecommitdiff
path: root/compiler/misc.c
blob: 4a12b82264fb5bd148397746b99bf4fce30d29ed (plain)
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414

/*

  misc.c -- Miscellaneous internal utility functons.

  Copyright © 2011-2017 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <errno.h>
#include <string.h>

#include "misc.h"
#include "platform.h"

static void linprobset_expand(LinProbSet *lps);


/**
 * Like realloc(), but frees the pointer on error.
 */
void *try_realloc(void *p, size_t size)
{
    char *np = realloc(p, size);
    if (np) return np;
    
    /* Error */
    free(p);
    return NULL;
}

/* Standard implementation of strndup, which is from C99 */
char *lrl_strndup(const char *s, size_t len)
{
    char *dup = malloc(len+1);
    
    if (!dup) return NULL;
    
    memcpy(dup, s, len);
    dup[len] = '\0';
    return dup;
}

/* Standard implementation of strdup, which is from C99 */
char *lrl_strdup(const char *s)
{
    size_t len = strlen(s);
    return lrl_strndup(s, len);
}

/**
 * Hashes sequence of bytes. Intended to be fast, but NOT secure against
 * pre-image attacks etc.
 */
LRLHashCode hash_bytes(const unsigned char *bytes, size_t length)
{
#if LRL_HASH_BITS == 64
#define LRL_HASH_INIT  0xFEDCBA9876543210UL
#define LRL_HASH_A     53
#define LRL_HASH_B     0x31415UL
#define LRL_HASH_C     13
#define LRL_HASH_D     57
#define LRL_HASH_E     27
#define LRL_HASH_F     17

#elif LRL_HASH_BITS == 32
#define LRL_HASH_INIT  0xFDB97531UL
#define LRL_HASH_A     25
#define LRL_HASH_B     0x31415UL
#define LRL_HASH_C     7
#define LRL_HASH_D     27
#define LRL_HASH_E     13
#define LRL_HASH_F     9

#else
#error Unsupported value of LRL_HASH_BITS
#endif
    /* TODO replace with some proven hash function */
    LRLHashCode h = LRL_HASH_INIT;
    int i;
    for (i = 0; i < 2; i++) {
        size_t l = length;
        const unsigned char *byte = bytes;
        while (l--) {
            LRLHashCode b = *(byte++);
            b ^= (b-1) << LRL_HASH_A;
            h -= LRL_HASH_B;
            h += b;
            h += h >> LRL_HASH_C;
            h ^= b << LRL_HASH_D;
            b += h;
            h += b >> LRL_HASH_E;
        }
        h += h << LRL_HASH_F;
    }
    return h;
}

/**
 * Hashes a string. See hash_bytes()
 */
LRLHashCode hash_name(const char *name, size_t length)
{
    return hash_bytes((const unsigned char*)name, length);
}

/**
 * Combines two hashes by concatenating them and hashing the result.
 */
LRLHashCode hash_merge(LRLHashCode a, LRLHashCode b)
{
#if LRL_HASH_BITS == 64
    unsigned char bytes[16];
    bytes[0] = a & 0xff;
    bytes[1] = (a >> 8) & 0xff;
    bytes[2] = (a >> 16) & 0xff;
    bytes[3] = (a >> 24) & 0xff;
    bytes[4] = (a >> 32) & 0xff;
    bytes[5] = (a >> 40) & 0xff;
    bytes[6] = (a >> 48) & 0xff;
    bytes[7] = (a >> 56) & 0xff;
    
    bytes[8] = b & 0xff;
    bytes[9] = (b >> 8) & 0xff;
    bytes[10] = (b >> 16) & 0xff;
    bytes[11] = (b >> 24) & 0xff;
    bytes[12] = (b >> 32) & 0xff;
    bytes[13] = (b >> 40) & 0xff;
    bytes[14] = (b >> 48) & 0xff;
    bytes[15] = (b >> 56) & 0xff;
#else
    unsigned char bytes[8];
    bytes[0] = a & 0xff;
    bytes[1] = (a >> 8) & 0xff;
    bytes[2] = (a >> 16) & 0xff;
    bytes[3] = (a >> 24) & 0xff;
    
    bytes[4] = b & 0xff;
    bytes[5] = (b >> 8) & 0xff;
    bytes[6] = (b >> 16) & 0xff;
    bytes[7] = (b >> 24) & 0xff;
#endif
    return hash_bytes(bytes, sizeof(bytes));
}

/**
 * Forces initialization of a linearly probed set. The "bits" parameter
 * specify how many bits are used for addressing initially, and also controls
 * the size of the set (size = 2^bits).
 *
 * The "bits" parameter must be at least 1.
 *
 * Note that if the structure has been memset/calloc'ed, the initialization is
 * done automatically on the first linprobset_add_hashcode() call.
 */
void linprobset_init(LinProbSet *lps, size_t bits)
{
    lps->size = bits;
    lps->set = calloc(1<<bits, sizeof(LRLHashCode));
}

/**
 * Adds a hashcode to a set of hashcodes. Linear probing is used.
 * Returns 1 if the item existed before the call, and 0 otherwise.
 *
 * Note that 0 is not a valid value to be added.
 */
int linprobset_add_hashcode(LinProbSet *lps, LRLHashCode hashcode)
{
    size_t max, steps;
    LRLHashCode *p, *last;
    
    if (!lps->set) {
        linprobset_init(lps, 2);
    }
    
  restart:
    max = ((1 << lps->size) - 1);
    p = &lps->set[hashcode & max];
    last = &lps->set[max];
    steps = 0;
    for (;;) {
        LRLHashCode cell = *p;
        if (cell == hashcode) return 1; /* Already exists */
        if (cell == 0) {
            /* Add */
            *p = hashcode;
            if (steps >> (lps->size-1)) {
                linprobset_expand(lps);
            }
            return 0;
        }
        if (++p > last) {
            p = lps->set; /* Wrap around */
            if (steps > max) {
                linprobset_expand(lps);
                goto restart;
            }
        }
        steps++;
    }
}

/**
 * Expands the set to twice its size. Then reorganizes
 * the set according to the new size.
 */
static void linprobset_expand(LinProbSet *lps)
{
    size_t max, oldsize;
    short limit;
    LRLHashCode *p, *last;
    
    oldsize = (1<<lps->size);
    lps->size++;
    lps->set = realloc(lps->set, (1<<lps->size)*sizeof(LRLHashCode));
    memset(&lps->set[oldsize], 0, oldsize*sizeof(LRLHashCode));
    
    max = ((1 << lps->size) - 1);
    last = &lps->set[max];
    limit = 10;
    for (p = lps->set; p <= last;) {
        LRLHashCode a;
        
        a = *p;
        if (a) {
            LRLHashCode *q = &lps->set[a & max];
          try_next:
            if (p != q) {
                LRLHashCode b = *q;
                if ((a & max) != (b & max)) {
                    /* Possible to switch here */
                    *q = a;
                    *p = b;
                    if (b && --limit) {
                        continue; /* Check this one again */
                    }
                } else {
                    if (++q > last) q = lps->set; /* Wrap around */
                    goto try_next;
                }
            }
        }
        limit = 10;
        p++;
    }
}

/**
 * Moves the given string pointer past all path separators.
 */
void skip_path_sep(const char **path)
{
    *path += strspn(*path, "/\\");
}

/**
 * Returns the end of the first path element in the given string.
 */
const char *end_of_path_elem(const char *path)
{
    return path + strcspn(path, "/\\");
}

/**
 * Creates the output filename based on the source filename, and an optional
 * output directory. The is_exec parameter controls whether the object file
 * or executable filename is returned.
 */
char *get_output_filename(const char *source_filename, const char *outdir,
                          int is_exec)
{
    const char *end;
    const char *ext;
    size_t dirlen = (outdir ? strlen(outdir)+1 : 0);
    size_t extlen, baselen;
    char *output;
    
    /* Determine start of the name of the file */
    const char *basename = strrchr(source_filename, '/');
    const char *basename_win = strrchr(source_filename, '\\');
    if ((uintptr_t)basename_win > (uintptr_t)basename) {
        basename = basename_win;
    } else if (!basename) {
        basename = source_filename;
    }
    
    /* The "name" of the input ends at the first dot */
    end = strchr(basename, '.');
    if (!end) end = basename + strlen(basename);
    
    if (is_exec) {
        /* TODO should .exe be added on Windows, and where in the code? */
        ext = "";
        extlen = 0;
    } else {
        ext = ".o";
        extlen = 2;
    }
    
    baselen = end-source_filename;
    output = malloc(dirlen+baselen+extlen+1);
    if (outdir) {
        memcpy(output, outdir, dirlen-1);
        output[dirlen-1] = PATHSEP[0];
    }
    memcpy(output+dirlen, source_filename, baselen);
    memcpy(output+dirlen+baselen, ext, extlen);
    output[dirlen+baselen+extlen] = '\0';
    return output;
}

/**
 * Reads from a file until EOF, and then null-terminates the result.
 * On error (or if the file is a directory), it returns NULL.
 */
char *file_get_contents(FILE *file)
{
    size_t capacity, size;
    char *contents;
    
    if (!check_not_dir(file)) return NULL;
    
    size = 0;
    capacity = 4096;
    contents = malloc(capacity+1);
    if (!contents) return NULL;
    
    for (;;) {
        /* Fill the buffer with data */
        size_t chunk_size = capacity-size;
        size_t numread = fread(&contents[size], 1, chunk_size, file);
        
        size += numread;
        
        /* If wasn't filled, then we reached then end */
        if (numread != chunk_size) break;
        
        /* Double the buffer size */
        if (capacity*2 < capacity) {
            /* Don't try to allocate more than 50% of the address space */
            free(contents);
            errno = EOVERFLOW;
            return NULL;
        }
        capacity *= 2;
        contents = try_realloc(contents, capacity);
        if (!contents) goto end;
    }
    
    contents[size] = '\0';
    contents = realloc(contents, size+1);
  end:
    return contents;
}

/**
 * Reads a file or from stdin if filename is "-". The file contents are
 * null-terminated. On error (or if the file is a directory), it returns NULL.
 */
char *read_input(const char *filename)
{
    if (!strcmp(filename, "-")) {
        /* Read from standard in */
        return file_get_contents(stdin);
    } else {
        /* Read from a file */
        FILE *f = fopen(filename, "rb");
        if (f) {
            char *contents = file_get_contents(f);
            fclose(f);
            return contents;
        } else {
            return NULL;
        }
    }
}

/**
 * Aborts the program with an error message.
 * Use only for "impossible" errors.
 */
NORETURN void fail(const char *error_id)
{
    volatile short *c = (short*)0xabc;
    
    fprintf(stderr, "lrlc: internal error (this is a bug!): %s\n", error_id);
    
    /* Unlike abort(), this is regarded as a crash, which means we get nice
       debugging things like stack traces and core dumps. */
    *c;
    
    /* If we fail to crash */
    abort();
}