1/*
2 * Copyright (C) 2018 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 "src/tracing/core/trace_writer_for_testing.h"
18
19#include "perfetto/base/logging.h"
20#include "perfetto/base/utils.h"
21
22#include "perfetto/protozero/message.h"
23
24#include "perfetto/trace/trace_packet.pbzero.h"
25
26namespace perfetto {
27
28TraceWriterForTesting::TraceWriterForTesting()
29    : delegate_(static_cast<size_t>(base::kPageSize)), stream_(&delegate_) {
30  delegate_.set_writer(&stream_);
31  cur_packet_.reset(new protos::pbzero::TracePacket());
32  cur_packet_->Finalize();  // To avoid the DCHECK in NewTracePacket().
33}
34
35TraceWriterForTesting::~TraceWriterForTesting() {}
36
37void TraceWriterForTesting::Flush(std::function<void()> callback) {
38  // Flush() cannot be called in the middle of a TracePacket.
39  PERFETTO_CHECK(cur_packet_->is_finalized());
40
41  if (callback)
42    callback();
43}
44
45std::unique_ptr<protos::TracePacket> TraceWriterForTesting::ParseProto() {
46  PERFETTO_CHECK(cur_packet_->is_finalized());
47  size_t chunk_size_ = base::kPageSize;
48  auto packet = std::unique_ptr<protos::TracePacket>(new protos::TracePacket());
49  size_t msg_size =
50      delegate_.chunks().size() * chunk_size_ - stream_.bytes_available();
51  std::unique_ptr<uint8_t[]> buffer = delegate_.StitchChunks(msg_size);
52  if (!packet->ParseFromArray(buffer.get(), static_cast<int>(msg_size)))
53    return nullptr;
54  return packet;
55}
56
57TraceWriterForTesting::TracePacketHandle
58TraceWriterForTesting::NewTracePacket() {
59  // If we hit this, the caller is calling NewTracePacket() without having
60  // finalized the previous packet.
61  PERFETTO_DCHECK(cur_packet_->is_finalized());
62  cur_packet_->Reset(&stream_);
63  return TraceWriter::TracePacketHandle(cur_packet_.get());
64}
65
66WriterID TraceWriterForTesting::writer_id() const {
67  return 0;
68}
69
70}  // namespace perfetto
71