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 <stddef.h>
18 #include <stdint.h>
19 #include <unistd.h>
20 
21 #include "perfetto/base/logging.h"
22 #include "perfetto/base/task_runner.h"
23 #include "perfetto/ext/base/utils.h"
24 #include "perfetto/ext/tracing/core/producer.h"
25 #include "perfetto/ext/tracing/core/trace_writer.h"
26 #include "perfetto/ext/tracing/ipc/default_socket.h"
27 #include "perfetto/ext/tracing/ipc/producer_ipc_client.h"
28 #include "perfetto/ext/tracing/ipc/service_ipc_host.h"
29 #include "perfetto/tracing/core/data_source_config.h"
30 #include "perfetto/tracing/core/data_source_descriptor.h"
31 #include "protos/perfetto/trace/test_event.pbzero.h"
32 #include "src/base/test/test_task_runner.h"
33 #include "test/test_helper.h"
34 
35 #include "protos/perfetto/trace/trace_packet.pbzero.h"
36 
37 // If we're building on Android and starting the daemons ourselves,
38 // create the sockets in a world-writable location.
39 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \
40     PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
41 #define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer"
42 #else
43 #define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket()
44 #endif
45 
46 namespace perfetto {
47 namespace shm_fuzz {
48 namespace {
49 
50 // Fake producer writing a protozero message of data into shared memory
51 // buffer, followed by a sentinel message to signal completion to the
52 // consumer.
53 class FakeProducer : public Producer {
54  public:
FakeProducer(std::string name,const uint8_t * data,size_t size,std::function<void ()> on_produced_and_committed)55   FakeProducer(std::string name,
56                const uint8_t* data,
57                size_t size,
58                std::function<void()> on_produced_and_committed)
59       : name_(std::move(name)),
60         data_(data),
61         size_(size),
62         on_produced_and_committed_(on_produced_and_committed) {}
63 
Connect(const char * socket_name,base::TaskRunner * task_runner)64   void Connect(const char* socket_name, base::TaskRunner* task_runner) {
65     endpoint_ = ProducerIPCClient::Connect(
66         socket_name, this, "android.perfetto.FakeProducer", task_runner);
67   }
68 
OnConnect()69   void OnConnect() override {
70     DataSourceDescriptor descriptor;
71     descriptor.set_name(name_);
72     endpoint_->RegisterDataSource(descriptor);
73   }
74 
OnDisconnect()75   void OnDisconnect() override {}
76 
SetupDataSource(DataSourceInstanceID,const DataSourceConfig &)77   void SetupDataSource(DataSourceInstanceID, const DataSourceConfig&) override {
78   }
79 
StartDataSource(DataSourceInstanceID,const DataSourceConfig & source_config)80   void StartDataSource(DataSourceInstanceID,
81                        const DataSourceConfig& source_config) override {
82     auto trace_writer = endpoint_->CreateTraceWriter(
83         static_cast<BufferID>(source_config.target_buffer()));
84     {
85       auto packet = trace_writer->NewTracePacket();
86       packet->AppendRawProtoBytes(data_, size_);
87     }
88     trace_writer->Flush();
89 
90     {
91       auto end_packet = trace_writer->NewTracePacket();
92       end_packet->set_for_testing()->set_str("end");
93     }
94     trace_writer->Flush(on_produced_and_committed_);
95   }
96 
StopDataSource(DataSourceInstanceID)97   void StopDataSource(DataSourceInstanceID) override {}
OnTracingSetup()98   void OnTracingSetup() override {}
Flush(FlushRequestID,const DataSourceInstanceID *,size_t)99   void Flush(FlushRequestID, const DataSourceInstanceID*, size_t) override {}
ClearIncrementalState(const DataSourceInstanceID *,size_t)100   void ClearIncrementalState(const DataSourceInstanceID*, size_t) override {}
101 
102  private:
103   const std::string name_;
104   const uint8_t* data_;
105   const size_t size_;
106   std::unique_ptr<TracingService::ProducerEndpoint> endpoint_;
107   std::function<void()> on_produced_and_committed_;
108 };
109 
110 class FuzzerFakeProducerThread {
111  public:
FuzzerFakeProducerThread(const uint8_t * data,size_t size,std::function<void ()> on_produced_and_committed)112   FuzzerFakeProducerThread(const uint8_t* data,
113                            size_t size,
114                            std::function<void()> on_produced_and_committed)
115       : data_(data),
116         size_(size),
117         on_produced_and_committed_(on_produced_and_committed) {}
118 
~FuzzerFakeProducerThread()119   ~FuzzerFakeProducerThread() {
120     if (!runner_)
121       return;
122     runner_->PostTaskAndWaitForTesting([this]() { producer_.reset(); });
123   }
124 
Connect()125   void Connect() {
126     runner_ = base::ThreadTaskRunner::CreateAndStart("perfetto.prd.fake");
127     runner_->PostTaskAndWaitForTesting([this]() {
128       producer_.reset(new FakeProducer("android.perfetto.FakeProducer", data_,
129                                        size_, on_produced_and_committed_));
130       producer_->Connect(TEST_PRODUCER_SOCK_NAME, runner_->get());
131     });
132   }
133 
134  private:
135   base::Optional<base::ThreadTaskRunner> runner_;  // Keep first.
136 
137   std::unique_ptr<FakeProducer> producer_;
138   const uint8_t* data_;
139   const size_t size_;
140   std::function<void()> on_produced_and_committed_;
141 };
142 
143 class FuzzTestHelper : public TestHelper {
144  public:
FuzzTestHelper(base::TestTaskRunner * task_runner)145   explicit FuzzTestHelper(base::TestTaskRunner* task_runner)
146       : TestHelper(task_runner) {}
147   // Do not verify the data, as it will most likely be corrupted.
ReadTraceData(std::vector<TracePacket>)148   void ReadTraceData(std::vector<TracePacket>) override {}
149 };
150 
151 int FuzzSharedMemory(const uint8_t* data, size_t size);
152 
FuzzSharedMemory(const uint8_t * data,size_t size)153 int FuzzSharedMemory(const uint8_t* data, size_t size) {
154   base::TestTaskRunner task_runner;
155 
156   FuzzTestHelper helper(&task_runner);
157   helper.StartServiceIfRequired();
158 
159   auto cp =
160       helper.WrapTask(task_runner.CreateCheckpoint("produced.and.committed"));
161   FuzzerFakeProducerThread producer_thread(data, size, cp);
162   producer_thread.Connect();
163 
164   helper.ConnectConsumer();
165   helper.WaitForConsumerConnect();
166 
167   TraceConfig trace_config;
168   trace_config.add_buffers()->set_size_kb(8);
169 
170   auto* ds_config = trace_config.add_data_sources()->mutable_config();
171   ds_config->set_name("android.perfetto.FakeProducer");
172   ds_config->set_target_buffer(0);
173 
174   helper.StartTracing(trace_config);
175   task_runner.RunUntilCheckpoint("produced.and.committed");
176 
177   helper.ReadData();
178   helper.WaitForReadData();
179 
180   return 0;
181 }
182 
183 }  // namespace
184 }  // namespace shm_fuzz
185 }  // namespace perfetto
186 
187 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
188 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)189 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
190   return perfetto::shm_fuzz::FuzzSharedMemory(data, size);
191 }
192