1 /*
2 * Copyright (C) 2023 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/trace_processor/sqlite/sqlite_engine.h"
18
19 #include <utility>
20
21 #include "perfetto/base/status.h"
22 #include "src/trace_processor/sqlite/db_sqlite_table.h"
23 #include "src/trace_processor/sqlite/query_cache.h"
24 #include "src/trace_processor/sqlite/sqlite_table.h"
25
26 // In Android and Chromium tree builds, we don't have the percentile module.
27 // Just don't include it.
28 #if PERFETTO_BUILDFLAG(PERFETTO_TP_PERCENTILE)
29 // defined in sqlite_src/ext/misc/percentile.c
30 extern "C" int sqlite3_percentile_init(sqlite3* db,
31 char** error,
32 const sqlite3_api_routines* api);
33 #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_PERCENTILE)
34
35 namespace perfetto {
36 namespace trace_processor {
37 namespace {
38
EnsureSqliteInitialized()39 void EnsureSqliteInitialized() {
40 // sqlite3_initialize isn't actually thread-safe despite being documented
41 // as such; we need to make sure multiple TraceProcessorImpl instances don't
42 // call it concurrently and only gets called once per process, instead.
43 static bool init_once = [] { return sqlite3_initialize() == SQLITE_OK; }();
44 PERFETTO_CHECK(init_once);
45 }
46
InitializeSqlite(sqlite3 * db)47 void InitializeSqlite(sqlite3* db) {
48 char* error = nullptr;
49 sqlite3_exec(db, "PRAGMA temp_store=2", nullptr, nullptr, &error);
50 if (error) {
51 PERFETTO_FATAL("Error setting pragma temp_store: %s", error);
52 }
53 // In Android tree builds, we don't have the percentile module.
54 // Just don't include it.
55 #if PERFETTO_BUILDFLAG(PERFETTO_TP_PERCENTILE)
56 sqlite3_percentile_init(db, &error, nullptr);
57 if (error) {
58 PERFETTO_ELOG("Error initializing: %s", error);
59 sqlite3_free(error);
60 }
61 #endif
62 }
63
64 } // namespace
65
SqliteEngine()66 SqliteEngine::SqliteEngine() : query_cache_(new QueryCache()) {
67 sqlite3* db = nullptr;
68 EnsureSqliteInitialized();
69 PERFETTO_CHECK(sqlite3_open(":memory:", &db) == SQLITE_OK);
70 InitializeSqlite(db);
71 db_.reset(std::move(db));
72 }
73
~SqliteEngine()74 SqliteEngine::~SqliteEngine() {
75 // It is important to unregister any functions that have been registered with
76 // the database before destroying it. This is because functions can hold onto
77 // prepared statements, which must be finalized before database destruction.
78 for (auto it = fn_ctx_.GetIterator(); it; ++it) {
79 int ret = sqlite3_create_function_v2(db_.get(), it.key().first.c_str(),
80 it.key().second, SQLITE_UTF8, nullptr,
81 nullptr, nullptr, nullptr, nullptr);
82 PERFETTO_CHECK(ret == 0);
83 }
84 fn_ctx_.Clear();
85 }
86
RegisterTable(const Table & table,const std::string & table_name)87 void SqliteEngine::RegisterTable(const Table& table,
88 const std::string& table_name) {
89 DbSqliteTable::Context context{query_cache_.get(),
90 DbSqliteTable::TableComputation::kStatic,
91 &table, nullptr};
92 RegisterVirtualTableModule<DbSqliteTable>(table_name, std::move(context),
93 SqliteTable::kEponymousOnly, false);
94
95 // Register virtual tables into an internal 'perfetto_tables' table.
96 // This is used for iterating through all the tables during a database
97 // export.
98 char* insert_sql = sqlite3_mprintf(
99 "INSERT INTO perfetto_tables(name) VALUES('%q')", table_name.c_str());
100 char* error = nullptr;
101 sqlite3_exec(db_.get(), insert_sql, nullptr, nullptr, &error);
102 sqlite3_free(insert_sql);
103 if (error) {
104 PERFETTO_ELOG("Error adding table to perfetto_tables: %s", error);
105 sqlite3_free(error);
106 }
107 }
108
RegisterTableFunction(std::unique_ptr<TableFunction> fn)109 void SqliteEngine::RegisterTableFunction(std::unique_ptr<TableFunction> fn) {
110 std::string table_name = fn->TableName();
111 DbSqliteTable::Context context{query_cache_.get(),
112 DbSqliteTable::TableComputation::kDynamic,
113 nullptr, std::move(fn)};
114 RegisterVirtualTableModule<DbSqliteTable>(table_name, std::move(context),
115 SqliteTable::kEponymousOnly, false);
116 }
117
DeclareVirtualTable(const std::string & create_stmt)118 base::Status SqliteEngine::DeclareVirtualTable(const std::string& create_stmt) {
119 int res = sqlite3_declare_vtab(db_.get(), create_stmt.c_str());
120 if (res != SQLITE_OK) {
121 return base::ErrStatus("Declare vtab failed: %s",
122 sqlite3_errmsg(db_.get()));
123 }
124 return base::OkStatus();
125 }
126
SaveSqliteTable(const std::string & table_name,std::unique_ptr<SqliteTable> table)127 base::Status SqliteEngine::SaveSqliteTable(const std::string& table_name,
128 std::unique_ptr<SqliteTable> table) {
129 auto res = saved_tables_.Insert(table_name, {});
130 if (!res.second) {
131 return base::ErrStatus("Table with name %s already is saved",
132 table_name.c_str());
133 }
134 *res.first = std::move(table);
135 return base::OkStatus();
136 }
137
RestoreSqliteTable(const std::string & table_name)138 base::StatusOr<std::unique_ptr<SqliteTable>> SqliteEngine::RestoreSqliteTable(
139 const std::string& table_name) {
140 auto* res = saved_tables_.Find(table_name);
141 if (!res) {
142 return base::ErrStatus("Table with name %s does not exist in saved state",
143 table_name.c_str());
144 }
145 return std::move(*res);
146 }
147
GetFunctionContext(const std::string & name,int argc)148 void* SqliteEngine::GetFunctionContext(const std::string& name, int argc) {
149 auto* res = fn_ctx_.Find(std::make_pair(name, argc));
150 return res ? *res : nullptr;
151 }
152
153 } // namespace trace_processor
154 } // namespace perfetto
155