summaryrefslogtreecommitdiff
path: root/nasmlib/file.c
blob: 62b854ded2ff0c7c3b62815742320c28088d8662 (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
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 1996-2017 The NASM Authors - All Rights Reserved
 *   See the file AUTHORS included with the NASM distribution for
 *   the specific copyright holders.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following
 *   conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ----------------------------------------------------------------------- */

#include "file.h"

void nasm_read(void *ptr, size_t size, FILE *f)
{
    size_t n = fread(ptr, 1, size, f);
    if (ferror(f)) {
        nasm_fatal("unable to read input: %s", strerror(errno));
    } else if (n != size || feof(f)) {
        nasm_fatal("fatal short read on input");
    }
}

void nasm_write(const void *ptr, size_t size, FILE *f)
{
    size_t n = fwrite(ptr, 1, size, f);
    if (n != size || ferror(f) || feof(f))
        nasm_fatal("unable to write output: %s", strerror(errno));
}

void fwriteint16_t(uint16_t data, FILE * fp)
{
    data = cpu_to_le16(data);
    nasm_write(&data, 2, fp);
}

void fwriteint32_t(uint32_t data, FILE * fp)
{
    data = cpu_to_le32(data);
    nasm_write(&data, 4, fp);
}

void fwriteint64_t(uint64_t data, FILE * fp)
{
    data = cpu_to_le64(data);
    nasm_write(&data, 8, fp);
}

void fwriteaddr(uint64_t data, int size, FILE * fp)
{
    data = cpu_to_le64(data);
    nasm_write(&data, size, fp);
}

void fwritezero(off_t bytes, FILE *fp)
{
    size_t blksize;

#ifdef os_ftruncate
    if (bytes >= BUFSIZ && !ferror(fp) && !feof(fp)) {
	off_t pos = ftello(fp);
	if (pos != (off_t)-1) {
            off_t end = pos + bytes;
	    if (!fflush(fp) && !os_ftruncate(fileno(fp), end)) {
                fseeko(fp, 0, SEEK_END);
                pos = ftello(fp);
                if (pos != (off_t)-1)
                    bytes = end - pos; /* This SHOULD be zero */
            }
	}
    }
#endif

    while (bytes > 0) {
	blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;

	nasm_write(zero_buffer, blksize, fp);
	bytes -= blksize;
    }
}

#ifdef _WIN32

/*
 * On Windows, we want to use _wfopen(), as fopen() has a much smaller limit
 * on the path length that it supports.
 *
 * Previously we tried to prefix the path name with \\?\ in order to
 * let the Windows kernel know that we are not limited to PATH_MAX
 * characters, but it breaks relative paths among other things, and
 * apparently Windows 10 contains a registry option to override this
 * limit anyway. One day maybe they will even implement UTF-8 as byte
 * characters so we can use the standard file API even on this OS.
 */

os_filename os_mangle_filename(const char *filename)
{
    mbstate_t ps;
    size_t wclen;
    wchar_t *buf;
    const char *p;

    /*
     * Note: mbsrtowcs() return (size_t)-1 on error, otherwise
     * the length of the string *without* final NUL in wchar_t
     * units. Thus we add 1 for the final NUL; the error value
     * now becomes 0.
     */
    memset(&ps, 0, sizeof ps);  /* Begin in the initial state */
    p = filename;
    wclen = mbsrtowcs(NULL, &p, 0, &ps) + 1;
    if (!wclen)
        return NULL;

    buf = nasm_malloc(wclen * sizeof(wchar_t));

    memset(&ps, 0, sizeof ps);  /* Begin in the initial state */
    p = filename;
    if (mbsrtowcs(buf, &p, wclen, &ps) + 1 != wclen || p) {
        nasm_free(buf);
        return NULL;
    }

    return buf;
}

#endif

void nasm_set_binary_mode(FILE *f)
{
	os_set_binary_mode(f);
}

FILE *nasm_open_read(const char *filename, enum file_flags flags)
{
    FILE *f = NULL;
    os_filename osfname;

    osfname = os_mangle_filename(filename);
    if (osfname) {
        os_fopenflag fopen_flags[4];
        memset(fopen_flags, 0, sizeof fopen_flags);

        fopen_flags[0] = 'r';
        fopen_flags[1] = (flags & NF_TEXT) ? 't' : 'b';

#if defined(__GLIBC__) || defined(__linux__)
        /*
         * Try to open this file with memory mapping for speed, unless we are
         * going to do it "manually" with nasm_map_file()
         */
        if (!(flags & NF_FORMAP))
            fopen_flags[2] = 'm';
#endif

        while (true) {
            f = os_fopen(osfname, fopen_flags);
            if (f || errno != EINVAL || !fopen_flags[2])
                break;

            /* We got EINVAL but with 'm'; try again without 'm' */
            fopen_flags[2] = '\0';
        }

        os_free_filename(osfname);
    }

    if (!f && (flags & NF_FATAL))
        nasm_fatalf(ERR_NOFILE, "unable to open input file: `%s': %s",
                    filename, strerror(errno));

    return f;
}

FILE *nasm_open_write(const char *filename, enum file_flags flags)
{
    FILE *f = NULL;
    os_filename osfname;

    osfname = os_mangle_filename(filename);
    if (osfname) {
        os_fopenflag fopen_flags[3];

        fopen_flags[0] = 'w';
        fopen_flags[1] = (flags & NF_TEXT) ? 't' : 'b';
        fopen_flags[2] = '\0';

        f = os_fopen(osfname, fopen_flags);
        os_free_filename(osfname);
    }

    if (!f && (flags & NF_FATAL))
        nasm_fatalf(ERR_NOFILE, "unable to open output file: `%s': %s",
                    filename, strerror(errno));

    switch (flags & NF_BUF_MASK) {
    case NF_IONBF:
        setvbuf(f, NULL, _IONBF, 0);
        break;
    case NF_IOLBF:
        setvbuf(f, NULL, _IOLBF, 0);
        break;
    case NF_IOFBF:
        setvbuf(f, NULL, _IOFBF, 0);
        break;
    default:
        break;
    }

    return f;
}

/* The appropriate "rb" strings for os_fopen() */
static const os_fopenflag fopenflags_rb[3] = { 'r', 'b', 0 };

/*
 * Report the existence of a file
 */
bool nasm_file_exists(const char *filename)
{
#ifndef os_access
    FILE *f;
#endif
    os_filename osfname;
    bool exists;

    osfname = os_mangle_filename(filename);
    if (!osfname)
        return false;

#ifdef os_access
    exists = os_access(osfname, R_OK) == 0;
#else
    f = os_fopen(osfname, fopenflags_rb);
    exists = f != NULL;
    if (f)
        fclose(f);
#endif

    os_free_filename(osfname);
    return exists;
}

/*
 * Report the file size of an open file.  This MAY move the file pointer.
 */
off_t nasm_file_size(FILE *f)
{
    off_t where, end;
    os_struct_stat st;

    if (!os_fstat(fileno(f), &st) && S_ISREG(st.st_mode))
        return st.st_size;

    /* Do it the hard way... this tests for seekability */

    if (fseeko(f, 0, SEEK_CUR))
        goto fail;              /* Not seekable, don't even try */

    where = ftello(f);
    if (where == (off_t)-1)
        goto fail;

    if (fseeko(f, 0, SEEK_END))
        goto fail;

    end = ftello(f);
    if (end == (off_t)-1)
        goto fail;

    /*
     * Move the file pointer back. If this fails, this is probably
     * not a plain file.
     */
    if (fseeko(f, where, SEEK_SET))
        goto fail;

    return end;

fail:
    return -1;
}

/*
 * Report file size given pathname
 */
off_t nasm_file_size_by_path(const char *pathname)
{
    os_filename osfname;
    off_t len = -1;
    os_struct_stat st;
    FILE *fp;

    osfname = os_mangle_filename(pathname);

    if (!os_stat(osfname, &st) && S_ISREG(st.st_mode))
        len = st.st_size;

    fp = os_fopen(osfname, fopenflags_rb);
    if (fp) {
        len = nasm_file_size(fp);
        fclose(fp);
    }

    return len;
}

/*
 * Report the timestamp on a file, returns true if successful
 */
bool nasm_file_time(time_t *t, const char *pathname)
{
#ifdef os_stat
    os_filename osfname;
    os_struct_stat st;
    bool rv = false;

    osfname = os_mangle_filename(pathname);
    if (!osfname)
        return false;

    rv = !os_stat(osfname, &st);
    *t = st.st_mtime;
    os_free_filename(osfname);

    return rv;
#else
    return false;               /* No idea how to do this on this OS */
#endif
}