this repo has no description
1// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
2#include "capi-state.h"
3
4#include <new>
5
6#include "cpython-func.h"
7#include "cpython-types.h"
8
9#include "api-handle.h"
10#include "dict-builtins.h"
11#include "globals.h"
12#include "handles-decl.h"
13#include "handles.h"
14#include "os.h"
15#include "runtime.h"
16#include "thread.h"
17#include "visitor.h"
18
19namespace py {
20
21static const word kHandleBlockSize = word{4} * kGiB;
22static const word kInitialCachesCapacity = 128;
23static const word kInitialHandlesCapacity = 256;
24
25void finalizeCAPIState(Runtime* runtime) {
26 CAPIState* state = capiState(runtime);
27 OS::freeMemory(state->handle_buffer, state->handle_buffer_size);
28 state->~CAPIState();
29}
30
31static void freeExtensionModule(PyObject* obj, const Module& module) {
32 PyModuleDef* def =
33 reinterpret_cast<PyModuleDef*>(Int::cast(module.def()).asCPtr());
34 if (def->m_free != nullptr) {
35 def->m_free(obj);
36 }
37 module.setDef(SmallInt::fromWord(0));
38 if (module.hasState()) {
39 std::free(Int::cast(module.state()).asCPtr());
40 module.setState(SmallInt::fromWord(0));
41 }
42}
43
44void freeExtensionModules(Thread* thread) {
45 HandleScope scope(thread);
46 Runtime* runtime = thread->runtime();
47 Object module_obj(&scope, NoneType::object());
48 for (PyObject* obj : *capiModules(runtime)) {
49 if (obj == nullptr) {
50 continue;
51 }
52 module_obj = ApiHandle::asObject(ApiHandle::fromPyObject(obj));
53 if (!runtime->isInstanceOfModule(*module_obj)) {
54 continue;
55 }
56 Module module(&scope, *module_obj);
57 if (module.hasDef()) {
58 freeExtensionModule(obj, module);
59 }
60 Py_DECREF(obj);
61 }
62}
63
64void initializeCAPIState(Runtime* runtime) {
65 CAPIState* state = capiState(runtime);
66 new (state) CAPIState;
67 state->caches.initialize(kInitialCachesCapacity);
68 state->handles.initialize(kInitialHandlesCapacity);
69
70 state->handle_buffer =
71 OS::allocateMemory(kHandleBlockSize, &state->handle_buffer_size);
72 state->free_handles = reinterpret_cast<FreeListNode*>(state->handle_buffer);
73
74 state->extension_objects = nullptr;
75 state->num_extension_objects = 0;
76}
77
78} // namespace py