JS_XDRNewMem(JSContext *cx, JSXDRMode mode) { JSXDRState *xdr = (JSXDRState *) JS_malloc(cx, sizeof(JSXDRMemState)); if (!xdr) return NULL; JS_XDRInitBase(xdr, mode, cx); if (mode == JSXDR_ENCODE) { if (!(MEM_BASE(xdr) = JS_malloc(cx, MEM_BLOCK))) { JS_free(cx, xdr); return NULL; } } else { /* XXXbe ok, so better not deref MEM_BASE(xdr) if not ENCODE */ MEM_BASE(xdr) = NULL; } xdr->ops = &xdrmem_ops; MEM_COUNT(xdr) = 0; MEM_LIMIT(xdr) = MEM_BLOCK; return xdr; }
/* XDRFile constructor */ JSXDRState * gpsee_XDRNewFile(JSContext *cx, JSXDRMode mode, const char *filename, FILE *f) { struct XDRFile *xdr; const char *fopen_mode; int own_file = 0; switch (mode) { case JSXDR_ENCODE: fopen_mode = "w"; break; case JSXDR_DECODE: fopen_mode = "r"; break; default: gpsee_throw(cx, "gpsee_XDRNewFile() error: invalid mode argument (%d as opposed to %d or %d)", mode, JSXDR_ENCODE, JSXDR_DECODE); return NULL; } if (!f) { if (!filename || !(f = fopen(filename, fopen_mode))) return NULL; own_file = 1; } /* Allocate our XDRState and also our internal XDRFile struct */ xdr = (struct XDRFile*) JS_malloc(cx, sizeof(struct XDRFile)); if (!xdr) { if (own_file) fclose(f); return NULL; } /* Initialize our XDRState */ JS_XDRInitBase(&xdr->xdr, mode, cx); /* Initialize our internal XDRFile members */ xdr->f = f; xdr->raw = NULL; xdr->rawlive = 0; xdr->rawlen = 0; xdr->rawsize = 0; xdr->own_file = own_file; /* Teach the new XDR object our XDROps implementation */ xdr->xdr.ops = &xdrfile_ops; /* Map file into memory if we're in read mode */ #ifdef XDR_USES_MMAP xdr->map = NULL; xdr->maplen = 0; xdr->mappos = NULL; xdr->mapend = NULL; /* Map read-only files into memory if possible */ if (mode != JSXDR_ENCODE) { /* Get the size of the file */ struct stat st; if (fstat(fileno(f), &st)) { /* Should never ever ever happen! */ dprintf("warning: fstat(\"%s\" fd=%d) failed: %m\n", filename, fileno(f)); } else { /* Map the file into memory! */ xdr->maplen = st.st_size; xdr->map = mmap(NULL, xdr->maplen, PROT_READ, MAP_PRIVATE, fileno(f), 0); if (xdr->map == MAP_FAILED) { dprintf("warning: mmap() failed: %m\n"); } xdr->mappos = xdr->map; xdr->mapend = xdr->map + xdr->maplen; } } #endif return (JSXDRState*) xdr; }