summaryrefslogtreecommitdiffstats
path: root/js/src/frontend/FrontendContext.h
blob: e7fc30ca7049ba5d47d73f81ac7ef220d7fa38ab (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef frontend_FrontendContext_h
#define frontend_FrontendContext_h

#include "mozilla/Assertions.h"  // MOZ_ASSERT
#include "mozilla/Attributes.h"  // MOZ_STACK_CLASS
#include "mozilla/Maybe.h"       // mozilla::Maybe

#include <stddef.h>  // size_t

#include "js/AllocPolicy.h"  // SystemAllocPolicy, AllocFunction
#include "js/ErrorReport.h"  // JSErrorCallback, JSErrorFormatString
#include "js/Stack.h"  // JS::NativeStackSize, JS::NativeStackLimit, JS::NativeStackLimitMax
#include "js/Vector.h"          // Vector
#include "vm/ErrorReporting.h"  // CompileError
#include "vm/MallocProvider.h"  // MallocProvider
#include "vm/SharedScriptDataTableHolder.h"  // js::SharedScriptDataTableHolder, js::globalSharedScriptDataTableHolder

struct JSContext;

namespace js {

class FrontendContext;

namespace frontend {
class NameCollectionPool;
}  // namespace frontend

struct FrontendErrors {
  FrontendErrors() = default;
  // Any errors or warnings produced during compilation. These are reported
  // when finishing the script.
  mozilla::Maybe<CompileError> error;
  Vector<CompileError, 0, SystemAllocPolicy> warnings;
  bool overRecursed = false;
  bool outOfMemory = false;
  bool allocationOverflow = false;

  // Set to true if the compilation is initiated with extra bindings, but
  // the script has no reference to the bindings, and the script should be
  // compiled without the extra bindings.
  //
  // See frontend::CompileGlobalScriptWithExtraBindings.
  bool extraBindingsAreNotUsed = false;

  bool hadErrors() const {
    return outOfMemory || overRecursed || allocationOverflow ||
           extraBindingsAreNotUsed || error;
  }

  void clearErrors();
  void clearWarnings();
};

class FrontendAllocator : public MallocProvider<FrontendAllocator> {
 private:
  FrontendContext* const fc_;

 public:
  explicit FrontendAllocator(FrontendContext* fc) : fc_(fc) {}

  void* onOutOfMemory(js::AllocFunction allocFunc, arena_id_t arena,
                      size_t nbytes, void* reallocPtr = nullptr);
  void reportAllocationOverflow();
};

class FrontendContext {
 private:
  FrontendAllocator alloc_;
  js::FrontendErrors errors_;

  // NameCollectionPool can be either:
  //   * owned by this FrontendContext, or
  //   * borrowed from JSContext
  frontend::NameCollectionPool* nameCollectionPool_;
  bool ownNameCollectionPool_;

  js::SharedScriptDataTableHolder* scriptDataTableHolder_;

  // Limit pointer for checking native stack consumption.
  //
  // The pointer is calculated based on the stack base of the current thread
  // except for JS::NativeStackLimitMax. Once such value is set, this
  // FrontendContext can be used only in the thread.
  //
  // In order to enforce this thread rule, setNativeStackLimitThread should
  // be called when setting the value, and assertNativeStackLimitThread should
  // be called at each entry-point that might make use of this field.
  JS::NativeStackLimit stackLimit_ = JS::NativeStackLimitMax;

#ifdef DEBUG
  // The thread ID where the native stack limit is set.
  mozilla::Maybe<size_t> stackLimitThreadId_;

  // The stack pointer where the AutoCheckRecursionLimit check is performed
  // last time.
  void* previousStackPointer_ = nullptr;
#endif

 protected:
  // (optional) Current JSContext to support main-thread-specific
  // handling for error reporting, GC, and memory allocation.
  //
  // Set by setCurrentJSContext.
  JSContext* maybeCx_ = nullptr;

 public:
  FrontendContext()
      : alloc_(this),
        nameCollectionPool_(nullptr),
        ownNameCollectionPool_(false),
        scriptDataTableHolder_(&js::globalSharedScriptDataTableHolder) {}
  ~FrontendContext();

  void setStackQuota(JS::NativeStackSize stackSize);
  JS::NativeStackLimit stackLimit() const { return stackLimit_; }

  bool allocateOwnedPool();

  frontend::NameCollectionPool& nameCollectionPool() {
    MOZ_ASSERT(
        nameCollectionPool_,
        "Either allocateOwnedPool or setCurrentJSContext must be called");
    return *nameCollectionPool_;
  }

  js::SharedScriptDataTableHolder* scriptDataTableHolder() {
    MOZ_ASSERT(scriptDataTableHolder_);
    return scriptDataTableHolder_;
  }

  FrontendAllocator* getAllocator() { return &alloc_; }

  // Use the given JSContext's for:
  //   * js::frontend::NameCollectionPool for reusing allocation
  //   * js::SharedScriptDataTableHolder for de-duplicating bytecode
  //     within given runtime
  //   * Copy the native stack limit from the JSContext
  //
  // And also this JSContext can be retrieved by maybeCurrentJSContext below.
  void setCurrentJSContext(JSContext* cx);

  // Returns JSContext if any.
  //
  // This can be used only for:
  //   * Main-thread-specific operation, such as operating on JSAtom
  //   * Optional operation, such as providing better error message
  JSContext* maybeCurrentJSContext() { return maybeCx_; }

  enum class Warning { Suppress, Report };

  // Returns false if the error cannot be converted (such as due to OOM). An
  // error might still be reported to the given JSContext. Returns true
  // otherwise.
  bool convertToRuntimeError(JSContext* cx, Warning warning = Warning::Report);

  mozilla::Maybe<CompileError>& maybeError() { return errors_.error; }
  Vector<CompileError, 0, SystemAllocPolicy>& warnings() {
    return errors_.warnings;
  }

  // Report CompileErrors
  void reportError(js::CompileError&& err);
  bool reportWarning(js::CompileError&& err);

  // Report FrontendAllocator errors
  void* onOutOfMemory(js::AllocFunction allocFunc, arena_id_t arena,
                      size_t nbytes, void* reallocPtr = nullptr);
  void onAllocationOverflow();

  void onOutOfMemory();
  void onOverRecursed();

  void recoverFromOutOfMemory();

  const JSErrorFormatString* gcSafeCallback(JSErrorCallback callback,
                                            void* userRef,
                                            const unsigned errorNumber);

  // Status of errors reported to this FrontendContext
  bool hadOutOfMemory() const { return errors_.outOfMemory; }
  bool hadOverRecursed() const { return errors_.overRecursed; }
  bool hadAllocationOverflow() const { return errors_.allocationOverflow; }
  bool extraBindingsAreNotUsed() const {
    return errors_.extraBindingsAreNotUsed;
  }
  void reportExtraBindingsAreNotUsed() {
    errors_.extraBindingsAreNotUsed = true;
  }
  void clearNoExtraBindingReferencesFound() {
    errors_.extraBindingsAreNotUsed = false;
  }
  bool hadErrors() const;
  // Clear errors and warnings.
  void clearErrors();
  // Clear warnings only.
  void clearWarnings();

#ifdef __wasi__
  void incWasiRecursionDepth();
  void decWasiRecursionDepth();
  bool checkWasiRecursionLimit();
#endif  // __wasi__

#ifdef DEBUG
  void setNativeStackLimitThread();
  void assertNativeStackLimitThread();
#endif

#ifdef DEBUG
  void checkAndUpdateFrontendContextRecursionLimit(void* sp);
#endif

 private:
  void ReportOutOfMemory();
  void addPendingOutOfMemory();
};

// Automatically report any pending exception when leaving the scope.
class MOZ_STACK_CLASS AutoReportFrontendContext : public FrontendContext {
  // The target JSContext to report the errors to.
  JSContext* cx_;

  Warning warning_;

 public:
  explicit AutoReportFrontendContext(JSContext* cx,
                                     Warning warning = Warning::Report)
      : cx_(cx), warning_(warning) {
    setCurrentJSContext(cx_);
    MOZ_ASSERT(cx_ == maybeCx_);
  }

  ~AutoReportFrontendContext() {
    if (cx_) {
      convertToRuntimeErrorAndClear();
    }
  }

  void clearAutoReport() { cx_ = nullptr; }

  bool convertToRuntimeErrorAndClear() {
    bool result = convertToRuntimeError(cx_, warning_);
    cx_ = nullptr;
    return result;
  }
};

/*
 * Explicitly report any pending exception before leaving the scope.
 *
 * Before an instance of this class leaves the scope, you must call either
 * failure() (if there are exceptions to report) or ok() (if there are no
 * exceptions to report).
 */
class ManualReportFrontendContext : public FrontendContext {
  JSContext* cx_;
#ifdef DEBUG
  bool handled_ = false;
#endif

 public:
  explicit ManualReportFrontendContext(JSContext* cx) : cx_(cx) {
    setCurrentJSContext(cx_);
  }

  ~ManualReportFrontendContext() { MOZ_ASSERT(handled_); }

  void ok() {
#ifdef DEBUG
    handled_ = true;
#endif
  }

  void failure() {
#ifdef DEBUG
    handled_ = true;
#endif
    convertToRuntimeError(cx_);
  }
};

// Create function for FrontendContext, which is manually allocated and
// exclusively owned.
extern FrontendContext* NewFrontendContext();

// Destroy function for FrontendContext, which was allocated with
// NewFrontendContext.
extern void DestroyFrontendContext(FrontendContext* fc);

}  // namespace js

#endif /* frontend_FrontendContext_h */