js/src/jsalloc.h

branch
TOR_BUG_9701
changeset 15
b8a032363ba2
equal deleted inserted replaced
-1:000000000000 0:0bfefde329e7
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sts=4 et sw=4 tw=99:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * JS allocation policies.
9 *
10 * The allocators here are for system memory with lifetimes which are not
11 * managed by the GC. See the comment at the top of vm/MallocProvider.h.
12 */
13
14 #ifndef jsalloc_h
15 #define jsalloc_h
16
17 #include "js/TypeDecls.h"
18 #include "js/Utility.h"
19
20 namespace js {
21
22 class ContextFriendFields;
23
24 /* Policy for using system memory functions and doing no error reporting. */
25 class SystemAllocPolicy
26 {
27 public:
28 void *malloc_(size_t bytes) { return js_malloc(bytes); }
29 void *calloc_(size_t bytes) { return js_calloc(bytes); }
30 void *realloc_(void *p, size_t oldBytes, size_t bytes) { return js_realloc(p, bytes); }
31 void free_(void *p) { js_free(p); }
32 void reportAllocOverflow() const {}
33 };
34
35 /*
36 * Allocation policy that calls the system memory functions and reports errors
37 * to the context. Since the JSContext given on construction is stored for
38 * the lifetime of the container, this policy may only be used for containers
39 * whose lifetime is a shorter than the given JSContext.
40 *
41 * FIXME bug 647103 - rewrite this in terms of temporary allocation functions,
42 * not the system ones.
43 */
44 class TempAllocPolicy
45 {
46 ContextFriendFields *const cx_;
47
48 /*
49 * Non-inline helper to call JSRuntime::onOutOfMemory with minimal
50 * code bloat.
51 */
52 JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes);
53
54 public:
55 TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :(
56 TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {}
57
58 void *malloc_(size_t bytes) {
59 void *p = js_malloc(bytes);
60 if (MOZ_UNLIKELY(!p))
61 p = onOutOfMemory(nullptr, bytes);
62 return p;
63 }
64
65 void *calloc_(size_t bytes) {
66 void *p = js_calloc(bytes);
67 if (MOZ_UNLIKELY(!p))
68 p = onOutOfMemory(nullptr, bytes);
69 return p;
70 }
71
72 void *realloc_(void *p, size_t oldBytes, size_t bytes) {
73 void *p2 = js_realloc(p, bytes);
74 if (MOZ_UNLIKELY(!p2))
75 p2 = onOutOfMemory(p2, bytes);
76 return p2;
77 }
78
79 void free_(void *p) {
80 js_free(p);
81 }
82
83 JS_FRIEND_API(void) reportAllocOverflow() const;
84 };
85
86 } /* namespace js */
87
88 #endif /* jsalloc_h */

mercurial