1 : /*
2 : * Copyright 2008 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can
4 : * be found in the LICENSE file.
5 : */
6 :
7 : /*
8 : * NaCl Generic I/O interface implementation: in-memory snapshot of a file.
9 : */
10 :
11 : #include "native_client/src/include/portability.h"
12 : #include <stdio.h>
13 : #include <sys/stat.h>
14 : #include <stdlib.h>
15 :
16 : #include "native_client/src/shared/gio/gio.h"
17 :
18 : struct GioVtbl const kGioMemoryFileSnapshotVtbl = {
19 : GioMemoryFileRead,
20 : GioMemoryFileWrite,
21 : GioMemoryFileSeek,
22 : GioMemoryFileFlush,
23 : GioMemoryFileClose,
24 : GioMemoryFileSnapshotDtor,
25 : };
26 :
27 :
28 : int GioMemoryFileSnapshotCtor(struct GioMemoryFileSnapshot *self,
29 12 : char *fn) {
30 : FILE *iop;
31 : struct stat stbuf;
32 : char *buffer;
33 :
34 12 : ((struct Gio *) self)->vtbl = (struct GioVtbl *) NULL;
35 12 : if (0 == (iop = fopen(fn, "rb"))) {
36 1 : return 0;
37 : }
38 11 : if (fstat(fileno(iop), &stbuf) == -1) {
39 0 : abort0:
40 0 : fclose(iop);
41 0 : return 0;
42 : }
43 11 : if (0 == (buffer = malloc(stbuf.st_size))) {
44 0 : goto abort0;
45 : }
46 11 : if (fread(buffer, 1, stbuf.st_size, iop) != (size_t) stbuf.st_size) {
47 0 : abort1:
48 0 : free(buffer);
49 0 : goto abort0;
50 : }
51 11 : if (GioMemoryFileCtor(&self->base, buffer, stbuf.st_size) == 0) {
52 0 : goto abort1;
53 : }
54 11 : (void) fclose(iop);
55 :
56 11 : ((struct Gio *) self)->vtbl = &kGioMemoryFileSnapshotVtbl;
57 11 : return 1;
58 : }
59 :
60 :
61 11 : void GioMemoryFileSnapshotDtor(struct Gio *vself) {
62 : struct GioMemoryFileSnapshot *self = (struct GioMemoryFileSnapshot *)
63 11 : vself;
64 11 : free(self->base.buffer);
65 11 : GioMemoryFileDtor(vself);
66 11 : }
|