1/*
2 * Copyright (c) 2023 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_MEM_ALLOCATION_INSPECTOR_H
17#define ECMASCRIPT_MEM_ALLOCATION_INSPECTOR_H
18
19#include "ecmascript/common.h"
20
21namespace panda::ecmascript {
22class Heap;
23class HeapSampling;
24
25class AllocationInspector {
26public:
27    explicit AllocationInspector(Heap *heap, uint64_t rate, HeapSampling *profiler)
28        : rate_(rate),
29          profiler_(profiler),
30          heap_(heap) {}
31    ~AllocationInspector() = default;
32    NO_MOVE_SEMANTIC(AllocationInspector);
33    NO_COPY_SEMANTIC(AllocationInspector);
34
35    // When total at least *rate_* bytes have been allocated, this func can be called.
36    // *object* is an address pointing to allocated and uninitialized memory.
37    // *size* is the dimension of allocation corresponding to `object`.
38    void Step([[maybe_unused]] Address object, [[maybe_unused]] size_t size);
39    size_t GetNextStepSize();
40
41private:
42    const uint64_t rate_;
43    [[maybe_unused]] HeapSampling *const profiler_;
44    [[maybe_unused]] Heap *const heap_;
45};
46
47// each space has an allocationCounter which inspector can be added to.
48class AllocationCounter final {
49public:
50    AllocationCounter() = default;
51    ~AllocationCounter() = default;
52
53    void AddAllocationInspector(AllocationInspector *inspector);
54    void ClearAllocationInspector();
55    void AdvanceAllocationInspector(size_t allocated);
56    void InvokeAllocationInspector(Address object, size_t objectSize, size_t alignedObjectSize);
57
58    bool IsActive() const
59    {
60        return inspector_ != nullptr;
61    }
62
63    size_t NextBytes() const
64    {
65        return nextCounter_ - currentCounter_;
66    }
67
68private:
69    AllocationInspector *inspector_ = nullptr;
70    size_t currentCounter_ = 0;
71    size_t nextCounter_ = 0;
72};
73} // namespace panda::ecmascript
74
75#endif