1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H
17#define ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H
18
19#include <unordered_map>
20
21#include "ecmascript/js_thread.h"
22#include "ecmascript/mem/visitor.h"
23
24namespace panda::ecmascript {
25class EcmaVM;
26
27class SnapshotEnv final {
28public:
29    explicit SnapshotEnv(EcmaVM *vm) : vm_(vm) {}
30    ~SnapshotEnv() = default;
31
32    void AddGlobalConstToMap();
33
34    void ClearEnvMap()
35    {
36        rootObjectMap_.clear();
37    }
38
39    void Iterate(const RootVisitor &v, VMRootVisitType type);
40
41    void Push(JSTaggedType objectAddr, uint32_t index)
42    {
43        if (multiThreadCheckValue_.exchange(JSThread::GetCurrentThreadId()) != 0) {
44            LOG_ECMA(FATAL) << "SnapshotEnv push multi-thread check fail, thread id: " << multiThreadCheckValue_;
45        }
46        rootObjectMap_.emplace(objectAddr, index);
47        multiThreadCheckValue_ = 0;
48    }
49
50    void Remove(JSTaggedType objectAddr)
51    {
52        if (multiThreadCheckValue_.exchange(JSThread::GetCurrentThreadId()) != 0) {
53            LOG_ECMA(FATAL) << "SnapshotEnv remove multi-thread check fail, thread id: " << multiThreadCheckValue_;
54        }
55        rootObjectMap_.erase(objectAddr);
56        multiThreadCheckValue_ = 0;
57    }
58
59    uint32_t FindEnvObjectIndex(JSTaggedType objectAddr) const
60    {
61        if (rootObjectMap_.find(objectAddr) != rootObjectMap_.end()) {
62            return rootObjectMap_.find(objectAddr)->second;
63        }
64        return MAX_UINT_32;
65    }
66
67    JSTaggedType RelocateRootObjectAddr(uint32_t index);
68
69    static constexpr size_t MAX_UINT_32 = 0xFFFFFFFF;
70
71private:
72    NO_MOVE_SEMANTIC(SnapshotEnv);
73    NO_COPY_SEMANTIC(SnapshotEnv);
74
75    void InitGlobalConst();
76    void InitGlobalEnv();
77
78    EcmaVM *vm_;
79    std::unordered_map<JSTaggedType, uint32_t> rootObjectMap_;
80    std::atomic<uint32_t> multiThreadCheckValue_ {0};
81};
82}  // namespace panda::ecmascript
83#endif  // ECMASCRIPT_SNAPSHOT_MEM_SNAPSHOT_ENV_H
84