xref: /aosp_15_r20/external/perfetto/src/shared_lib/heap_buffer.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/public/abi/heap_buffer.h"
18 
19 #include "perfetto/protozero/scattered_heap_buffer.h"
20 #include "src/shared_lib/stream_writer.h"
21 
PerfettoHeapBufferCreate(struct PerfettoStreamWriter * w)22 struct PerfettoHeapBuffer* PerfettoHeapBufferCreate(
23     struct PerfettoStreamWriter* w) {
24   auto* shb = new protozero::ScatteredHeapBuffer(4096, 4096);
25   auto* sw = new protozero::ScatteredStreamWriter(shb);
26   shb->set_writer(sw);
27 
28   w->impl = reinterpret_cast<PerfettoStreamWriterImpl*>(sw);
29   perfetto::UpdateStreamWriter(*sw, w);
30   return reinterpret_cast<PerfettoHeapBuffer*>(shb);
31 }
32 
PerfettoHeapBufferCopyInto(struct PerfettoHeapBuffer * buf,struct PerfettoStreamWriter * w,void * dst,size_t size)33 void PerfettoHeapBufferCopyInto(struct PerfettoHeapBuffer* buf,
34                                 struct PerfettoStreamWriter* w,
35                                 void* dst,
36                                 size_t size) {
37   auto* shb = reinterpret_cast<protozero::ScatteredHeapBuffer*>(buf);
38   auto* sw = reinterpret_cast<protozero::ScatteredStreamWriter*>(w->impl);
39   sw->set_write_ptr(w->write_ptr);
40 
41   uint8_t* dst_ptr = reinterpret_cast<uint8_t*>(dst);
42   for (const protozero::ScatteredHeapBuffer::Slice& slice : shb->GetSlices()) {
43     if (size == 0) {
44       break;
45     }
46     protozero::ContiguousMemoryRange used_range = slice.GetUsedRange();
47     size_t to_copy = std::min(size, used_range.size());
48     memcpy(dst_ptr, used_range.begin, to_copy);
49     dst_ptr += to_copy;
50     size -= to_copy;
51   }
52 }
53 
PerfettoHeapBufferDestroy(struct PerfettoHeapBuffer * buf,struct PerfettoStreamWriter * w)54 void PerfettoHeapBufferDestroy(struct PerfettoHeapBuffer* buf,
55                                struct PerfettoStreamWriter* w) {
56   auto* shb = reinterpret_cast<protozero::ScatteredHeapBuffer*>(buf);
57   auto* sw = reinterpret_cast<protozero::ScatteredStreamWriter*>(w->impl);
58   delete sw;
59   delete shb;
60 }
61