Branch data Line data Source code
1 : : /* Debuginfo-over-http server.
2 : : Copyright (C) 2019-2024 Red Hat, Inc.
3 : : Copyright (C) 2021, 2022 Mark J. Wielaard <mark@klomp.org>
4 : : This file is part of elfutils.
5 : :
6 : : This file is free software; you can redistribute it and/or modify
7 : : it under the terms of the GNU General Public License as published by
8 : : the Free Software Foundation; either version 3 of the License, or
9 : : (at your option) any later version.
10 : :
11 : : elfutils is distributed in the hope that it will be useful, but
12 : : WITHOUT ANY WARRANTY; without even the implied warranty of
13 : : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : : GNU General Public License for more details.
15 : :
16 : : You should have received a copy of the GNU General Public License
17 : : along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 : :
19 : :
20 : : /* cargo-cult from libdwfl linux-kernel-modules.c */
21 : : /* In case we have a bad fts we include this before config.h because it
22 : : can't handle _FILE_OFFSET_BITS.
23 : : Everything we need here is fine if its declarations just come first.
24 : : Also, include sys/types.h before fts. On some systems fts.h is not self
25 : : contained. */
26 : : #ifdef BAD_FTS
27 : : #include <sys/types.h>
28 : : #include <fts.h>
29 : : #endif
30 : :
31 : : #ifdef HAVE_CONFIG_H
32 : : #include "config.h"
33 : : #endif
34 : :
35 : : // #define _GNU_SOURCE
36 : : #ifdef HAVE_SCHED_H
37 : : extern "C" {
38 : : #include <sched.h>
39 : : }
40 : : #endif
41 : : #ifdef HAVE_SYS_RESOURCE_H
42 : : extern "C" {
43 : : #include <sys/resource.h>
44 : : }
45 : : #endif
46 : :
47 : : #ifdef HAVE_EXECINFO_H
48 : : extern "C" {
49 : : #include <execinfo.h>
50 : : }
51 : : #endif
52 : : #ifdef HAVE_MALLOC_H
53 : : extern "C" {
54 : : #include <malloc.h>
55 : : }
56 : : #endif
57 : :
58 : : #include "debuginfod.h"
59 : : #include <dwarf.h>
60 : :
61 : : #include <argp.h>
62 : : #ifdef __GNUC__
63 : : #undef __attribute__ /* glibc bug - rhbz 1763325 */
64 : : #endif
65 : :
66 : : #ifdef USE_LZMA
67 : : #include <lzma.h>
68 : : #endif
69 : :
70 : : #include <unistd.h>
71 : : #include <stdlib.h>
72 : : #include <locale.h>
73 : : #include <pthread.h>
74 : : #include <signal.h>
75 : : #include <sys/stat.h>
76 : : #include <sys/time.h>
77 : : #include <sys/vfs.h>
78 : : #include <unistd.h>
79 : : #include <fcntl.h>
80 : : #include <netdb.h>
81 : : #include <math.h>
82 : : #include <float.h>
83 : : #include <fnmatch.h>
84 : :
85 : :
86 : : /* If fts.h is included before config.h, its indirect inclusions may not
87 : : give us the right LFS aliases of these functions, so map them manually. */
88 : : #ifdef BAD_FTS
89 : : #ifdef _FILE_OFFSET_BITS
90 : : #define open open64
91 : : #define fopen fopen64
92 : : #endif
93 : : #else
94 : : #include <sys/types.h>
95 : : #include <fts.h>
96 : : #endif
97 : :
98 : : #include <cstring>
99 : : #include <vector>
100 : : #include <set>
101 : : #include <unordered_set>
102 : : #include <map>
103 : : #include <string>
104 : : #include <iostream>
105 : : #include <iomanip>
106 : : #include <ostream>
107 : : #include <sstream>
108 : : #include <mutex>
109 : : #include <deque>
110 : : #include <condition_variable>
111 : : #include <exception>
112 : : #include <thread>
113 : : // #include <regex> // on rhel7 gcc 4.8, not competent
114 : : #include <regex.h>
115 : : // #include <algorithm>
116 : : using namespace std;
117 : :
118 : : #include <gelf.h>
119 : : #include <libdwelf.h>
120 : :
121 : : #include <microhttpd.h>
122 : :
123 : : #if MHD_VERSION >= 0x00097002
124 : : // libmicrohttpd 0.9.71 broke API
125 : : #define MHD_RESULT enum MHD_Result
126 : : #else
127 : : #define MHD_RESULT int
128 : : #endif
129 : :
130 : : #ifdef ENABLE_IMA_VERIFICATION
131 : : #include <rpm/rpmlib.h>
132 : : #include <rpm/rpmfi.h>
133 : : #include <rpm/header.h>
134 : : #include <glob.h>
135 : : #endif
136 : :
137 : : #include <curl/curl.h>
138 : : #include <archive.h>
139 : : #include <archive_entry.h>
140 : : #include <sqlite3.h>
141 : :
142 : : #ifdef __linux__
143 : : #include <sys/syscall.h>
144 : : #endif
145 : :
146 : : #ifdef __linux__
147 : : #define tid() syscall(SYS_gettid)
148 : : #else
149 : : #define tid() pthread_self()
150 : : #endif
151 : :
152 : : extern "C" {
153 : : #include "printversion.h"
154 : : #include "system.h"
155 : : }
156 : : #include <json-c/json.h>
157 : :
158 : :
159 : : inline bool
160 : 137035 : string_endswith(const string& haystack, const string& needle)
161 : : {
162 [ + + ]: 137035 : return (haystack.size() >= needle.size() &&
163 : 132032 : equal(haystack.end()-needle.size(), haystack.end(),
164 : 137035 : needle.begin()));
165 : : }
166 : :
167 : :
168 : : // Roll this identifier for every sqlite schema incompatibility.
169 : : #define BUILDIDS "buildids10"
170 : :
171 : : #if SQLITE_VERSION_NUMBER >= 3008000
172 : : #define WITHOUT_ROWID "without rowid"
173 : : #else
174 : : #define WITHOUT_ROWID ""
175 : : #endif
176 : :
177 : : static const char DEBUGINFOD_SQLITE_DDL[] =
178 : : "pragma foreign_keys = on;\n"
179 : : "pragma synchronous = 0;\n" // disable fsync()s - this cache is disposable across a machine crash
180 : : "pragma journal_mode = wal;\n" // https://sqlite.org/wal.html
181 : : "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
182 : : "pragma journal_size_limit = 0;\n" // limit steady state file (between grooming, which also =truncate's)
183 : : "pragma auto_vacuum = incremental;\n" // https://sqlite.org/pragma.html
184 : : "pragma busy_timeout = 1000;\n" // https://sqlite.org/pragma.html
185 : : // NB: all these are overridable with -D option
186 : :
187 : : // Normalization table for interning file names
188 : : "create table if not exists " BUILDIDS "_fileparts (\n"
189 : : " id integer primary key not null,\n"
190 : : " name text unique not null\n"
191 : : " );\n"
192 : : "create table if not exists " BUILDIDS "_files (\n"
193 : : " id integer primary key not null,\n"
194 : : " dirname integer not null,\n"
195 : : " basename integer not null,\n"
196 : : " unique (dirname, basename),\n"
197 : : " foreign key (dirname) references " BUILDIDS "_fileparts(id) on delete cascade,\n"
198 : : " foreign key (basename) references " BUILDIDS "_fileparts(id) on delete cascade\n"
199 : : " );\n"
200 : : "create view if not exists " BUILDIDS "_files_v as\n" // a
201 : : " select f.id, n1.name || '/' || n2.name as name\n"
202 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts n1, " BUILDIDS "_fileparts n2\n"
203 : : " where f.dirname = n1.id and f.basename = n2.id;\n"
204 : :
205 : : // Normalization table for interning buildids
206 : : "create table if not exists " BUILDIDS "_buildids (\n"
207 : : " id integer primary key not null,\n"
208 : : " hex text unique not null);\n"
209 : : // Track the completion of scanning of a given file & sourcetype at given time
210 : : "create table if not exists " BUILDIDS "_file_mtime_scanned (\n"
211 : : " mtime integer not null,\n"
212 : : " file integer not null,\n"
213 : : " size integer not null,\n" // in bytes
214 : : " sourcetype text(1) not null\n"
215 : : " check (sourcetype IN ('F', 'R')),\n"
216 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
217 : : " primary key (file, mtime, sourcetype)\n"
218 : : " ) " WITHOUT_ROWID ";\n"
219 : : "create table if not exists " BUILDIDS "_f_de (\n"
220 : : " buildid integer not null,\n"
221 : : " debuginfo_p integer not null,\n"
222 : : " executable_p integer not null,\n"
223 : : " file integer not null,\n"
224 : : " mtime integer not null,\n"
225 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
226 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
227 : : " primary key (buildid, file, mtime)\n"
228 : : " ) " WITHOUT_ROWID ";\n"
229 : : // Index for faster delete by file identifier and metadata searches
230 : : "create index if not exists " BUILDIDS "_f_de_idx on " BUILDIDS "_f_de (file, mtime);\n"
231 : : "create table if not exists " BUILDIDS "_f_s (\n"
232 : : " buildid integer not null,\n"
233 : : " artifactsrc integer not null,\n"
234 : : " file integer not null,\n" // NB: not necessarily entered into _mtime_scanned
235 : : " mtime integer not null,\n"
236 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
237 : : " foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
238 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
239 : : " primary key (buildid, artifactsrc, file, mtime)\n"
240 : : " ) " WITHOUT_ROWID ";\n"
241 : : "create table if not exists " BUILDIDS "_r_de (\n"
242 : : " buildid integer not null,\n"
243 : : " debuginfo_p integer not null,\n"
244 : : " executable_p integer not null,\n"
245 : : " file integer not null,\n"
246 : : " mtime integer not null,\n"
247 : : " content integer not null,\n"
248 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
249 : : " foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
250 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
251 : : " primary key (buildid, debuginfo_p, executable_p, file, content, mtime)\n"
252 : : " ) " WITHOUT_ROWID ";\n"
253 : : // Index for faster delete by archive file identifier
254 : : "create index if not exists " BUILDIDS "_r_de_idx on " BUILDIDS "_r_de (file, mtime);\n"
255 : : // Index for metadata searches
256 : : "create index if not exists " BUILDIDS "_r_de_idx2 on " BUILDIDS "_r_de (content);\n"
257 : : "create table if not exists " BUILDIDS "_r_sref (\n" // outgoing dwarf sourcefile references from rpm
258 : : " buildid integer not null,\n"
259 : : " artifactsrc integer not null,\n"
260 : : " foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
261 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
262 : : " primary key (buildid, artifactsrc)\n"
263 : : " ) " WITHOUT_ROWID ";\n"
264 : : "create table if not exists " BUILDIDS "_r_sdef (\n" // rpm contents that may satisfy sref
265 : : " file integer not null,\n"
266 : : " mtime integer not null,\n"
267 : : " content integer not null,\n"
268 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
269 : : " foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
270 : : " primary key (content, file, mtime)\n"
271 : : " ) " WITHOUT_ROWID ";\n"
272 : : "create table if not exists " BUILDIDS "_r_seekable (\n" // seekable rpm contents
273 : : " file integer not null,\n"
274 : : " content integer not null,\n"
275 : : " type text not null,\n"
276 : : " size integer not null,\n"
277 : : " offset integer not null,\n"
278 : : " mtime integer not null,\n"
279 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
280 : : " foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
281 : : " primary key (file, content)\n"
282 : : " ) " WITHOUT_ROWID ";\n"
283 : : // create views to glue together some of the above tables, for webapi D queries
284 : : // NB: _query_d2 and _query_e2 were added to replace _query_d and _query_e
285 : : // without updating BUILDIDS. They can be renamed back the next time BUILDIDS
286 : : // is updated.
287 : : "create view if not exists " BUILDIDS "_query_d2 as \n"
288 : : "select\n"
289 : : " b.hex as buildid, 'F' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, null as id1, null as source1\n"
290 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
291 : : " where b.id = n.buildid and f0.id = n.file and n.debuginfo_p = 1\n"
292 : : "union all select\n"
293 : : " b.hex as buildid, 'R' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, n.content as id1, f1.name as source1\n"
294 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
295 : : " where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.debuginfo_p = 1\n"
296 : : ";"
297 : : // ... and for E queries
298 : : "create view if not exists " BUILDIDS "_query_e2 as \n"
299 : : "select\n"
300 : : " b.hex as buildid, 'F' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, null as id1, null as source1\n"
301 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
302 : : " where b.id = n.buildid and f0.id = n.file and n.executable_p = 1\n"
303 : : "union all select\n"
304 : : " b.hex as buildid, 'R' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, n.content as id1, f1.name as source1\n"
305 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
306 : : " where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.executable_p = 1\n"
307 : : ";"
308 : : // ... and for S queries
309 : : "create view if not exists " BUILDIDS "_query_s as \n"
310 : : "select\n"
311 : : " b.hex as buildid, fs.name as artifactsrc, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1, null as source0ref\n"
312 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v fs, " BUILDIDS "_f_s n\n"
313 : : " where b.id = n.buildid and f0.id = n.file and fs.id = n.artifactsrc\n"
314 : : "union all select\n"
315 : : " b.hex as buildid, f1.name as artifactsrc, 'R' as sourcetype, f0.name as source0, sd.mtime as mtime, f1.name as source1, fsref.name as source0ref\n"
316 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_files_v fsref, "
317 : : " " BUILDIDS "_r_sdef sd, " BUILDIDS "_r_sref sr, " BUILDIDS "_r_de sde\n"
318 : : " where b.id = sr.buildid and f0.id = sd.file and fsref.id = sde.file and f1.id = sd.content\n"
319 : : " and sr.artifactsrc = sd.content and sde.buildid = sr.buildid\n"
320 : : ";"
321 : : // and for startup overview counts
322 : : "drop view if exists " BUILDIDS "_stats;\n"
323 : : "create view if not exists " BUILDIDS "_stats as\n"
324 : : " select 'file d/e' as label,count(*) as quantity from " BUILDIDS "_f_de\n"
325 : : "union all select 'file s',count(*) from " BUILDIDS "_f_s\n"
326 : : "union all select 'archive d/e',count(*) from " BUILDIDS "_r_de\n"
327 : : "union all select 'archive sref',count(*) from " BUILDIDS "_r_sref\n"
328 : : "union all select 'archive sdef',count(*) from " BUILDIDS "_r_sdef\n"
329 : : "union all select 'buildids',count(*) from " BUILDIDS "_buildids\n"
330 : : "union all select 'filenames',count(*) from " BUILDIDS "_files\n"
331 : : "union all select 'fileparts',count(*) from " BUILDIDS "_fileparts\n"
332 : : "union all select 'files scanned (#)',count(*) from " BUILDIDS "_file_mtime_scanned\n"
333 : : "union all select 'files scanned (mb)',coalesce(sum(size)/1024/1024,0) from " BUILDIDS "_file_mtime_scanned\n"
334 : : #if SQLITE_VERSION_NUMBER >= 3016000
335 : : "union all select 'index db size (mb)',page_count*page_size/1024/1024 as size FROM pragma_page_count(), pragma_page_size()\n"
336 : : #endif
337 : : ";\n"
338 : :
339 : : // schema change history & garbage collection
340 : : //
341 : : // XXX: we could have migration queries here to bring prior-schema
342 : : // data over instead of just dropping it. But that could incur
343 : : // doubled storage costs.
344 : : //
345 : : // buildids10: split the _files table into _parts
346 : : "" // <<< we are here
347 : : // buildids9: widen the mtime_scanned table
348 : : "DROP VIEW IF EXISTS buildids9_stats;\n"
349 : : "DROP INDEX IF EXISTS buildids9_r_de_idx;\n"
350 : : "DROP INDEX IF EXISTS buildids9_f_de_idx;\n"
351 : : "DROP VIEW IF EXISTS buildids9_query_s;\n"
352 : : "DROP VIEW IF EXISTS buildids9_query_e;\n"
353 : : "DROP VIEW IF EXISTS buildids9_query_d;\n"
354 : : "DROP TABLE IF EXISTS buildids9_r_sdef;\n"
355 : : "DROP TABLE IF EXISTS buildids9_r_sref;\n"
356 : : "DROP TABLE IF EXISTS buildids9_r_de;\n"
357 : : "DROP TABLE IF EXISTS buildids9_f_s;\n"
358 : : "DROP TABLE IF EXISTS buildids9_f_de;\n"
359 : : "DROP TABLE IF EXISTS buildids9_file_mtime_scanned;\n"
360 : : "DROP TABLE IF EXISTS buildids9_buildids;\n"
361 : : "DROP TABLE IF EXISTS buildids9_files;\n"
362 : : // buildids8: slim the sref table
363 : : "drop table if exists buildids8_f_de;\n"
364 : : "drop table if exists buildids8_f_s;\n"
365 : : "drop table if exists buildids8_r_de;\n"
366 : : "drop table if exists buildids8_r_sref;\n"
367 : : "drop table if exists buildids8_r_sdef;\n"
368 : : "drop table if exists buildids8_file_mtime_scanned;\n"
369 : : "drop table if exists buildids8_files;\n"
370 : : "drop table if exists buildids8_buildids;\n"
371 : : // buildids7: separate _norm table into dense subtype tables
372 : : "drop table if exists buildids7_f_de;\n"
373 : : "drop table if exists buildids7_f_s;\n"
374 : : "drop table if exists buildids7_r_de;\n"
375 : : "drop table if exists buildids7_r_sref;\n"
376 : : "drop table if exists buildids7_r_sdef;\n"
377 : : "drop table if exists buildids7_file_mtime_scanned;\n"
378 : : "drop table if exists buildids7_files;\n"
379 : : "drop table if exists buildids7_buildids;\n"
380 : : // buildids6: drop bolo/rfolo again, represent sources / rpmcontents in main table
381 : : "drop table if exists buildids6_norm;\n"
382 : : "drop table if exists buildids6_files;\n"
383 : : "drop table if exists buildids6_buildids;\n"
384 : : "drop view if exists buildids6;\n"
385 : : // buildids5: redefine srcfile1 column to be '.'-less (for rpms)
386 : : "drop table if exists buildids5_norm;\n"
387 : : "drop table if exists buildids5_files;\n"
388 : : "drop table if exists buildids5_buildids;\n"
389 : : "drop table if exists buildids5_bolo;\n"
390 : : "drop table if exists buildids5_rfolo;\n"
391 : : "drop view if exists buildids5;\n"
392 : : // buildids4: introduce rpmfile RFOLO
393 : : "drop table if exists buildids4_norm;\n"
394 : : "drop table if exists buildids4_files;\n"
395 : : "drop table if exists buildids4_buildids;\n"
396 : : "drop table if exists buildids4_bolo;\n"
397 : : "drop table if exists buildids4_rfolo;\n"
398 : : "drop view if exists buildids4;\n"
399 : : // buildids3*: split out srcfile BOLO
400 : : "drop table if exists buildids3_norm;\n"
401 : : "drop table if exists buildids3_files;\n"
402 : : "drop table if exists buildids3_buildids;\n"
403 : : "drop table if exists buildids3_bolo;\n"
404 : : "drop view if exists buildids3;\n"
405 : : // buildids2: normalized buildid and filenames into interning tables;
406 : : "drop table if exists buildids2_norm;\n"
407 : : "drop table if exists buildids2_files;\n"
408 : : "drop table if exists buildids2_buildids;\n"
409 : : "drop view if exists buildids2;\n"
410 : : // buildids1: made buildid and artifacttype NULLable, to represent cached-negative
411 : : // lookups from sources, e.g. files or rpms that contain no buildid-indexable content
412 : : "drop table if exists buildids1;\n"
413 : : // buildids: original
414 : : "drop table if exists buildids;\n"
415 : : ;
416 : :
417 : : static const char DEBUGINFOD_SQLITE_CLEANUP_DDL[] =
418 : : "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
419 : : ;
420 : :
421 : :
422 : :
423 : :
424 : : /* Name and version of program. */
425 : : ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
426 : :
427 : : /* Bug report address. */
428 : : ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
429 : :
430 : : /* Definitions of arguments for argp functions. */
431 : : static const struct argp_option options[] =
432 : : {
433 : : { NULL, 0, NULL, 0, "Scanners:", 1 },
434 : : { "scan-file-dir", 'F', NULL, 0, "Enable ELF/DWARF file scanning.", 0 },
435 : : { "scan-rpm-dir", 'R', NULL, 0, "Enable RPM scanning.", 0 },
436 : : { "scan-deb-dir", 'U', NULL, 0, "Enable DEB scanning.", 0 },
437 : : { "scan-archive", 'Z', "EXT=CMD", 0, "Enable arbitrary archive scanning.", 0 },
438 : : // "source-oci-imageregistry" ...
439 : :
440 : : { NULL, 0, NULL, 0, "Options:", 2 },
441 : : { "logical", 'L', NULL, 0, "Follow symlinks, default=ignore.", 0 },
442 : : { "rescan-time", 't', "SECONDS", 0, "Number of seconds to wait between rescans, 0=disable.", 0 },
443 : : { "groom-time", 'g', "SECONDS", 0, "Number of seconds to wait between database grooming, 0=disable.", 0 },
444 : : { "maxigroom", 'G', NULL, 0, "Run a complete database groom/shrink pass at startup.", 0 },
445 : : { "concurrency", 'c', "NUM", 0, "Limit scanning thread concurrency to NUM, default=#CPUs.", 0 },
446 : : { "connection-pool", 'C', "NUM", OPTION_ARG_OPTIONAL,
447 : : "Use webapi connection pool with NUM threads, default=unlim.", 0 },
448 : : { "include", 'I', "REGEX", 0, "Include files matching REGEX, default=all.", 0 },
449 : : { "exclude", 'X', "REGEX", 0, "Exclude files matching REGEX, default=none.", 0 },
450 : : { "port", 'p', "NUM", 0, "HTTP port to listen on, default 8002.", 0 },
451 : : #define ARGP_KEY_CORS 0x1000
452 : : { "cors", ARGP_KEY_CORS, NULL, 0, "Add CORS response headers to HTTP queries, default no.", 0 },
453 : : { "database", 'd', "FILE", 0, "Path to sqlite database.", 0 },
454 : : { "ddl", 'D', "SQL", 0, "Apply extra sqlite ddl/pragma to connection.", 0 },
455 : : { "verbose", 'v', NULL, 0, "Increase verbosity.", 0 },
456 : : { "regex-groom", 'r', NULL, 0,"Uses regexes from -I and -X arguments to groom the database.",0},
457 : : #define ARGP_KEY_FDCACHE_FDS 0x1001
458 : : { "fdcache-fds", ARGP_KEY_FDCACHE_FDS, "NUM", OPTION_HIDDEN, NULL, 0 },
459 : : #define ARGP_KEY_FDCACHE_MBS 0x1002
460 : : { "fdcache-mbs", ARGP_KEY_FDCACHE_MBS, "MB", 0, "Maximum total size of archive file fdcache.", 0 },
461 : : #define ARGP_KEY_FDCACHE_PREFETCH 0x1003
462 : : { "fdcache-prefetch", ARGP_KEY_FDCACHE_PREFETCH, "NUM", 0, "Number of archive files to prefetch into fdcache.", 0 },
463 : : #define ARGP_KEY_FDCACHE_MINTMP 0x1004
464 : : { "fdcache-mintmp", ARGP_KEY_FDCACHE_MINTMP, "NUM", 0, "Minimum free space% on tmpdir.", 0 },
465 : : #define ARGP_KEY_FDCACHE_PREFETCH_MBS 0x1005
466 : : { "fdcache-prefetch-mbs", ARGP_KEY_FDCACHE_PREFETCH_MBS, "MB", OPTION_HIDDEN, NULL, 0},
467 : : #define ARGP_KEY_FDCACHE_PREFETCH_FDS 0x1006
468 : : { "fdcache-prefetch-fds", ARGP_KEY_FDCACHE_PREFETCH_FDS, "NUM", OPTION_HIDDEN, NULL, 0},
469 : : #define ARGP_KEY_FORWARDED_TTL_LIMIT 0x1007
470 : : {"forwarded-ttl-limit", ARGP_KEY_FORWARDED_TTL_LIMIT, "NUM", 0, "Limit of X-Forwarded-For hops, default 8.", 0},
471 : : #define ARGP_KEY_PASSIVE 0x1008
472 : : { "passive", ARGP_KEY_PASSIVE, NULL, 0, "Do not scan or groom, read-only database.", 0 },
473 : : #define ARGP_KEY_DISABLE_SOURCE_SCAN 0x1009
474 : : { "disable-source-scan", ARGP_KEY_DISABLE_SOURCE_SCAN, NULL, 0, "Do not scan dwarf source info.", 0 },
475 : : #define ARGP_SCAN_CHECKPOINT 0x100A
476 : : { "scan-checkpoint", ARGP_SCAN_CHECKPOINT, "NUM", 0, "Number of files scanned before a WAL checkpoint.", 0 },
477 : : #ifdef ENABLE_IMA_VERIFICATION
478 : : #define ARGP_KEY_KOJI_SIGCACHE 0x100B
479 : : { "koji-sigcache", ARGP_KEY_KOJI_SIGCACHE, NULL, 0, "Do a koji specific mapping of rpm paths to get IMA signatures.", 0 },
480 : : #endif
481 : : #define ARGP_KEY_METADATA_MAXTIME 0x100C
482 : : { "metadata-maxtime", ARGP_KEY_METADATA_MAXTIME, "SECONDS", 0,
483 : : "Number of seconds to limit metadata query run time, 0=unlimited.", 0 },
484 : : { NULL, 0, NULL, 0, NULL, 0 },
485 : : };
486 : :
487 : : /* Short description of program. */
488 : : static const char doc[] = "Serve debuginfo-related content across HTTP from files under PATHs.";
489 : :
490 : : /* Strings for arguments in help texts. */
491 : : static const char args_doc[] = "[PATH ...]";
492 : :
493 : : /* Prototype for option handler. */
494 : : static error_t parse_opt (int key, char *arg, struct argp_state *state);
495 : :
496 : : static unsigned default_concurrency();
497 : :
498 : : /* Data structure to communicate with argp functions. */
499 : : static struct argp argp =
500 : : {
501 : : options, parse_opt, args_doc, doc, NULL, NULL, NULL
502 : : };
503 : :
504 : :
505 : : static string db_path;
506 : : static sqlite3 *db; // single connection, serialized across all our threads!
507 : : static sqlite3 *dbq; // webapi query-servicing readonly connection, serialized ditto!
508 : : static unsigned verbose;
509 : : static volatile sig_atomic_t interrupted = 0;
510 : : static volatile sig_atomic_t forced_rescan_count = 0;
511 : : static volatile sig_atomic_t sigusr1 = 0;
512 : : static volatile sig_atomic_t forced_groom_count = 0;
513 : : static volatile sig_atomic_t sigusr2 = 0;
514 : : static unsigned http_port = 8002;
515 : : static bool webapi_cors = false;
516 : : static unsigned rescan_s = 300;
517 : : static unsigned groom_s = 86400;
518 : : static bool maxigroom = false;
519 : : static unsigned concurrency = default_concurrency();
520 : : static int connection_pool = 0;
521 : : static set<string> source_paths;
522 : : static bool scan_files = false;
523 : : static map<string,string> scan_archives;
524 : : static vector<string> extra_ddl;
525 : : static regex_t file_include_regex;
526 : : static regex_t file_exclude_regex;
527 : : static bool regex_groom = false;
528 : : static bool traverse_logical;
529 : : static long fdcache_mbs;
530 : : static long fdcache_prefetch;
531 : : static long fdcache_mintmp;
532 : : static unsigned forwarded_ttl_limit = 8;
533 : : static bool scan_source_info = true;
534 : : static string tmpdir;
535 : : static bool passive_p = false;
536 : : static long scan_checkpoint = 256;
537 : : #ifdef ENABLE_IMA_VERIFICATION
538 : : static bool requires_koji_sigcache_mapping = false;
539 : : #endif
540 : : static unsigned metadata_maxtime_s = 5;
541 : :
542 : : static void set_metric(const string& key, double value);
543 : : static void inc_metric(const string& key);
544 : : static void add_metric(const string& metric,
545 : : double value);
546 : : static void set_metric(const string& metric,
547 : : const string& lname, const string& lvalue,
548 : : double value);
549 : : static void inc_metric(const string& metric,
550 : : const string& lname, const string& lvalue);
551 : : static void add_metric(const string& metric,
552 : : const string& lname, const string& lvalue,
553 : : double value);
554 : : static void inc_metric(const string& metric,
555 : : const string& lname, const string& lvalue,
556 : : const string& rname, const string& rvalue);
557 : : static void add_metric(const string& metric,
558 : : const string& lname, const string& lvalue,
559 : : const string& rname, const string& rvalue,
560 : : double value);
561 : :
562 : :
563 : : class tmp_inc_metric { // a RAII style wrapper for exception-safe scoped increment & decrement
564 : : string m, n, v;
565 : : public:
566 : 3348 : tmp_inc_metric(const string& mname, const string& lname, const string& lvalue):
567 [ + - + - ]: 3348 : m(mname), n(lname), v(lvalue)
568 : : {
569 [ + - ]: 3348 : add_metric (m, n, v, 1);
570 [ - - - - : 3348 : }
- - ]
571 : 3348 : ~tmp_inc_metric()
572 : : {
573 : 3348 : add_metric (m, n, v, -1);
574 [ - + - + : 3348 : }
- + ]
575 : : };
576 : :
577 : : class tmp_ms_metric { // a RAII style wrapper for exception-safe scoped timing
578 : : string m, n, v;
579 : : struct timespec ts_start;
580 : : public:
581 : 346029 : tmp_ms_metric(const string& mname, const string& lname, const string& lvalue):
582 [ + - + - ]: 346029 : m(mname), n(lname), v(lvalue)
583 : : {
584 : 346029 : clock_gettime (CLOCK_MONOTONIC, & ts_start);
585 [ - - - - ]: 346202 : }
586 : 346311 : ~tmp_ms_metric()
587 : : {
588 : 346311 : struct timespec ts_end;
589 : 346311 : clock_gettime (CLOCK_MONOTONIC, & ts_end);
590 : 346306 : double deltas = (ts_end.tv_sec - ts_start.tv_sec)
591 : 346306 : + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
592 : :
593 [ + - ]: 346306 : add_metric (m + "_milliseconds_sum", n, v, (deltas*1000.0));
594 [ + + ]: 346330 : inc_metric (m + "_milliseconds_count", n, v);
595 [ + + - + : 639022 : }
- + ]
596 : : };
597 : :
598 : :
599 : : /* Handle program arguments. */
600 : : static error_t
601 : 1232 : parse_opt (int key, char *arg,
602 : : struct argp_state *state __attribute__ ((unused)))
603 : : {
604 : 1232 : int rc;
605 [ + + + + : 1232 : switch (key)
+ + + + +
+ - + + -
- + + + +
+ + + + +
+ - + -
+ ]
606 : : {
607 : 296 : case 'v': verbose ++; break;
608 : 80 : case 'd':
609 : : /* When using the in-memory database make sure it is shareable,
610 : : so we can open it twice as read/write and read-only. */
611 [ + + ]: 80 : if (strcmp (arg, ":memory:") == 0)
612 : 1246 : db_path = "file::memory:?cache=shared";
613 : : else
614 [ + - ]: 132 : db_path = string(arg);
615 : : break;
616 : 80 : case 'p': http_port = (unsigned) atoi(arg);
617 [ + - ]: 80 : if (http_port == 0 || http_port > 65535)
618 : 0 : argp_failure(state, 1, EINVAL, "port number");
619 : : break;
620 : 6 : case ARGP_KEY_CORS:
621 : 6 : webapi_cors = true;
622 : 6 : break;
623 : 50 : case 'F': scan_files = true; break;
624 : 24 : case 'R':
625 [ + - + - : 24 : scan_archives[".rpm"]="cat"; // libarchive groks rpm natively
- + ]
626 : 24 : break;
627 : 18 : case 'U':
628 [ + - + - : 18 : scan_archives[".deb"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
629 [ + - + - : 18 : scan_archives[".ddeb"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
630 [ + - + - : 18 : scan_archives[".ipk"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
631 : : // .udeb too?
632 : 18 : break;
633 : 40 : case 'Z':
634 : 40 : {
635 [ - + ]: 40 : char* extension = strchr(arg, '=');
636 [ - + ]: 40 : if (arg[0] == '\0')
637 : 0 : argp_failure(state, 1, EINVAL, "missing EXT");
638 [ + + ]: 40 : else if (extension)
639 [ + - + - : 20 : scan_archives[string(arg, (extension-arg))]=string(extension+1);
- + - + -
- ]
640 : : else
641 [ + - + - : 20 : scan_archives[string(arg)]=string("cat");
- + - + -
- ]
642 : : }
643 : : break;
644 : 8 : case 'L':
645 [ - + ]: 8 : if (passive_p)
646 : 0 : argp_failure(state, 1, EINVAL, "-L option inconsistent with passive mode");
647 : 8 : traverse_logical = true;
648 : 8 : break;
649 : 0 : case 'D':
650 [ # # ]: 0 : if (passive_p)
651 : 0 : argp_failure(state, 1, EINVAL, "-D option inconsistent with passive mode");
652 [ # # ]: 0 : extra_ddl.push_back(string(arg));
653 : 0 : break;
654 : 64 : case 't':
655 [ - + ]: 64 : if (passive_p)
656 : 0 : argp_failure(state, 1, EINVAL, "-t option inconsistent with passive mode");
657 : 64 : rescan_s = (unsigned) atoi(arg);
658 : 64 : break;
659 : 64 : case 'g':
660 [ - + ]: 64 : if (passive_p)
661 : 0 : argp_failure(state, 1, EINVAL, "-g option inconsistent with passive mode");
662 : 64 : groom_s = (unsigned) atoi(arg);
663 : 64 : break;
664 : 0 : case 'G':
665 [ # # ]: 0 : if (passive_p)
666 : 0 : argp_failure(state, 1, EINVAL, "-G option inconsistent with passive mode");
667 : 0 : maxigroom = true;
668 : 0 : break;
669 : 0 : case 'c':
670 [ # # ]: 0 : if (passive_p)
671 : 0 : argp_failure(state, 1, EINVAL, "-c option inconsistent with passive mode");
672 : 0 : concurrency = (unsigned) atoi(arg);
673 [ # # ]: 0 : if (concurrency < 1) concurrency = 1;
674 : : break;
675 : 6 : case 'C':
676 [ + + ]: 6 : if (arg)
677 : : {
678 : 4 : connection_pool = atoi(arg);
679 [ + - ]: 4 : if (connection_pool < 2)
680 : 0 : argp_failure(state, 1, EINVAL, "-C NUM minimum 2");
681 : : }
682 : : break;
683 : 4 : case 'I':
684 : : // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
685 [ - + ]: 4 : if (passive_p)
686 : 0 : argp_failure(state, 1, EINVAL, "-I option inconsistent with passive mode");
687 : 4 : regfree (&file_include_regex);
688 : 4 : rc = regcomp (&file_include_regex, arg, REG_EXTENDED|REG_NOSUB);
689 [ + - ]: 4 : if (rc != 0)
690 : 0 : argp_failure(state, 1, EINVAL, "regular expression");
691 : : break;
692 : 6 : case 'X':
693 [ - + ]: 6 : if (passive_p)
694 : 0 : argp_failure(state, 1, EINVAL, "-X option inconsistent with passive mode");
695 : 6 : regfree (&file_exclude_regex);
696 : 6 : rc = regcomp (&file_exclude_regex, arg, REG_EXTENDED|REG_NOSUB);
697 [ + - ]: 6 : if (rc != 0)
698 : 0 : argp_failure(state, 1, EINVAL, "regular expression");
699 : : break;
700 : 4 : case 'r':
701 [ - + ]: 4 : if (passive_p)
702 : 0 : argp_failure(state, 1, EINVAL, "-r option inconsistent with passive mode");
703 : 4 : regex_groom = true;
704 : 4 : break;
705 : : case ARGP_KEY_FDCACHE_FDS:
706 : : // deprecated
707 : : break;
708 : 4 : case ARGP_KEY_FDCACHE_MBS:
709 : 4 : fdcache_mbs = atol (arg);
710 : 4 : break;
711 : 4 : case ARGP_KEY_FDCACHE_PREFETCH:
712 : 4 : fdcache_prefetch = atol (arg);
713 : 4 : break;
714 : 4 : case ARGP_KEY_FDCACHE_MINTMP:
715 : 4 : fdcache_mintmp = atol (arg);
716 [ + - ]: 4 : if( fdcache_mintmp > 100 || fdcache_mintmp < 0 )
717 : 0 : argp_failure(state, 1, EINVAL, "fdcache mintmp percent");
718 : : break;
719 : 4 : case ARGP_KEY_FORWARDED_TTL_LIMIT:
720 : 4 : forwarded_ttl_limit = (unsigned) atoi(arg);
721 : 4 : break;
722 : 110 : case ARGP_KEY_ARG:
723 [ + - ]: 110 : source_paths.insert(string(arg));
724 : 110 : break;
725 : : case ARGP_KEY_FDCACHE_PREFETCH_FDS:
726 : : // deprecated
727 : : break;
728 : : case ARGP_KEY_FDCACHE_PREFETCH_MBS:
729 : : // deprecated
730 : : break;
731 : 2 : case ARGP_KEY_PASSIVE:
732 : 2 : passive_p = true;
733 [ + - ]: 2 : if (source_paths.size() > 0
734 [ + - ]: 2 : || maxigroom
735 [ + - ]: 2 : || extra_ddl.size() > 0
736 [ + - + - ]: 4 : || traverse_logical)
737 : : // other conflicting options tricky to check
738 : 0 : argp_failure(state, 1, EINVAL, "inconsistent options with passive mode");
739 : : break;
740 : 0 : case ARGP_KEY_DISABLE_SOURCE_SCAN:
741 : 0 : scan_source_info = false;
742 : 0 : break;
743 : 2 : case ARGP_SCAN_CHECKPOINT:
744 : 2 : scan_checkpoint = atol (arg);
745 [ + - ]: 2 : if (scan_checkpoint < 0)
746 : 0 : argp_failure(state, 1, EINVAL, "scan checkpoint");
747 : : break;
748 : 0 : case ARGP_KEY_METADATA_MAXTIME:
749 : 0 : metadata_maxtime_s = (unsigned) atoi(arg);
750 : 0 : break;
751 : : #ifdef ENABLE_IMA_VERIFICATION
752 : : case ARGP_KEY_KOJI_SIGCACHE:
753 : : requires_koji_sigcache_mapping = true;
754 : : break;
755 : : #endif
756 : : // case 'h': argp_state_help (state, stderr, ARGP_HELP_LONG|ARGP_HELP_EXIT_OK);
757 : : default: return ARGP_ERR_UNKNOWN;
758 : : }
759 : :
760 : : return 0;
761 : : }
762 : :
763 : :
764 : : ////////////////////////////////////////////////////////////////////////
765 : :
766 : :
767 : : static void add_mhd_response_header (struct MHD_Response *r,
768 : : const char *h, const char *v);
769 : :
770 : : // represent errors that may get reported to an ostream and/or a libmicrohttpd connection
771 : :
772 : 8 : struct reportable_exception
773 : : {
774 : : int code;
775 : : string message;
776 : :
777 [ - - + - : 106 : reportable_exception(int c, const string& m): code(c), message(m) {}
- - + - +
- ]
778 [ - - - - : 604 : reportable_exception(const string& m): code(503), message(m) {}
- - - - -
- - - + -
- - - - +
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
- - ]
779 : : reportable_exception(): code(503), message() {}
780 : :
781 : : void report(ostream& o) const; // defined under obatched() class below
782 : :
783 : 634 : MHD_RESULT mhd_send_response(MHD_Connection* c) const {
784 : 1268 : MHD_Response* r = MHD_create_response_from_buffer (message.size(),
785 : 634 : (void*) message.c_str(),
786 : : MHD_RESPMEM_MUST_COPY);
787 : 634 : add_mhd_response_header (r, "Content-Type", "text/plain");
788 : 634 : MHD_RESULT rc = MHD_queue_response (c, code, r);
789 : 634 : MHD_destroy_response (r);
790 : 634 : return rc;
791 : : }
792 : : };
793 : :
794 : :
795 : : struct sqlite_exception: public reportable_exception
796 : : {
797 : 0 : sqlite_exception(int rc, const string& msg):
798 [ # # # # : 0 : reportable_exception(string("sqlite3 error: ") + msg + ": " + string(sqlite3_errstr(rc) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
799 [ # # # # : 0 : inc_metric("error_count","sqlite3",sqlite3_errstr(rc));
# # # # #
# # # # #
# # # # ]
800 [ # # ]: 0 : }
801 : : };
802 : :
803 [ + - - - ]: 4 : struct libc_exception: public reportable_exception
804 : : {
805 : 594 : libc_exception(int rc, const string& msg):
806 [ - + + - : 2376 : reportable_exception(string("libc error: ") + msg + ": " + string(strerror(rc) ?: "?")) {
+ - + - +
- - + - +
- + + - -
- ]
807 [ + - + - : 1188 : inc_metric("error_count","libc",strerror(rc));
+ - + - -
+ + - - -
- - ]
808 [ - - ]: 594 : }
809 : : };
810 : :
811 : :
812 : : struct archive_exception: public reportable_exception
813 : : {
814 : 0 : archive_exception(const string& msg):
815 [ # # # # : 0 : reportable_exception(string("libarchive error: ") + msg) {
# # ]
816 [ # # # # : 0 : inc_metric("error_count","libarchive",msg);
# # # # #
# ]
817 [ # # ]: 0 : }
818 : 0 : archive_exception(struct archive* a, const string& msg):
819 [ # # # # : 0 : reportable_exception(string("libarchive error: ") + msg + ": " + string(archive_error_string(a) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
820 [ # # # # : 0 : inc_metric("error_count","libarchive",msg + ": " + string(archive_error_string(a) ?: "?"));
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ]
821 [ # # ]: 0 : }
822 : : };
823 : :
824 : :
825 : : struct elfutils_exception: public reportable_exception
826 : : {
827 : 0 : elfutils_exception(int rc, const string& msg):
828 [ # # # # : 0 : reportable_exception(string("elfutils error: ") + msg + ": " + string(elf_errmsg(rc) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
829 [ # # # # : 0 : inc_metric("error_count","elfutils",elf_errmsg(rc));
# # # # #
# # # # #
# # # # ]
830 [ # # ]: 0 : }
831 : : };
832 : :
833 : :
834 : : ////////////////////////////////////////////////////////////////////////
835 : :
836 : : template <typename Payload>
837 : : class workq
838 : : {
839 : : unordered_set<Payload> q; // eliminate duplicates
840 : : mutex mtx;
841 : : condition_variable cv;
842 : : bool dead;
843 : : unsigned idlers; // number of threads busy with wait_idle / done_idle
844 : : unsigned fronters; // number of threads busy with wait_front / done_front
845 : :
846 : : public:
847 : 80 : workq() { dead = false; idlers = 0; fronters = 0; }
848 : 80 : ~workq() {}
849 : :
850 : 1306 : void push_back(const Payload& p)
851 : : {
852 : 1306 : unique_lock<mutex> lock(mtx);
853 [ + - ]: 1306 : q.insert (p);
854 [ + - + - : 2612 : set_metric("thread_work_pending","role","scan", q.size());
+ - + - -
+ - + - -
- - ]
855 : 1306 : cv.notify_all();
856 : 1306 : }
857 : :
858 : : // kill this workqueue, wake up all idlers / scanners
859 : 80 : void nuke() {
860 : 80 : unique_lock<mutex> lock(mtx);
861 : : // optional: q.clear();
862 : 80 : dead = true;
863 : 80 : cv.notify_all();
864 : 80 : }
865 : :
866 : : // clear the workqueue, when scanning is interrupted with USR2
867 : 0 : void clear() {
868 : 0 : unique_lock<mutex> lock(mtx);
869 : 0 : q.clear();
870 [ # # # # : 0 : set_metric("thread_work_pending","role","scan", q.size());
# # # # #
# # # # #
# # ]
871 : : // NB: there may still be some live fronters
872 : 0 : cv.notify_all(); // maybe wake up waiting idlers
873 : 0 : }
874 : :
875 : : // block this scanner thread until there is work to do and no active idler
876 : 1593 : bool wait_front (Payload& p)
877 : : {
878 : 1593 : unique_lock<mutex> lock(mtx);
879 [ + + + + : 5141 : while (!dead && (q.size() == 0 || idlers > 0))
+ + ]
880 [ + - ]: 3547 : cv.wait(lock);
881 [ + + ]: 1594 : if (dead)
882 : : return false;
883 : : else
884 : : {
885 [ + - ]: 1306 : p = * q.begin();
886 : 1306 : q.erase (q.begin());
887 : 1306 : fronters ++; // prevent idlers from starting awhile, even if empty q
888 [ + - + - : 2612 : set_metric("thread_work_pending","role","scan", q.size());
+ - + - -
+ - + - -
- - - - ]
889 : : // NB: don't wake up idlers yet! The consumer is busy
890 : : // processing this element until it calls done_front().
891 : 1306 : return true;
892 : : }
893 : 1594 : }
894 : :
895 : : // notify waitq that scanner thread is done with that last item
896 : 1306 : void done_front ()
897 : : {
898 : 1306 : unique_lock<mutex> lock(mtx);
899 : 1306 : fronters --;
900 [ + + + + ]: 1306 : if (q.size() == 0 && fronters == 0)
901 : 98 : cv.notify_all(); // maybe wake up waiting idlers
902 : 1306 : }
903 : :
904 : : // block this idler thread until there is no work to do
905 : 606 : void wait_idle ()
906 : : {
907 : 606 : unique_lock<mutex> lock(mtx);
908 : 606 : cv.notify_all(); // maybe wake up waiting scanners
909 [ + + + + : 674 : while (!dead && ((q.size() != 0) || fronters > 0))
+ + ]
910 [ + - ]: 68 : cv.wait(lock);
911 [ + - ]: 606 : idlers ++;
912 : 606 : }
913 : :
914 : 528 : void done_idle ()
915 : : {
916 : 528 : unique_lock<mutex> lock(mtx);
917 : 528 : idlers --;
918 : 528 : cv.notify_all(); // maybe wake up waiting scanners, but probably not (shutting down)
919 : 528 : }
920 : : };
921 : :
922 : : typedef struct stat stat_t;
923 : : typedef pair<string,stat_t> scan_payload;
924 : : inline bool operator< (const scan_payload& a, const scan_payload& b)
925 : : {
926 : : return a.first < b.first; // don't bother compare the stat fields
927 : : }
928 : :
929 : : namespace std { // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480
930 : : template<> struct hash<::scan_payload>
931 : : {
932 : 5421 : std::size_t operator() (const ::scan_payload& p) const noexcept
933 : : {
934 [ + + + + ]: 5421 : return hash<string>()(p.first);
935 : : }
936 : : };
937 : : template<> struct equal_to<::scan_payload>
938 : : {
939 : 512 : std::size_t operator() (const ::scan_payload& a, const ::scan_payload& b) const noexcept
940 : : {
941 [ - + - - ]: 512 : return a.first == b.first;
942 : : }
943 : : };
944 : : }
945 : :
946 : : static workq<scan_payload> scanq; // just a single one
947 : : // producer & idler: thread_main_fts_source_paths()
948 : : // consumer: thread_main_scanner()
949 : : // idler: thread_main_groom()
950 : :
951 : :
952 : : ////////////////////////////////////////////////////////////////////////
953 : :
954 : : // Unique set is a thread-safe structure that lends 'ownership' of a value
955 : : // to a thread. Other threads requesting the same thing are made to wait.
956 : : // It's like a semaphore-on-demand.
957 : : template <typename T>
958 : : class unique_set
959 : : {
960 : : private:
961 : : set<T> values;
962 : : mutex mtx;
963 : : condition_variable cv;
964 : : public:
965 : 60 : unique_set() {}
966 : 60 : ~unique_set() {}
967 : :
968 : 2574 : void acquire(const T& value)
969 : : {
970 : 2574 : unique_lock<mutex> lock(mtx);
971 [ + + ]: 3148 : while (values.find(value) != values.end())
972 [ + - ]: 574 : cv.wait(lock);
973 [ + - ]: 2574 : values.insert(value);
974 : 2574 : }
975 : :
976 : 2574 : void release(const T& value)
977 : : {
978 : 2574 : unique_lock<mutex> lock(mtx);
979 : : // assert (values.find(value) != values.end());
980 : 2574 : values.erase(value);
981 : 2574 : cv.notify_all();
982 : 2574 : }
983 : : };
984 : :
985 : :
986 : : // This is the object that's instantiate to uniquely hold a value in a
987 : : // RAII-pattern way.
988 : : template <typename T>
989 : : class unique_set_reserver
990 : : {
991 : : private:
992 : : unique_set<T>& please_hold;
993 : : T mine;
994 : : public:
995 : 2574 : unique_set_reserver(unique_set<T>& t, const T& value):
996 [ + - - - ]: 2574 : please_hold(t), mine(value) { please_hold.acquire(mine); }
997 [ + - ]: 2574 : ~unique_set_reserver() { please_hold.release(mine); }
998 : : };
999 : :
1000 : :
1001 : : ////////////////////////////////////////////////////////////////////////
1002 : :
1003 : : // periodic_barrier is a concurrency control object that lets N threads
1004 : : // periodically (based on counter value) agree to wait at a barrier,
1005 : : // let one of them carry out some work, then be set free
1006 : :
1007 : : class periodic_barrier
1008 : : {
1009 : : private:
1010 : : unsigned period; // number of count() reports to trigger barrier activation
1011 : : unsigned threads; // number of threads participating
1012 : : mutex mtx; // protects all the following fields
1013 : : unsigned counter; // count of count() reports in the current generation
1014 : : unsigned generation; // barrier activation generation
1015 : : unsigned waiting; // number of threads waiting for barrier
1016 : : bool dead; // bring out your
1017 : : condition_variable cv;
1018 : : public:
1019 : 72 : periodic_barrier(unsigned t, unsigned p):
1020 : 72 : period(p), threads(t), counter(0), generation(0), waiting(0), dead(false) { }
1021 : : virtual ~periodic_barrier() {}
1022 : :
1023 : : virtual void periodic_barrier_work() noexcept = 0;
1024 : 72 : void nuke() {
1025 : 72 : unique_lock<mutex> lock(mtx);
1026 : 72 : dead = true;
1027 : 72 : cv.notify_all();
1028 : 72 : }
1029 : :
1030 : 1594 : void count()
1031 : : {
1032 : 1594 : unique_lock<mutex> lock(mtx);
1033 : 1594 : unsigned prev_generation = this->generation;
1034 [ + + ]: 1594 : if (counter < period-1) // normal case: counter just freely running
1035 : : {
1036 : 1450 : counter ++;
1037 : 1450 : return;
1038 : : }
1039 [ + + ]: 144 : else if (counter == period-1) // we're the doer
1040 : : {
1041 : 39 : counter = period; // entering barrier holding phase
1042 : 39 : cv.notify_all();
1043 [ + + + - ]: 177 : while (waiting < threads-1 && !dead)
1044 [ + - ]: 99 : cv.wait(lock);
1045 : : // all other threads are now stuck in the barrier
1046 : 39 : this->periodic_barrier_work(); // NB: we're holding the mutex the whole time
1047 : : // reset for next barrier, releasing other waiters
1048 : 39 : counter = 0;
1049 : 39 : generation ++;
1050 : 39 : cv.notify_all();
1051 : 39 : return;
1052 : : }
1053 [ + - ]: 105 : else if (counter == period) // we're a waiter, in holding phase
1054 : : {
1055 : 105 : waiting ++;
1056 : 105 : cv.notify_all();
1057 [ + + + + : 390 : while (counter == period && generation == prev_generation && !dead)
+ - ]
1058 [ + - ]: 180 : cv.wait(lock);
1059 : 105 : waiting --;
1060 : 105 : return;
1061 : : }
1062 : 1594 : }
1063 : : };
1064 : :
1065 : :
1066 : :
1067 : : ////////////////////////////////////////////////////////////////////////
1068 : :
1069 : :
1070 : : // Print a standard timestamp.
1071 : : static ostream&
1072 : 44584 : timestamp (ostream &o)
1073 : : {
1074 : 44584 : char datebuf[80];
1075 : 44584 : char *now2 = NULL;
1076 : 44584 : time_t now_t = time(NULL);
1077 : 44583 : struct tm now;
1078 : 44583 : struct tm *nowp = gmtime_r (&now_t, &now);
1079 [ + - ]: 44584 : if (nowp)
1080 : : {
1081 : 44584 : (void) strftime (datebuf, sizeof (datebuf), "%c", nowp);
1082 : 44584 : now2 = datebuf;
1083 : : }
1084 : :
1085 : 44584 : return o << "[" << (now2 ? now2 : "") << "] "
1086 [ - + ]: 44584 : << "(" << getpid () << "/" << tid() << "): ";
1087 : : }
1088 : :
1089 : :
1090 : : // A little class that impersonates an ostream to the extent that it can
1091 : : // take << streaming operations. It batches up the bits into an internal
1092 : : // stringstream until it is destroyed; then flushes to the original ostream.
1093 : : // It adds a timestamp
1094 : : class obatched
1095 : : {
1096 : : private:
1097 : : ostream& o;
1098 : : stringstream stro;
1099 : : static mutex lock;
1100 : : public:
1101 : 44583 : obatched(ostream& oo, bool timestamp_p = true): o(oo)
1102 : : {
1103 [ + - ]: 44584 : if (timestamp_p)
1104 [ + - ]: 44584 : timestamp(stro);
1105 : 44580 : }
1106 : 44581 : ~obatched()
1107 : : {
1108 : 44581 : unique_lock<mutex> do_not_cross_the_streams(obatched::lock);
1109 [ + - ]: 44584 : o << stro.str();
1110 : 44584 : o.flush();
1111 : 44584 : }
1112 : : operator ostream& () { return stro; }
1113 [ - - + - : 34578 : template <typename T> ostream& operator << (const T& t) { stro << t; return stro; }
+ - + - +
- + - + -
- - - - -
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - + -
+ - + - -
- + - - -
+ - - - +
- + - + -
- - - - -
- - - - -
- - + - -
- + - + -
- - + - +
- - - + -
- - + - -
- - - + -
+ - + - +
- + - + -
- - - - ]
1114 : : };
1115 : : mutex obatched::lock; // just the one, since cout/cerr iostreams are not thread-safe
1116 : :
1117 : :
1118 : 696 : void reportable_exception::report(ostream& o) const {
1119 [ + - + - ]: 696 : obatched(o) << message << endl;
1120 : 696 : }
1121 : :
1122 : :
1123 : : ////////////////////////////////////////////////////////////////////////
1124 : :
1125 : :
1126 : : // RAII style sqlite prepared-statement holder that matches { } block lifetime
1127 : :
1128 : : struct sqlite_ps
1129 : : {
1130 : : private:
1131 : : sqlite3* db;
1132 : : const string nickname;
1133 : : const string sql;
1134 : : sqlite3_stmt *pp;
1135 : : // for step_timeout()/callback
1136 : : struct timespec ts_start;
1137 : : double ts_timeout;
1138 : :
1139 : : sqlite_ps(const sqlite_ps&); // make uncopyable
1140 : : sqlite_ps& operator=(const sqlite_ps &); // make unassignable
1141 : :
1142 : : public:
1143 [ + - - - ]: 9143 : sqlite_ps (sqlite3* d, const string& n, const string& s): db(d), nickname(n), sql(s) {
1144 : : // tmp_ms_metric tick("sqlite3","prep",nickname);
1145 [ + + ]: 9143 : if (verbose > 4)
1146 [ + - + - : 174 : obatched(clog) << nickname << " prep " << sql << endl;
+ - + - +
- - - ]
1147 [ + - ]: 9143 : int rc = sqlite3_prepare_v2 (db, sql.c_str(), -1 /* to \0 */, & this->pp, NULL);
1148 [ - + ]: 9144 : if (rc != SQLITE_OK)
1149 [ # # # # ]: 0 : throw sqlite_exception(rc, "prepare " + sql);
1150 : 18288 : this->reset_timeout(0.0);
1151 : 0 : }
1152 : :
1153 : 190253 : sqlite_ps& reset()
1154 : : {
1155 [ + - + - : 380481 : tmp_ms_metric tick("sqlite3","reset",nickname);
- + - - ]
1156 [ + - ]: 190228 : sqlite3_reset(this->pp);
1157 : 190254 : return *this;
1158 : 190247 : }
1159 : :
1160 : 218103 : sqlite_ps& bind(int parameter, const string& str)
1161 : : {
1162 [ + + ]: 218103 : if (verbose > 4)
1163 [ + - + - : 196 : obatched(clog) << nickname << " bind " << parameter << "=" << str << endl;
+ - + - +
- + - ]
1164 : 218103 : int rc = sqlite3_bind_text (this->pp, parameter, str.c_str(), -1, SQLITE_TRANSIENT);
1165 [ - + ]: 218110 : if (rc != SQLITE_OK)
1166 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 bind");
1167 : 218110 : return *this;
1168 : : }
1169 : :
1170 : 58494 : sqlite_ps& bind(int parameter, int64_t value)
1171 : : {
1172 [ + + ]: 58494 : if (verbose > 4)
1173 [ + - + - : 64 : obatched(clog) << nickname << " bind " << parameter << "=" << value << endl;
+ - + - +
- + - ]
1174 : 58494 : int rc = sqlite3_bind_int64 (this->pp, parameter, value);
1175 [ - + ]: 58499 : if (rc != SQLITE_OK)
1176 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 bind");
1177 : 58499 : return *this;
1178 : : }
1179 : :
1180 : : sqlite_ps& bind(int parameter)
1181 : : {
1182 : : if (verbose > 4)
1183 : : obatched(clog) << nickname << " bind " << parameter << "=" << "NULL" << endl;
1184 : : int rc = sqlite3_bind_null (this->pp, parameter);
1185 : : if (rc != SQLITE_OK)
1186 : : throw sqlite_exception(rc, "sqlite3 bind");
1187 : : return *this;
1188 : : }
1189 : :
1190 : :
1191 : 117225 : void step_ok_done() {
1192 [ + - + - : 234418 : tmp_ms_metric tick("sqlite3","step_done",nickname);
- + - - ]
1193 [ + - ]: 117193 : int rc = sqlite3_step (this->pp);
1194 [ + + ]: 117236 : if (verbose > 4)
1195 [ + - + - : 128 : obatched(clog) << nickname << " step-ok-done(" << sqlite3_errstr(rc) << ") " << sql << endl;
+ - + - +
- + - + -
+ - ]
1196 [ + + - + ]: 117236 : if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
1197 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 step");
1198 [ + - ]: 117236 : (void) sqlite3_reset (this->pp);
1199 : 117236 : }
1200 : :
1201 : :
1202 : 38838 : int step() {
1203 [ + - + - : 77672 : tmp_ms_metric tick("sqlite3","step",nickname);
- + - - ]
1204 [ + - ]: 38834 : int rc = sqlite3_step (this->pp);
1205 [ + + ]: 38838 : if (verbose > 4)
1206 [ + - + - : 62 : obatched(clog) << nickname << " step(" << sqlite3_errstr(rc) << ") " << sql << endl;
+ - + - +
- + - + -
+ - ]
1207 : 38838 : return rc;
1208 : 38838 : }
1209 : :
1210 : :
1211 : 9174 : void reset_timeout(double s) // set starting point for maximum elapsed time in step_timeouts()
1212 : : {
1213 : 9144 : clock_gettime (CLOCK_MONOTONIC, &this->ts_start);
1214 : 9144 : this->ts_timeout = s;
1215 : : }
1216 : :
1217 : :
1218 : 0 : static int sqlite3_progress_handler_cb (void *param)
1219 : : {
1220 : 0 : sqlite_ps *pp = (sqlite_ps*) param;
1221 : 0 : struct timespec ts_end;
1222 : 0 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
1223 : 0 : double deltas = (ts_end.tv_sec - pp->ts_start.tv_sec) + (ts_end.tv_nsec - pp->ts_start.tv_nsec)/1.e9;
1224 [ # # # # ]: 0 : return (interrupted || (deltas > pp->ts_timeout)); // non-zero => interrupt sqlite operation in progress
1225 : : }
1226 : :
1227 : :
1228 : 48 : int step_timeout() {
1229 : : // Do the same thing as step(), except wrapping it into a timeout
1230 : : // relative to the last reset_timeout() invocation.
1231 : : //
1232 : : // Do this by attaching a progress_handler to the database
1233 : : // connection, for the duration of this operation. It should be a
1234 : : // private connection to the calling thread, so other operations
1235 : : // cannot begin concurrently.
1236 : :
1237 : 48 : sqlite3_progress_handler(this->db, 10000 /* bytecode insns */,
1238 : : & sqlite3_progress_handler_cb, (void*) this);
1239 : 48 : int rc = this->step();
1240 : 48 : sqlite3_progress_handler(this->db, 0, 0, 0); // disable
1241 : 48 : struct timespec ts_end;
1242 : 48 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
1243 : 48 : double deltas = (ts_end.tv_sec - this->ts_start.tv_sec) + (ts_end.tv_nsec - this->ts_start.tv_nsec)/1.e9;
1244 [ - + ]: 48 : if (verbose > 3)
1245 [ # # # # : 0 : obatched(clog) << this->nickname << " progress-delta-final " << deltas << endl;
# # # # ]
1246 : 48 : return rc;
1247 : : }
1248 : :
1249 : :
1250 [ + + + + ]: 18127 : ~sqlite_ps () { sqlite3_finalize (this->pp); }
1251 [ + - + - : 6800 : operator sqlite3_stmt* () { return this->pp; }
+ - + - +
- + - + -
+ - + - +
- ]
1252 : : };
1253 : :
1254 : :
1255 : : ////////////////////////////////////////////////////////////////////////
1256 : :
1257 : :
1258 : : struct sqlite_checkpoint_pb: public periodic_barrier
1259 : : {
1260 : : // NB: don't use sqlite_ps since it can throw exceptions during ctor etc.
1261 : 72 : sqlite_checkpoint_pb(unsigned t, unsigned p):
1262 : 144 : periodic_barrier(t, p) { }
1263 : :
1264 : 39 : void periodic_barrier_work() noexcept
1265 : : {
1266 : 39 : (void) sqlite3_exec (db, "pragma wal_checkpoint(truncate);", NULL, NULL, NULL);
1267 : 39 : }
1268 : : };
1269 : :
1270 : : static periodic_barrier* scan_barrier = 0; // initialized in main()
1271 : :
1272 : :
1273 : : ////////////////////////////////////////////////////////////////////////
1274 : :
1275 : : // RAII style templated autocloser
1276 : :
1277 : : template <class Payload, class Ignore>
1278 : : struct defer_dtor
1279 : : {
1280 : : public:
1281 : : typedef Ignore (*dtor_fn) (Payload);
1282 : :
1283 : : private:
1284 : : Payload p;
1285 : : dtor_fn fn;
1286 : :
1287 : : public:
1288 : 5084 : defer_dtor(Payload _p, dtor_fn _fn): p(_p), fn(_fn) {}
1289 : 750 : ~defer_dtor() { (void) (*fn)(p); }
1290 : :
1291 : : private:
1292 : : defer_dtor(const defer_dtor<Payload,Ignore>&); // make uncopyable
1293 : : defer_dtor& operator=(const defer_dtor<Payload,Ignore> &); // make unassignable
1294 : : };
1295 : :
1296 : :
1297 : :
1298 : : ////////////////////////////////////////////////////////////////////////
1299 : :
1300 : :
1301 : : static string
1302 : 6708 : header_censor(const string& str)
1303 : : {
1304 : 6708 : string y;
1305 [ + + ]: 82930 : for (auto&& x : str)
1306 : : {
1307 [ + + ]: 76222 : if (isalnum(x) || x == '/' || x == '.' || x == ',' || x == '_' || x == ':')
1308 [ + - ]: 152438 : y += x;
1309 : : }
1310 : 6708 : return y;
1311 : 0 : }
1312 : :
1313 : :
1314 : : static string
1315 : 3354 : conninfo (struct MHD_Connection * conn)
1316 : : {
1317 : 3354 : char hostname[256]; // RFC1035
1318 : 3354 : char servname[256];
1319 : 3354 : int sts = -1;
1320 : :
1321 [ - + ]: 3354 : if (conn == 0)
1322 : 0 : return "internal";
1323 : :
1324 : : /* Look up client address data. */
1325 : 3354 : const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
1326 : : MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1327 [ + - ]: 3354 : struct sockaddr *so = u ? u->client_addr : 0;
1328 : :
1329 [ + - - + ]: 3354 : if (so && so->sa_family == AF_INET) {
1330 : 0 : sts = getnameinfo (so, sizeof (struct sockaddr_in),
1331 : : hostname, sizeof (hostname),
1332 : : servname, sizeof (servname),
1333 : : NI_NUMERICHOST | NI_NUMERICSERV);
1334 [ + - ]: 3354 : } else if (so && so->sa_family == AF_INET6) {
1335 : 3354 : struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
1336 [ + - + - : 3354 : if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
- + ]
1337 : 3354 : struct sockaddr_in addr4;
1338 : 3354 : memset (&addr4, 0, sizeof(addr4));
1339 : 3354 : addr4.sin_family = AF_INET;
1340 : 3354 : addr4.sin_port = addr6->sin6_port;
1341 : 3354 : memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
1342 : 3354 : sts = getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
1343 : : hostname, sizeof (hostname),
1344 : : servname, sizeof (servname),
1345 : : NI_NUMERICHOST | NI_NUMERICSERV);
1346 : : } else {
1347 : 0 : sts = getnameinfo (so, sizeof (struct sockaddr_in6),
1348 : : hostname, sizeof (hostname),
1349 : : servname, sizeof (servname),
1350 : : NI_NUMERICHOST | NI_NUMERICSERV);
1351 : : }
1352 : : }
1353 : :
1354 [ - + ]: 3354 : if (sts != 0) {
1355 : 0 : hostname[0] = servname[0] = '\0';
1356 : : }
1357 : :
1358 : : // extract headers relevant to administration
1359 [ - + ]: 3354 : const char* user_agent = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
1360 [ + + ]: 3354 : const char* x_forwarded_for = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
1361 : : // NB: these are untrustworthy, beware if machine-processing log files
1362 : :
1363 [ + - + - : 10062 : return string(hostname) + string(":") + string(servname) +
+ - + - +
- + - - +
- + - + -
+ - + - +
- - - - -
- ]
1364 [ + - + - : 14918 : string(" UA:") + header_censor(string(user_agent)) +
+ - + - +
- - + + +
- + + + -
+ - - -
- ]
1365 [ + - + - : 10074 : string(" XFF:") + header_censor(string(x_forwarded_for));
+ - + + +
+ - - ]
1366 : : }
1367 : :
1368 : :
1369 : :
1370 : : ////////////////////////////////////////////////////////////////////////
1371 : :
1372 : : /* Wrapper for MHD_add_response_header that logs an error if we
1373 : : couldn't add the specified header. */
1374 : : static void
1375 : 13184 : add_mhd_response_header (struct MHD_Response *r,
1376 : : const char *h, const char *v)
1377 : : {
1378 [ - + ]: 13184 : if (MHD_add_response_header (r, h, v) == MHD_NO)
1379 [ # # # # : 0 : obatched(clog) << "Error: couldn't add '" << h << "' header" << endl;
# # ]
1380 : 13184 : }
1381 : :
1382 : : static void
1383 : 2128 : add_mhd_last_modified (struct MHD_Response *resp, time_t mtime)
1384 : : {
1385 : 2128 : struct tm now;
1386 : 2128 : struct tm *nowp = gmtime_r (&mtime, &now);
1387 [ + - ]: 2128 : if (nowp != NULL)
1388 : : {
1389 : 2128 : char datebuf[80];
1390 : 2128 : size_t rc = strftime (datebuf, sizeof (datebuf), "%a, %d %b %Y %T GMT",
1391 : : nowp);
1392 [ + - ]: 2128 : if (rc > 0 && rc < sizeof (datebuf))
1393 : 2128 : add_mhd_response_header (resp, "Last-Modified", datebuf);
1394 : : }
1395 : :
1396 : 2128 : add_mhd_response_header (resp, "Cache-Control", "public");
1397 : 2128 : }
1398 : :
1399 : : // quote all questionable characters of str for safe passage through a sh -c expansion.
1400 : : static string
1401 : 64 : shell_escape(const string& str)
1402 : : {
1403 : 64 : string y;
1404 [ + + ]: 4478 : for (auto&& x : str)
1405 : : {
1406 [ + + + + ]: 4414 : if (! isalnum(x) && x != '/')
1407 [ + - ]: 586 : y += "\\";
1408 [ + - ]: 8828 : y += x;
1409 : : }
1410 : 64 : return y;
1411 : 0 : }
1412 : :
1413 : :
1414 : : // PR25548: Perform POSIX / RFC3986 style path canonicalization on the input string.
1415 : : //
1416 : : // Namely:
1417 : : // // -> /
1418 : : // /foo/../ -> /
1419 : : // /./ -> /
1420 : : //
1421 : : // This mapping is done on dwarf-side source path names, which may
1422 : : // include these constructs, so we can deal with debuginfod clients
1423 : : // that accidentally canonicalize the paths.
1424 : : //
1425 : : // realpath(3) is close but not quite right, because it also resolves
1426 : : // symbolic links. Symlinks at the debuginfod server have nothing to
1427 : : // do with the build-time symlinks, thus they must not be considered.
1428 : : //
1429 : : // see also curl Curl_dedotdotify() aka RFC3986, which we mostly follow here
1430 : : // see also libc __realpath()
1431 : : // see also llvm llvm::sys::path::remove_dots()
1432 : : static string
1433 : 16254 : canon_pathname (const string& input)
1434 : : {
1435 : 16254 : string i = input; // 5.2.4 (1)
1436 : 16254 : string o;
1437 : :
1438 : 155004 : while (i.size() != 0)
1439 : : {
1440 : : // 5.2.4 (2) A
1441 [ + - - + : 277500 : if (i.substr(0,3) == "../")
- + ]
1442 [ # # # # ]: 0 : i = i.substr(3);
1443 [ + - - + : 277500 : else if(i.substr(0,2) == "./")
- + ]
1444 [ # # # # ]: 0 : i = i.substr(2);
1445 : :
1446 : : // 5.2.4 (2) B
1447 [ + - - + : 277500 : else if (i.substr(0,3) == "/./")
+ + ]
1448 [ + - + + ]: 2822 : i = i.substr(2);
1449 [ - + ]: 137106 : else if (i == "/.")
1450 [ # # ]: 0 : i = ""; // no need to handle "/." complete-path-segment case; we're dealing with file names
1451 : :
1452 : : // 5.2.4 (2) C
1453 [ + - - + : 274212 : else if (i.substr(0,4) == "/../") {
+ + ]
1454 [ + - + + ]: 2266 : i = i.substr(3);
1455 : 2266 : string::size_type sl = o.rfind("/");
1456 [ + - ]: 2266 : if (sl != string::npos)
1457 [ + - + - ]: 4532 : o = o.substr(0, sl);
1458 : : else
1459 [ # # ]: 0 : o = "";
1460 [ - + ]: 134840 : } else if (i == "/..")
1461 [ # # ]: 0 : i = ""; // no need to handle "/.." complete-path-segment case; we're dealing with file names
1462 : :
1463 : : // 5.2.4 (2) D
1464 : : // no need to handle these cases; we're dealing with file names
1465 [ - + ]: 134840 : else if (i == ".")
1466 [ # # ]: 0 : i = "";
1467 [ - + ]: 134840 : else if (i == "..")
1468 [ # # ]: 0 : i = "";
1469 : :
1470 : : // POSIX special: map // to /
1471 [ + - - + : 269680 : else if (i.substr(0,2) == "//")
+ + ]
1472 [ + - + + ]: 144 : i = i.substr(1);
1473 : :
1474 : : // 5.2.4 (2) E
1475 : : else {
1476 [ - + ]: 134712 : string::size_type next_slash = i.find("/", (i[0]=='/' ? 1 : 0)); // skip first slash
1477 [ + - + + ]: 269424 : o += i.substr(0, next_slash);
1478 [ + + ]: 134712 : if (next_slash == string::npos)
1479 [ + - + + ]: 171258 : i = "";
1480 : : else
1481 [ + - + + : 223788 : i = i.substr(next_slash);
- - ]
1482 : : }
1483 : : }
1484 : :
1485 [ + - ]: 16254 : return o;
1486 : 16254 : }
1487 : :
1488 : :
1489 : : // Estimate available free space for a given filesystem via statfs(2).
1490 : : // Return true if the free fraction is known to be smaller than the
1491 : : // given minimum percentage. Also update a related metric.
1492 : 2972 : bool statfs_free_enough_p(const string& path, const string& label, long minfree = 0)
1493 : : {
1494 : 2972 : struct statfs sfs;
1495 : 2972 : int rc = statfs(path.c_str(), &sfs);
1496 [ + + ]: 2972 : if (rc == 0)
1497 : : {
1498 : 2898 : double s = (double) sfs.f_bavail / (double) sfs.f_blocks;
1499 [ + - + - : 5796 : set_metric("filesys_free_ratio","purpose",label, s);
- + - - ]
1500 : 2898 : return ((s * 100.0) < minfree);
1501 : : }
1502 : : return false;
1503 : : }
1504 : :
1505 : :
1506 : :
1507 : : // A map-like class that owns a cache of file descriptors (indexed by
1508 : : // file / content names).
1509 : : //
1510 : : // If only it could use fd's instead of file names ... but we can't
1511 : : // dup(2) to create independent descriptors for the same unlinked
1512 : : // files, so would have to use some goofy linux /proc/self/fd/%d
1513 : : // hack such as the following
1514 : :
1515 : : #if 0
1516 : : int superdup(int fd)
1517 : : {
1518 : : #ifdef __linux__
1519 : : char *fdpath = NULL;
1520 : : int rc = asprintf(& fdpath, "/proc/self/fd/%d", fd);
1521 : : int newfd;
1522 : : if (rc >= 0)
1523 : : newfd = open(fdpath, O_RDONLY);
1524 : : else
1525 : : newfd = -1;
1526 : : free (fdpath);
1527 : : return newfd;
1528 : : #else
1529 : : return -1;
1530 : : #endif
1531 : : }
1532 : : #endif
1533 : :
1534 : : class libarchive_fdcache
1535 : : {
1536 : : private:
1537 : : mutex fdcache_lock;
1538 : :
1539 : : typedef pair<string,string> key; // archive, entry
1540 [ + - ]: 282 : struct fdcache_entry
1541 : : {
1542 : : string fd; // file name (probably in $TMPDIR), not an actual open fd (EMFILE)
1543 : : double fd_size_mb; // slightly rounded up megabytes
1544 : : time_t freshness; // when was this entry created or requested last
1545 : : unsigned request_count; // how many requests were made; or 0=prefetch only
1546 : : double latency; // how many seconds it took to extract the file
1547 : : };
1548 : :
1549 : : map<key,fdcache_entry> entries; // optimized for lookup
1550 : : time_t last_cleaning;
1551 : : long max_mbs;
1552 : :
1553 : : public:
1554 : 362 : void set_metrics()
1555 : : {
1556 : 362 : double fdcache_mb = 0.0;
1557 : 362 : double prefetch_mb = 0.0;
1558 : 362 : unsigned fdcache_count = 0;
1559 : 362 : unsigned prefetch_count = 0;
1560 [ + + ]: 3474 : for (auto &i : entries) {
1561 [ + + ]: 3112 : if (i.second.request_count) {
1562 : 3018 : fdcache_mb += i.second.fd_size_mb;
1563 : 3018 : fdcache_count ++;
1564 : : } else {
1565 : 94 : prefetch_mb += i.second.fd_size_mb;
1566 : 94 : prefetch_count ++;
1567 : : }
1568 : : }
1569 [ + - ]: 362 : set_metric("fdcache_bytes", fdcache_mb*1024.0*1024.0);
1570 [ + - ]: 362 : set_metric("fdcache_count", fdcache_count);
1571 [ + - ]: 362 : set_metric("fdcache_prefetch_bytes", prefetch_mb*1024.0*1024.0);
1572 [ + - ]: 362 : set_metric("fdcache_prefetch_count", prefetch_count);
1573 : 362 : }
1574 : :
1575 : 284 : void intern(const string& a, const string& b, string fd, off_t sz,
1576 : : bool requested_p, double lat)
1577 : : {
1578 : 284 : {
1579 : 284 : unique_lock<mutex> lock(fdcache_lock);
1580 : 284 : time_t now = time(NULL);
1581 : : // there is a chance it's already in here, just wasn't found last time
1582 : : // if so, there's nothing to do but count our luck
1583 [ + - ]: 284 : auto i = entries.find(make_pair(a,b));
1584 [ + + ]: 284 : if (i != entries.end())
1585 : : {
1586 [ + - + - : 4 : inc_metric("fdcache_op_count","op","redundant_intern");
+ - + - -
+ + - - -
- - ]
1587 [ + - ]: 2 : if (requested_p) i->second.request_count ++; // repeat prefetch doesn't count
1588 : 2 : i->second.freshness = now;
1589 : : // We need to nuke the temp file, since interning passes
1590 : : // responsibility over the path to this structure. It is
1591 : : // possible that the caller still has an fd open, but that's
1592 : : // OK.
1593 : 2 : unlink (fd.c_str());
1594 : 2 : return;
1595 : : }
1596 : 282 : double mb = (sz+65535)/1048576.0; // round up to 64K block
1597 : 282 : fdcache_entry n = { .fd=fd, .fd_size_mb=mb,
1598 : 282 : .freshness=now, .request_count = requested_p?1U:0U,
1599 [ + - + + ]: 282 : .latency=lat};
1600 [ + - + - : 282 : entries.insert(make_pair(make_pair(a,b),n));
+ - ]
1601 : :
1602 [ + + ]: 282 : if (requested_p)
1603 [ + - + - : 472 : inc_metric("fdcache_op_count","op","enqueue");
+ - + - -
+ - + - -
- - ]
1604 : : else
1605 [ + - + - : 138 : inc_metric("fdcache_op_count","op","prefetch_enqueue");
+ - + - -
+ + - - -
- - ]
1606 : :
1607 [ + + ]: 282 : if (verbose > 3)
1608 [ + - + - : 504 : obatched(clog) << "fdcache interned a=" << a << " b=" << b
- - ]
1609 [ + - + - : 168 : << " fd=" << fd << " mb=" << mb << " front=" << requested_p
+ - + - +
- + - + -
+ - ]
1610 [ + - + - : 168 : << " latency=" << lat << endl;
+ - ]
1611 : :
1612 [ + - ]: 282 : set_metrics();
1613 : 284 : }
1614 : :
1615 : : // NB: we age the cache at lookup time too
1616 [ + - - + : 282 : if (statfs_free_enough_p(tmpdir, "tmpdir", fdcache_mintmp))
- + ]
1617 : : {
1618 [ # # # # : 0 : inc_metric("fdcache_op_count","op","emerg-flush");
# # # # #
# # # #
# ]
1619 [ # # ]: 0 : obatched(clog) << "fdcache emergency flush for filling tmpdir" << endl;
1620 : 0 : this->limit(0); // emergency flush
1621 : : }
1622 : : else // age cache normally
1623 : 282 : this->limit(max_mbs);
1624 : : }
1625 : :
1626 : 1014 : int lookup(const string& a, const string& b)
1627 : : {
1628 : 1014 : int fd = -1;
1629 : 1014 : {
1630 : 1014 : unique_lock<mutex> lock(fdcache_lock);
1631 [ + - ]: 1014 : auto i = entries.find(make_pair(a,b));
1632 [ + + ]: 1014 : if (i != entries.end())
1633 : : {
1634 [ + + ]: 772 : if (i->second.request_count == 0) // was a prefetch!
1635 : : {
1636 [ + - + - ]: 12 : inc_metric("fdcache_prefetch_saved_milliseconds_count");
1637 [ + - + - ]: 24 : add_metric("fdcache_prefetch_saved_milliseconds_sum", i->second.latency*1000.);
1638 : : }
1639 : 772 : i->second.request_count ++;
1640 : 772 : i->second.freshness = time(NULL);
1641 : : // brag about our success
1642 [ + - + - : 1544 : inc_metric("fdcache_op_count","op","prefetch_access"); // backward compat
+ - + - -
+ - + - -
- - ]
1643 [ + - + - ]: 772 : inc_metric("fdcache_saved_milliseconds_count");
1644 [ + - + - ]: 772 : add_metric("fdcache_saved_milliseconds_sum", i->second.latency*1000.);
1645 [ + - ]: 1014 : fd = open(i->second.fd.c_str(), O_RDONLY);
1646 : : }
1647 : 0 : }
1648 : :
1649 [ + + ]: 1014 : if (fd >= 0)
1650 [ + - + - : 1544 : inc_metric("fdcache_op_count","op","lookup_hit");
+ - - + -
+ - - -
- ]
1651 : : else
1652 [ + - + - : 484 : inc_metric("fdcache_op_count","op","lookup_miss");
+ - - + -
+ - - -
- ]
1653 : :
1654 : : // NB: no need to age the cache after just a lookup
1655 : :
1656 : 1014 : return fd;
1657 : : }
1658 : :
1659 : 208 : int probe(const string& a, const string& b) // just a cache residency check - don't modify state, don't open
1660 : : {
1661 : 208 : unique_lock<mutex> lock(fdcache_lock);
1662 [ + - ]: 208 : auto i = entries.find(make_pair(a,b));
1663 [ + + ]: 208 : if (i != entries.end()) {
1664 [ + - + - : 56 : inc_metric("fdcache_op_count","op","probe_hit");
+ - + - -
+ - + - -
- - ]
1665 : 28 : return true;
1666 : : } else {
1667 [ + - + - : 360 : inc_metric("fdcache_op_count","op","probe_miss");
+ - + - -
+ - + - -
- - ]
1668 : 180 : return false;
1669 : : }
1670 : 208 : }
1671 : :
1672 : 0 : void clear(const string& a, const string& b)
1673 : : {
1674 : 0 : unique_lock<mutex> lock(fdcache_lock);
1675 [ # # ]: 0 : auto i = entries.find(make_pair(a,b));
1676 [ # # ]: 0 : if (i != entries.end()) {
1677 [ # # # # : 0 : inc_metric("fdcache_op_count","op",
# # # # #
# # # # #
# # # # ]
1678 [ # # ]: 0 : i->second.request_count > 0 ? "clear" : "prefetch_clear");
1679 : 0 : unlink (i->second.fd.c_str());
1680 : 0 : entries.erase(i);
1681 [ # # ]: 0 : set_metrics();
1682 : 0 : return;
1683 : : }
1684 : 0 : }
1685 : :
1686 : 442 : void limit(long maxmbs, bool metrics_p = true)
1687 : : {
1688 : 442 : time_t now = time(NULL);
1689 : :
1690 : : // avoid overly frequent limit operations
1691 [ + + + + ]: 442 : if (maxmbs > 0 && (now - this->last_cleaning) < 10) // probably not worth parametrizing
1692 : 282 : return;
1693 : 160 : this->last_cleaning = now;
1694 : :
1695 [ + + + - ]: 160 : if (verbose > 3 && (this->max_mbs != maxmbs))
1696 [ + - + - ]: 192 : obatched(clog) << "fdcache limited to maxmbs=" << maxmbs << endl;
1697 : :
1698 : 160 : unique_lock<mutex> lock(fdcache_lock);
1699 : :
1700 : 160 : this->max_mbs = maxmbs;
1701 : 160 : double total_mb = 0.0;
1702 : :
1703 : 160 : map<double, pair<string,string>> sorted_entries;
1704 [ + + ]: 442 : for (auto &i: entries)
1705 : : {
1706 : 282 : total_mb += i.second.fd_size_mb;
1707 : :
1708 : : // need a scalar quantity that combines these inputs in a sensible way:
1709 : : //
1710 : : // 1) freshness of this entry (last time it was accessed)
1711 : : // 2) size of this entry
1712 : : // 3) number of times it has been accessed (or if just prefetched with 0 accesses)
1713 : : // 4) latency it required to extract
1714 : : //
1715 : : // The lower the "score", the earlier garbage collection will
1716 : : // nuke it, so to prioritize entries for preservation, the
1717 : : // score should be higher, and vice versa.
1718 : 282 : time_t factor_1_freshness = (now - i.second.freshness); // seconds
1719 : 282 : double factor_2_size = i.second.fd_size_mb; // megabytes
1720 : 282 : unsigned factor_3_accesscount = i.second.request_count; // units
1721 : 282 : double factor_4_latency = i.second.latency; // seconds
1722 : :
1723 : : #if 0
1724 : : double score = - factor_1_freshness; // simple LRU
1725 : : #endif
1726 : :
1727 [ + + ]: 282 : double score = 0.
1728 : 282 : - log1p(factor_1_freshness) // penalize old file
1729 : 282 : - log1p(factor_2_size) // penalize large file
1730 : 282 : + factor_4_latency * factor_3_accesscount; // reward slow + repeatedly read files
1731 : :
1732 [ + + ]: 282 : if (verbose > 4)
1733 [ + - ]: 8 : obatched(clog) << "fdcache scored score=" << score
1734 [ + - + - ]: 8 : << " a=" << i.first.first << " b=" << i.first.second
1735 [ + - + - : 12 : << " f1=" << factor_1_freshness << " f2=" << factor_2_size
+ - + - +
- + - +
- ]
1736 [ + - + - : 4 : << " f3=" << factor_3_accesscount << " f4=" << factor_4_latency
+ - + - +
- ]
1737 : 4 : << endl;
1738 : :
1739 [ + - + - ]: 564 : sorted_entries.insert(make_pair(score, i.first));
1740 : : }
1741 : :
1742 : 160 : unsigned cleaned = 0;
1743 : 160 : unsigned entries_original = entries.size();
1744 : 160 : double cleaned_score_min = DBL_MAX;
1745 : 160 : double cleaned_score_max = DBL_MIN;
1746 : :
1747 : : // drop as many entries[] as needed to bring total mb down to the threshold
1748 [ + + ]: 442 : for (auto &i: sorted_entries) // in increasing score order!
1749 : : {
1750 [ - + ]: 282 : if (this->max_mbs > 0 // if this is not a "clear entire table"
1751 [ # # ]: 0 : && total_mb < this->max_mbs) // we've cleared enough to meet threshold
1752 : : break; // stop clearing
1753 : :
1754 [ - + ]: 282 : auto j = entries.find(i.second);
1755 [ - + ]: 282 : if (j == entries.end())
1756 : 0 : continue; // should not happen
1757 : :
1758 [ + + ]: 282 : if (cleaned == 0)
1759 : 36 : cleaned_score_min = i.first;
1760 : 282 : cleaned++;
1761 : 282 : cleaned_score_max = i.first;
1762 : :
1763 [ + + ]: 282 : if (verbose > 3)
1764 [ + - + - ]: 504 : obatched(clog) << "fdcache evicted score=" << i.first
1765 [ + - + - ]: 336 : << " a=" << i.second.first << " b=" << i.second.second
1766 [ + - + - : 504 : << " fd=" << j->second.fd << " mb=" << j->second.fd_size_mb
+ - + - +
- + - ]
1767 [ + - + - : 168 : << " rq=" << j->second.request_count << " lat=" << j->second.latency
+ - + - ]
1768 [ + - + - : 168 : << " fr=" << (now - j->second.freshness)
+ - ]
1769 : 168 : << endl;
1770 [ - + ]: 282 : if (metrics_p)
1771 [ # # # # : 0 : inc_metric("fdcache_op_count","op","evict");
# # # # #
# # # # #
# # ]
1772 : :
1773 : 282 : total_mb -= j->second.fd_size_mb;
1774 : 282 : unlink (j->second.fd.c_str());
1775 : 282 : entries.erase(j);
1776 : : }
1777 : :
1778 [ + + ]: 160 : if (metrics_p)
1779 [ + - + - : 160 : inc_metric("fdcache_op_count","op","evict_cycle");
+ - + - -
+ - + - -
- - ]
1780 : :
1781 [ + - + + ]: 160 : if (verbose > 1 && cleaned > 0)
1782 : : {
1783 [ + - + - : 108 : obatched(clog) << "fdcache evicted num=" << cleaned << " of=" << entries_original
+ - + - ]
1784 [ + - + - : 36 : << " min=" << cleaned_score_min << " max=" << cleaned_score_max
+ - + - +
- ]
1785 : 36 : << endl;
1786 : : }
1787 : :
1788 [ + + + - ]: 160 : if (metrics_p) set_metrics();
1789 : 160 : }
1790 : :
1791 : :
1792 : 80 : ~libarchive_fdcache()
1793 : : {
1794 : : // unlink any fdcache entries in $TMPDIR
1795 : : // don't update metrics; those globals may be already destroyed
1796 : 80 : limit(0, false);
1797 : 80 : }
1798 : : };
1799 : : static libarchive_fdcache fdcache;
1800 : :
1801 : : /* Search ELF_FD for an ELF/DWARF section with name SECTION.
1802 : : If found copy the section to a temporary file and return
1803 : : its file descriptor, otherwise return -1.
1804 : :
1805 : : The temporary file's mtime will be set to PARENT_MTIME.
1806 : : B_SOURCE should be a description of the parent file suitable
1807 : : for printing to the log. */
1808 : :
1809 : : static int
1810 : 14 : extract_section (int elf_fd, int64_t parent_mtime,
1811 : : const string& b_source, const string& section,
1812 : : const timespec& extract_begin)
1813 : : {
1814 : : /* Search the fdcache. */
1815 : 14 : struct stat fs;
1816 : 14 : int fd = fdcache.lookup (b_source, section);
1817 [ - + ]: 14 : if (fd >= 0)
1818 : : {
1819 [ # # ]: 0 : if (fstat (fd, &fs) != 0)
1820 : : {
1821 [ # # ]: 0 : if (verbose)
1822 [ # # ]: 0 : obatched (clog) << "cannot fstate fdcache "
1823 [ # # # # : 0 : << b_source << " " << section << endl;
# # ]
1824 : 0 : close (fd);
1825 : 0 : return -1;
1826 : : }
1827 [ # # ]: 0 : if ((int64_t) fs.st_mtime != parent_mtime)
1828 : : {
1829 [ # # ]: 0 : if (verbose)
1830 [ # # ]: 0 : obatched(clog) << "mtime mismatch for "
1831 [ # # # # : 0 : << b_source << " " << section << endl;
# # ]
1832 : 0 : close (fd);
1833 : 0 : return -1;
1834 : : }
1835 : : /* Success. */
1836 : : return fd;
1837 : : }
1838 : :
1839 : 14 : Elf *elf = elf_begin (elf_fd, ELF_C_READ_MMAP_PRIVATE, NULL);
1840 [ - + ]: 14 : if (elf == NULL)
1841 : : return -1;
1842 : :
1843 : : /* Try to find the section and copy the contents into a separate file. */
1844 : 14 : try
1845 : : {
1846 : 14 : size_t shstrndx;
1847 [ + - ]: 14 : int rc = elf_getshdrstrndx (elf, &shstrndx);
1848 [ - + ]: 14 : if (rc < 0)
1849 [ # # # # ]: 0 : throw elfutils_exception (rc, "getshdrstrndx");
1850 : :
1851 : : Elf_Scn *scn = NULL;
1852 : 482 : while (true)
1853 : : {
1854 [ + - ]: 248 : scn = elf_nextscn (elf, scn);
1855 [ + - ]: 248 : if (scn == NULL)
1856 : : break;
1857 : 248 : GElf_Shdr shdr_storage;
1858 [ + - ]: 248 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
1859 [ + - ]: 248 : if (shdr == NULL)
1860 : : break;
1861 : :
1862 [ + - ]: 248 : const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
1863 [ + - ]: 248 : if (scn_name == NULL)
1864 : : break;
1865 [ + + ]: 248 : if (scn_name == section)
1866 : : {
1867 : 14 : Elf_Data *data = NULL;
1868 : :
1869 : : /* We found the desired section. */
1870 [ + - ]: 14 : data = elf_rawdata (scn, NULL);
1871 [ - + ]: 14 : if (data == NULL)
1872 [ # # # # : 0 : throw elfutils_exception (elf_errno (), "elfraw_data");
# # ]
1873 [ + + ]: 14 : if (data->d_buf == NULL)
1874 : : {
1875 [ + - + - ]: 12 : obatched(clog) << "section " << section
1876 [ + - + - ]: 6 : << " is empty" << endl;
1877 : 6 : break;
1878 : : }
1879 : :
1880 : : /* Create temporary file containing the section. */
1881 : 8 : char *tmppath = NULL;
1882 : 8 : rc = asprintf (&tmppath, "%s/debuginfod-section.XXXXXX", tmpdir.c_str());
1883 [ - + ]: 8 : if (rc < 0)
1884 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
1885 : 8 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
1886 [ + - ]: 8 : fd = mkstemp (tmppath);
1887 [ - + ]: 8 : if (fd < 0)
1888 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
1889 : :
1890 [ + - ]: 8 : ssize_t res = write_retry (fd, data->d_buf, data->d_size);
1891 [ + - - + ]: 8 : if (res < 0 || (size_t) res != data->d_size) {
1892 [ # # ]: 0 : close (fd);
1893 : 0 : unlink (tmppath);
1894 [ # # # # ]: 0 : throw libc_exception (errno, "cannot write to temporary file");
1895 : : }
1896 : :
1897 : : /* Set mtime to be the same as the parent file's mtime. */
1898 : 8 : struct timespec tvs[2];
1899 [ - + ]: 8 : if (fstat (elf_fd, &fs) != 0) {
1900 [ # # ]: 0 : close (fd);
1901 : 0 : unlink (tmppath);
1902 [ # # # # ]: 0 : throw libc_exception (errno, "cannot fstat file");
1903 : : }
1904 : :
1905 : 8 : tvs[0].tv_sec = 0;
1906 : 8 : tvs[0].tv_nsec = UTIME_OMIT;
1907 : 8 : tvs[1] = fs.st_mtim;
1908 : 8 : (void) futimens (fd, tvs);
1909 : :
1910 : 8 : struct timespec extract_end;
1911 : 8 : clock_gettime (CLOCK_MONOTONIC, &extract_end);
1912 : 8 : double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
1913 : 8 : + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
1914 : :
1915 : : /* Add to fdcache. */
1916 [ + - + - ]: 8 : fdcache.intern (b_source, section, tmppath, data->d_size, true, extract_time);
1917 : 8 : break;
1918 : 14 : }
1919 : 234 : }
1920 : : }
1921 [ - - ]: 0 : catch (const reportable_exception &e)
1922 : : {
1923 [ - - ]: 0 : e.report (clog);
1924 [ - - ]: 0 : close (fd);
1925 : 0 : fd = -1;
1926 : 0 : }
1927 : :
1928 : 14 : elf_end (elf);
1929 : : return fd;
1930 : : }
1931 : :
1932 : : static struct MHD_Response*
1933 : 1128 : handle_buildid_f_match (bool internal_req_t,
1934 : : int64_t b_mtime,
1935 : : const string& b_source0,
1936 : : const string& section,
1937 : : int *result_fd)
1938 : : {
1939 : 1128 : (void) internal_req_t; // ignored
1940 : :
1941 : 1128 : struct timespec extract_begin;
1942 : 1128 : clock_gettime (CLOCK_MONOTONIC, &extract_begin);
1943 : :
1944 : 1128 : int fd = open(b_source0.c_str(), O_RDONLY);
1945 [ - + ]: 1128 : if (fd < 0)
1946 [ # # # # : 0 : throw libc_exception (errno, string("open ") + b_source0);
# # # # ]
1947 : :
1948 : : // NB: use manual close(2) in error case instead of defer_dtor, because
1949 : : // in the normal case, we want to hand the fd over to libmicrohttpd for
1950 : : // file transfer.
1951 : :
1952 : 1128 : struct stat s;
1953 : 1128 : int rc = fstat(fd, &s);
1954 [ - + ]: 1128 : if (rc < 0)
1955 : : {
1956 : 0 : close(fd);
1957 [ # # # # : 0 : throw libc_exception (errno, string("fstat ") + b_source0);
# # # # ]
1958 : : }
1959 : :
1960 [ - + ]: 1128 : if ((int64_t) s.st_mtime != b_mtime)
1961 : : {
1962 [ # # ]: 0 : if (verbose)
1963 [ # # # # ]: 0 : obatched(clog) << "mtime mismatch for " << b_source0 << endl;
1964 : 0 : close(fd);
1965 : 0 : return 0;
1966 : : }
1967 : :
1968 [ + + ]: 1128 : if (!section.empty ())
1969 : : {
1970 : 6 : int scn_fd = extract_section (fd, s.st_mtime, b_source0, section, extract_begin);
1971 : 6 : close (fd);
1972 : :
1973 [ + + ]: 6 : if (scn_fd >= 0)
1974 : 4 : fd = scn_fd;
1975 : : else
1976 : : {
1977 [ + - ]: 2 : if (verbose)
1978 [ + - ]: 6 : obatched (clog) << "cannot find section " << section
1979 [ + - + - : 2 : << " for " << b_source0 << endl;
+ - ]
1980 : 2 : return 0;
1981 : : }
1982 : :
1983 : 4 : rc = fstat(fd, &s);
1984 [ - + ]: 4 : if (rc < 0)
1985 : : {
1986 : 0 : close (fd);
1987 [ # # # # : 0 : throw libc_exception (errno, string ("fstat ") + b_source0
# # # # #
# # # #
# ]
1988 [ # # # # : 0 : + string (" ") + section);
# # # # #
# ]
1989 : : }
1990 : : }
1991 : :
1992 : 1126 : struct MHD_Response* r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
1993 [ + - + - : 2252 : inc_metric ("http_responses_total","result","file");
+ - - + -
+ - - -
- ]
1994 [ - + ]: 1126 : if (r == 0)
1995 : : {
1996 [ # # ]: 0 : if (verbose)
1997 [ # # ]: 0 : obatched(clog) << "cannot create fd-response for " << b_source0
1998 [ # # # # : 0 : << " section=" << section << endl;
# # ]
1999 : 0 : close(fd);
2000 : : }
2001 : : else
2002 : : {
2003 : 1126 : add_mhd_response_header (r, "Content-Type", "application/octet-stream");
2004 [ + - ]: 1126 : add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
2005 : 1126 : to_string(s.st_size).c_str());
2006 : 1126 : add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source0.c_str());
2007 : 1126 : add_mhd_last_modified (r, s.st_mtime);
2008 [ + - ]: 1126 : if (verbose > 1)
2009 [ + - + - : 2252 : obatched(clog) << "serving file " << b_source0 << " section=" << section << endl;
+ - + - ]
2010 : : /* libmicrohttpd will close it. */
2011 [ - + ]: 1126 : if (result_fd)
2012 : 1126 : *result_fd = fd;
2013 : : }
2014 : :
2015 : : return r;
2016 : : }
2017 : :
2018 : :
2019 : : #ifdef USE_LZMA
2020 : : struct lzma_exception: public reportable_exception
2021 : : {
2022 : 0 : lzma_exception(int rc, const string& msg):
2023 : : // liblzma doesn't have a lzma_ret -> string conversion function, so just
2024 : : // report the value.
2025 [ # # # # : 0 : reportable_exception(string ("lzma error: ") + msg + ": error " + to_string(rc)) {
# # # # #
# # # # #
# # # # ]
2026 [ # # # # : 0 : inc_metric("error_count","lzma",to_string(rc));
# # # # #
# # # #
# ]
2027 [ # # ]: 0 : }
2028 : : };
2029 : :
2030 : : // Neither RPM nor deb files support seeking to a specific file in the package.
2031 : : // Instead, to extract a specific file, we normally need to read the archive
2032 : : // sequentially until we find the file. This is very slow for files at the end
2033 : : // of a large package with lots of files, like kernel debuginfo.
2034 : : //
2035 : : // However, if the compression format used in the archive supports seeking, we
2036 : : // can accelerate this. As of July 2024, xz is the only widely-used format that
2037 : : // supports seeking, and usually only in multi-threaded mode. Luckily, the
2038 : : // kernel-debuginfo package in Fedora and its downstreams, and the
2039 : : // linux-image-*-dbg package in Debian and its downstreams, all happen to use
2040 : : // this.
2041 : : //
2042 : : // The xz format [1] ends with an index of independently compressed blocks in
2043 : : // the stream. In RPM and deb files, the xz stream is the last thing in the
2044 : : // file, so we assume that the xz Stream Footer is at the end of the package
2045 : : // file and do everything relative to that. For each file in the archive, we
2046 : : // remember the size and offset of the file data in the uncompressed xz stream,
2047 : : // then we use the index to seek to that offset when we need that file.
2048 : : //
2049 : : // 1: https://xz.tukaani.org/format/xz-file-format.txt
2050 : :
2051 : : // Return whether an archive supports seeking.
2052 : : static bool
2053 : 530 : is_seekable_archive (const string& rps, struct archive* a)
2054 : : {
2055 : : // Only xz supports seeking.
2056 [ + + ]: 530 : if (archive_filter_code (a, 0) != ARCHIVE_FILTER_XZ)
2057 : : return false;
2058 : :
2059 : 336 : int fd = open (rps.c_str(), O_RDONLY);
2060 [ - + ]: 336 : if (fd < 0)
2061 : : return false;
2062 : 336 : defer_dtor<int,int> fd_closer (fd, close);
2063 : :
2064 : : // Seek to the xz Stream Footer. We assume that it's the last thing in the
2065 : : // file, which is true for RPM and deb files.
2066 : 336 : off_t footer_pos = -LZMA_STREAM_HEADER_SIZE;
2067 [ - + ]: 336 : if (lseek (fd, footer_pos, SEEK_END) == -1)
2068 : : return false;
2069 : :
2070 : : // Decode the Stream Footer.
2071 : : uint8_t footer[LZMA_STREAM_HEADER_SIZE];
2072 : : size_t footer_read = 0;
2073 [ + + ]: 672 : while (footer_read < sizeof (footer))
2074 : : {
2075 [ - + ]: 336 : ssize_t bytes_read = read (fd, footer + footer_read,
2076 : : sizeof (footer) - footer_read);
2077 [ - + ]: 336 : if (bytes_read < 0)
2078 : : {
2079 [ # # ]: 0 : if (errno == EINTR)
2080 : 0 : continue;
2081 : : return false;
2082 : : }
2083 [ - + ]: 336 : if (bytes_read == 0)
2084 : : return false;
2085 : 336 : footer_read += bytes_read;
2086 : : }
2087 : :
2088 : 336 : lzma_stream_flags stream_flags;
2089 : 336 : lzma_ret ret = lzma_stream_footer_decode (&stream_flags, footer);
2090 [ - + ]: 336 : if (ret != LZMA_OK)
2091 : : return false;
2092 : :
2093 : : // Seek to the xz Index.
2094 [ - + ]: 336 : if (lseek (fd, footer_pos - stream_flags.backward_size, SEEK_END) == -1)
2095 : : return false;
2096 : :
2097 : : // Decode the Number of Records in the Index. liblzma doesn't have an API for
2098 : : // this if you don't want to decode the whole Index, so we have to do it
2099 : : // ourselves.
2100 : : //
2101 : : // We need 1 byte for the Index Indicator plus 1-9 bytes for the
2102 : : // variable-length integer Number of Records.
2103 : : uint8_t index[10];
2104 : : size_t index_read = 0;
2105 [ + + ]: 672 : while (index_read == 0) {
2106 [ + - ]: 336 : ssize_t bytes_read = read (fd, index, sizeof (index));
2107 [ - + ]: 336 : if (bytes_read < 0)
2108 : : {
2109 [ # # ]: 0 : if (errno == EINTR)
2110 : 0 : continue;
2111 : : return false;
2112 : : }
2113 [ - + ]: 336 : if (bytes_read == 0)
2114 : : return false;
2115 : 336 : index_read += bytes_read;
2116 : : }
2117 : : // The Index Indicator must be 0.
2118 [ - + ]: 336 : if (index[0] != 0)
2119 : : return false;
2120 : :
2121 : 336 : lzma_vli num_records;
2122 : 336 : size_t pos = 0;
2123 : 336 : size_t in_pos = 1;
2124 : 336 : while (true)
2125 : : {
2126 [ - + ]: 336 : if (in_pos >= index_read)
2127 : : {
2128 [ # # ]: 0 : ssize_t bytes_read = read (fd, index, sizeof (index));
2129 [ # # ]: 0 : if (bytes_read < 0)
2130 : : {
2131 [ # # ]: 0 : if (errno == EINTR)
2132 : 0 : continue;
2133 : : return false;
2134 : : }
2135 [ # # ]: 0 : if (bytes_read == 0)
2136 : : return false;
2137 : 0 : index_read = bytes_read;
2138 : 0 : in_pos = 0;
2139 : : }
2140 : 336 : ret = lzma_vli_decode (&num_records, &pos, index, &in_pos, index_read);
2141 [ - + ]: 336 : if (ret == LZMA_STREAM_END)
2142 : : break;
2143 [ # # ]: 0 : else if (ret != LZMA_OK)
2144 : : return false;
2145 : : }
2146 : :
2147 [ + + ]: 336 : if (verbose > 3)
2148 [ + - + - : 572 : obatched(clog) << rps << " has " << num_records << " xz Blocks" << endl;
+ - + - +
- ]
2149 : :
2150 : : // The file is only seekable if it has more than one Block.
2151 : 336 : return num_records > 1;
2152 : 530 : }
2153 : :
2154 : : // Read the Index at the end of an xz file.
2155 : : static lzma_index*
2156 : 94 : read_xz_index (int fd)
2157 : : {
2158 : 94 : off_t footer_pos = -LZMA_STREAM_HEADER_SIZE;
2159 [ - + ]: 94 : if (lseek (fd, footer_pos, SEEK_END) == -1)
2160 [ # # # # ]: 0 : throw libc_exception (errno, "lseek");
2161 : :
2162 : : uint8_t footer[LZMA_STREAM_HEADER_SIZE];
2163 : : size_t footer_read = 0;
2164 [ + + ]: 188 : while (footer_read < sizeof (footer))
2165 : : {
2166 [ - + ]: 94 : ssize_t bytes_read = read (fd, footer + footer_read,
2167 : : sizeof (footer) - footer_read);
2168 [ - + ]: 94 : if (bytes_read < 0)
2169 : : {
2170 [ # # ]: 0 : if (errno == EINTR)
2171 : 0 : continue;
2172 [ # # # # ]: 0 : throw libc_exception (errno, "read");
2173 : : }
2174 [ - + ]: 94 : if (bytes_read == 0)
2175 [ # # # # ]: 0 : throw reportable_exception ("truncated file");
2176 : 94 : footer_read += bytes_read;
2177 : : }
2178 : :
2179 : 94 : lzma_stream_flags stream_flags;
2180 : 94 : lzma_ret ret = lzma_stream_footer_decode (&stream_flags, footer);
2181 [ - + ]: 94 : if (ret != LZMA_OK)
2182 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_stream_footer_decode");
2183 : :
2184 [ - + ]: 94 : if (lseek (fd, footer_pos - stream_flags.backward_size, SEEK_END) == -1)
2185 [ # # # # ]: 0 : throw libc_exception (errno, "lseek");
2186 : :
2187 : 94 : lzma_stream strm = LZMA_STREAM_INIT;
2188 : 94 : lzma_index* index = NULL;
2189 : 94 : ret = lzma_index_decoder (&strm, &index, UINT64_MAX);
2190 [ - + ]: 94 : if (ret != LZMA_OK)
2191 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_index_decoder");
2192 : 94 : defer_dtor<lzma_stream*,void> strm_ender (&strm, lzma_end);
2193 : :
2194 : 94 : uint8_t in_buf[4096];
2195 : 94 : while (true)
2196 : : {
2197 [ + - ]: 94 : if (strm.avail_in == 0)
2198 : : {
2199 [ + - ]: 94 : ssize_t bytes_read = read (fd, in_buf, sizeof (in_buf));
2200 [ - + ]: 94 : if (bytes_read < 0)
2201 : : {
2202 [ # # ]: 0 : if (errno == EINTR)
2203 : 0 : continue;
2204 [ # # # # ]: 0 : throw libc_exception (errno, "read");
2205 : : }
2206 [ - + ]: 94 : if (bytes_read == 0)
2207 [ # # # # ]: 0 : throw reportable_exception ("truncated file");
2208 : 94 : strm.avail_in = bytes_read;
2209 : 94 : strm.next_in = in_buf;
2210 : : }
2211 : :
2212 : 94 : ret = lzma_code (&strm, LZMA_RUN);
2213 [ - + ]: 94 : if (ret == LZMA_STREAM_END)
2214 : : break;
2215 [ # # ]: 0 : else if (ret != LZMA_OK)
2216 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_code index");
2217 : : }
2218 : :
2219 : 94 : ret = lzma_index_stream_flags (index, &stream_flags);
2220 [ - + ]: 94 : if (ret != LZMA_OK)
2221 : : {
2222 : 0 : lzma_index_end (index, NULL);
2223 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_index_stream_flags");
2224 : : }
2225 : 94 : return index;
2226 : 94 : }
2227 : :
2228 : : static void
2229 : 94 : my_lzma_index_end (lzma_index* index)
2230 : : {
2231 : 94 : lzma_index_end (index, NULL);
2232 : 94 : }
2233 : :
2234 : : static void
2235 : 102 : free_lzma_block_filter_options (lzma_block* block)
2236 : : {
2237 [ + + ]: 510 : for (int i = 0; i < LZMA_FILTERS_MAX; i++)
2238 : : {
2239 : 408 : free (block->filters[i].options);
2240 : 408 : block->filters[i].options = NULL;
2241 : : }
2242 : 102 : }
2243 : :
2244 : : static void
2245 : 94 : free_lzma_block_filters (lzma_block* block)
2246 : : {
2247 [ + - ]: 94 : if (block->filters != NULL)
2248 : : {
2249 : 94 : free_lzma_block_filter_options (block);
2250 : 94 : free (block->filters);
2251 : : }
2252 : 94 : }
2253 : :
2254 : : static void
2255 : 94 : extract_xz_blocks_into_fd (const string& srcpath,
2256 : : int src,
2257 : : int dst,
2258 : : lzma_index_iter* iter,
2259 : : uint64_t offset,
2260 : : uint64_t size)
2261 : : {
2262 : : // Seek to the Block. Seeking from the end using the compressed size from the
2263 : : // footer means we don't need to know where the xz stream starts in the
2264 : : // archive.
2265 [ - + ]: 94 : if (lseek (src,
2266 : 94 : (off_t) iter->block.compressed_stream_offset
2267 : 94 : - (off_t) iter->stream.compressed_size,
2268 : : SEEK_END) == -1)
2269 [ # # # # ]: 0 : throw libc_exception (errno, "lseek");
2270 : :
2271 : 94 : offset -= iter->block.uncompressed_file_offset;
2272 : :
2273 : 94 : lzma_block block{};
2274 : 94 : block.filters = (lzma_filter*) calloc (LZMA_FILTERS_MAX + 1,
2275 : : sizeof (lzma_filter));
2276 [ - + ]: 94 : if (block.filters == NULL)
2277 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate lzma_block filters");
2278 : 94 : defer_dtor<lzma_block*,void> filters_freer (&block, free_lzma_block_filters);
2279 : :
2280 : 94 : uint8_t in_buf[4096];
2281 : 94 : uint8_t out_buf[4096];
2282 : 94 : size_t header_read = 0;
2283 : 94 : bool need_log_extracting = verbose > 3;
2284 : : while (true)
2285 : : {
2286 : : // The first byte of the Block is the encoded Block Header Size. Read the
2287 : : // first byte and whatever extra fits in the buffer.
2288 [ + + ]: 196 : while (header_read == 0)
2289 : : {
2290 [ + - ]: 94 : ssize_t bytes_read = read (src, in_buf, sizeof (in_buf));
2291 [ - + ]: 94 : if (bytes_read < 0)
2292 : : {
2293 [ # # ]: 0 : if (errno == EINTR)
2294 : 0 : continue;
2295 [ # # # # ]: 0 : throw libc_exception (errno, "read");
2296 : : }
2297 [ - + ]: 94 : if (bytes_read == 0)
2298 [ # # # # ]: 0 : throw reportable_exception ("truncated file");
2299 : 94 : header_read += bytes_read;
2300 : : }
2301 : :
2302 : 102 : block.header_size = lzma_block_header_size_decode (in_buf[0]);
2303 : :
2304 : : // If we didn't buffer the whole Block Header earlier, get the rest.
2305 : 102 : eu_static_assert (sizeof (in_buf)
2306 : : >= lzma_block_header_size_decode (UINT8_MAX));
2307 [ - + ]: 102 : while (header_read < block.header_size)
2308 : : {
2309 [ # # ]: 0 : ssize_t bytes_read = read (src, in_buf + header_read,
2310 : : sizeof (in_buf) - header_read);
2311 [ # # ]: 0 : if (bytes_read < 0)
2312 : : {
2313 [ # # ]: 0 : if (errno == EINTR)
2314 : 0 : continue;
2315 [ # # # # ]: 0 : throw libc_exception (errno, "read");
2316 : : }
2317 [ # # ]: 0 : if (bytes_read == 0)
2318 [ # # # # ]: 0 : throw reportable_exception ("truncated file");
2319 : 0 : header_read += bytes_read;
2320 : : }
2321 : :
2322 : : // Decode the Block Header.
2323 : 102 : block.check = iter->stream.flags->check;
2324 : 102 : lzma_ret ret = lzma_block_header_decode (&block, NULL, in_buf);
2325 [ - + ]: 102 : if (ret != LZMA_OK)
2326 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_block_header_decode");
2327 : 102 : ret = lzma_block_compressed_size (&block, iter->block.unpadded_size);
2328 [ - + ]: 102 : if (ret != LZMA_OK)
2329 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_block_compressed_size");
2330 : :
2331 : : // Start decoding the Block data.
2332 : 102 : lzma_stream strm = LZMA_STREAM_INIT;
2333 : 102 : ret = lzma_block_decoder (&strm, &block);
2334 [ - + ]: 102 : if (ret != LZMA_OK)
2335 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_block_decoder");
2336 : 102 : defer_dtor<lzma_stream*,void> strm_ender (&strm, lzma_end);
2337 : :
2338 : : // We might still have some input buffered from when we read the header.
2339 : 102 : strm.avail_in = header_read - block.header_size;
2340 : 102 : strm.next_in = in_buf + block.header_size;
2341 : 102 : strm.avail_out = sizeof (out_buf);
2342 : 102 : strm.next_out = out_buf;
2343 : 11518 : while (true)
2344 : : {
2345 [ + + ]: 11518 : if (strm.avail_in == 0)
2346 : : {
2347 [ + - ]: 14 : ssize_t bytes_read = read (src, in_buf, sizeof (in_buf));
2348 [ - + ]: 14 : if (bytes_read < 0)
2349 : : {
2350 [ # # ]: 0 : if (errno == EINTR)
2351 : 0 : continue;
2352 [ # # # # ]: 0 : throw libc_exception (errno, "read");
2353 : : }
2354 [ - + ]: 14 : if (bytes_read == 0)
2355 [ # # # # ]: 0 : throw reportable_exception ("truncated file");
2356 : 14 : strm.avail_in = bytes_read;
2357 : 14 : strm.next_in = in_buf;
2358 : : }
2359 : :
2360 : 11518 : ret = lzma_code (&strm, LZMA_RUN);
2361 [ - + ]: 11518 : if (ret != LZMA_OK && ret != LZMA_STREAM_END)
2362 [ # # # # ]: 0 : throw lzma_exception (ret, "lzma_code block");
2363 : :
2364 : : // Throw away anything we decode until we reach the offset, then
2365 : : // start writing to the destination.
2366 [ + + ]: 11518 : if (strm.total_out > offset)
2367 : : {
2368 : 2898 : size_t bytes_to_write = strm.next_out - out_buf;
2369 : 2898 : uint8_t* buf_to_write = out_buf;
2370 : :
2371 : : // Ignore anything in the buffer before the offset.
2372 [ + + ]: 2898 : if (bytes_to_write > strm.total_out - offset)
2373 : : {
2374 : 88 : buf_to_write += bytes_to_write - (strm.total_out - offset);
2375 : 88 : bytes_to_write = strm.total_out - offset;
2376 : : }
2377 : :
2378 : : // Ignore anything after the size.
2379 [ + + ]: 2898 : if (strm.total_out - offset >= size)
2380 : 94 : bytes_to_write -= strm.total_out - offset - size;
2381 : :
2382 [ + + ]: 2898 : if (need_log_extracting)
2383 : : {
2384 [ + - + - ]: 24 : obatched(clog) << "extracting from xz archive " << srcpath
2385 [ + - + - : 12 : << " size=" << size << endl;
+ - ]
2386 : 12 : need_log_extracting = false;
2387 : : }
2388 : :
2389 [ + + ]: 5796 : while (bytes_to_write > 0)
2390 : : {
2391 [ + - ]: 2898 : ssize_t written = write (dst, buf_to_write, bytes_to_write);
2392 [ - + ]: 2898 : if (written < 0)
2393 : : {
2394 [ # # ]: 0 : if (errno == EAGAIN)
2395 : 0 : continue;
2396 [ # # # # ]: 0 : throw libc_exception (errno, "write");
2397 : : }
2398 : 2898 : bytes_to_write -= written;
2399 : 2898 : buf_to_write += written;
2400 : : }
2401 : :
2402 : : // If we reached the size, we're done.
2403 [ + + ]: 2898 : if (strm.total_out - offset >= size)
2404 : 94 : return;
2405 : : }
2406 : :
2407 : 11424 : strm.avail_out = sizeof (out_buf);
2408 : 11424 : strm.next_out = out_buf;
2409 : :
2410 [ + + ]: 11424 : if (ret == LZMA_STREAM_END)
2411 : : break;
2412 : : }
2413 : :
2414 : : // This Block didn't have enough data. Go to the next one.
2415 [ - + ]: 8 : if (lzma_index_iter_next (iter, LZMA_INDEX_ITER_BLOCK))
2416 [ # # # # ]: 0 : throw reportable_exception ("no more blocks");
2417 [ + - ]: 8 : if (strm.total_out > offset)
2418 : 8 : size -= strm.total_out - offset;
2419 : 8 : offset = 0;
2420 : : // If we had any buffered input left, move it to the beginning of the
2421 : : // buffer to decode the next Block Header.
2422 [ + - ]: 8 : if (strm.avail_in > 0)
2423 : : {
2424 : 8 : memmove (in_buf, strm.next_in, strm.avail_in);
2425 : 8 : header_read = strm.avail_in;
2426 : : }
2427 : : else
2428 : : header_read = 0;
2429 : 8 : free_lzma_block_filter_options (&block);
2430 : 102 : }
2431 : 94 : }
2432 : :
2433 : : static int
2434 : 94 : extract_from_seekable_archive (const string& srcpath,
2435 : : char* tmppath,
2436 : : uint64_t offset,
2437 : : uint64_t size)
2438 : : {
2439 [ + - + - : 188 : inc_metric ("seekable_archive_extraction_attempts","type","xz");
+ - - + -
+ - - -
- ]
2440 : 94 : try
2441 : : {
2442 [ + - ]: 94 : int src = open (srcpath.c_str(), O_RDONLY);
2443 [ - + ]: 94 : if (src < 0)
2444 [ # # # # : 0 : throw libc_exception (errno, string("open ") + srcpath);
# # # # ]
2445 : 94 : defer_dtor<int,int> src_closer (src, close);
2446 : :
2447 [ + - ]: 94 : lzma_index* index = read_xz_index (src);
2448 : 94 : defer_dtor<lzma_index*,void> index_ender (index, my_lzma_index_end);
2449 : :
2450 : : // Find the Block containing the offset.
2451 : 94 : lzma_index_iter iter;
2452 : 94 : lzma_index_iter_init (&iter, index);
2453 [ - + ]: 94 : if (lzma_index_iter_locate (&iter, offset))
2454 [ # # # # ]: 0 : throw reportable_exception ("offset not found");
2455 : :
2456 [ + + ]: 94 : if (verbose > 3)
2457 [ + - + - ]: 36 : obatched(clog) << "seeking in xz archive " << srcpath
2458 [ + - + - : 12 : << " offset=" << offset << " block_offset="
+ - ]
2459 [ + - + - ]: 12 : << iter.block.uncompressed_file_offset << endl;
2460 : :
2461 [ + - ]: 94 : int dst = mkstemp (tmppath);
2462 [ - + ]: 94 : if (dst < 0)
2463 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
2464 : :
2465 : 94 : try
2466 : : {
2467 [ + - ]: 94 : extract_xz_blocks_into_fd (srcpath, src, dst, &iter, offset, size);
2468 : : }
2469 : 0 : catch (...)
2470 : : {
2471 : 0 : unlink (tmppath);
2472 [ - - ]: 0 : close (dst);
2473 : 0 : throw;
2474 : 0 : }
2475 : :
2476 [ + - + - : 188 : inc_metric ("seekable_archive_extraction_successes","type","xz");
+ - + - -
+ - + - -
- - ]
2477 : 94 : return dst;
2478 : 94 : }
2479 [ - - ]: 0 : catch (const reportable_exception &e)
2480 : : {
2481 [ - - - - : 0 : inc_metric ("seekable_archive_extraction_failures","type","xz");
- - - - -
- - - - -
- - ]
2482 [ - - ]: 0 : if (verbose)
2483 [ - - - - ]: 0 : obatched(clog) << "failed to extract from seekable xz archive "
2484 [ - - - - : 0 : << srcpath << ": " << e.message << endl;
- - ]
2485 : 0 : return -1;
2486 : 0 : }
2487 : : }
2488 : : #else
2489 : : static bool
2490 : : is_seekable_archive (const string& rps, struct archive* a)
2491 : : {
2492 : : return false;
2493 : : }
2494 : : static int
2495 : : extract_from_seekable_archive (const string& srcpath,
2496 : : char* tmppath,
2497 : : uint64_t offset,
2498 : : uint64_t size)
2499 : : {
2500 : : return -1;
2501 : : }
2502 : : #endif
2503 : :
2504 : :
2505 : : // For security/portability reasons, many distro-package archives have
2506 : : // a "./" in front of path names; others have nothing, others have
2507 : : // "/". Canonicalize them all to a single leading "/", with the
2508 : : // assumption that this matches the dwarf-derived file names too.
2509 : 1314 : string canonicalized_archive_entry_pathname(struct archive_entry *e)
2510 : : {
2511 : 1314 : string fn = archive_entry_pathname(e);
2512 [ - + ]: 1313 : if (fn.size() == 0)
2513 : 0 : return fn;
2514 [ - + ]: 1313 : if (fn[0] == '/')
2515 : 0 : return fn;
2516 [ + + ]: 1313 : if (fn[0] == '.')
2517 [ + - ]: 1081 : return fn.substr(1);
2518 : : else
2519 [ + - + - : 464 : return string("/")+fn;
- - ]
2520 : 1313 : }
2521 : :
2522 : :
2523 : : // NB: takes ownership of, and may reassign, fd.
2524 : : static struct MHD_Response*
2525 : 1002 : create_buildid_r_response (int64_t b_mtime0,
2526 : : const string& b_source0,
2527 : : const string& b_source1,
2528 : : const string& section,
2529 : : const string& ima_sig,
2530 : : const char* tmppath,
2531 : : int& fd,
2532 : : off_t size,
2533 : : time_t mtime,
2534 : : const string& metric,
2535 : : const struct timespec& extract_begin)
2536 : : {
2537 [ + + ]: 1002 : if (tmppath != NULL)
2538 : : {
2539 : 230 : struct timespec extract_end;
2540 : 230 : clock_gettime (CLOCK_MONOTONIC, &extract_end);
2541 : 230 : double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
2542 : 230 : + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
2543 [ + - ]: 460 : fdcache.intern(b_source0, b_source1, tmppath, size, true, extract_time);
2544 : : }
2545 : :
2546 [ + + ]: 1002 : if (!section.empty ())
2547 : : {
2548 [ + - + - ]: 8 : int scn_fd = extract_section (fd, b_mtime0,
2549 [ + - - + ]: 16 : b_source0 + ":" + b_source1,
2550 : : section, extract_begin);
2551 : 8 : close (fd);
2552 [ + + ]: 8 : if (scn_fd >= 0)
2553 : 4 : fd = scn_fd;
2554 : : else
2555 : : {
2556 [ + - ]: 4 : if (verbose)
2557 [ + - ]: 12 : obatched (clog) << "cannot find section " << section
2558 : : << " for archive " << b_source0
2559 [ + - + - : 4 : << " file " << b_source1 << endl;
+ - + - +
- ]
2560 : 4 : return 0;
2561 : : }
2562 : :
2563 : 4 : struct stat fs;
2564 [ - + ]: 4 : if (fstat (fd, &fs) < 0)
2565 : : {
2566 : 0 : close (fd);
2567 [ # # # # ]: 0 : throw libc_exception (errno,
2568 [ # # # # : 0 : string ("fstat ") + b_source0 + string (" ") + section);
# # # # #
# # # # #
# # # # #
# ]
2569 : : }
2570 : 4 : size = fs.st_size;
2571 : : }
2572 : :
2573 : 998 : struct MHD_Response* r = MHD_create_response_from_fd (size, fd);
2574 [ - + ]: 998 : if (r == 0)
2575 : : {
2576 [ # # ]: 0 : if (verbose)
2577 [ # # # # ]: 0 : obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
2578 : 0 : close(fd);
2579 : : }
2580 : : else
2581 : : {
2582 [ + - + - : 1996 : inc_metric ("http_responses_total","result",metric);
- + - - ]
2583 : 998 : add_mhd_response_header (r, "Content-Type", "application/octet-stream");
2584 [ + - ]: 998 : add_mhd_response_header (r, "X-DEBUGINFOD-SIZE", to_string(size).c_str());
2585 : 998 : add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE", b_source0.c_str());
2586 : 998 : add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source1.c_str());
2587 [ - + ]: 998 : if(!ima_sig.empty()) add_mhd_response_header(r, "X-DEBUGINFOD-IMASIGNATURE", ima_sig.c_str());
2588 : 998 : add_mhd_last_modified (r, mtime);
2589 [ - + ]: 998 : if (verbose > 1)
2590 [ + - ]: 2994 : obatched(clog) << "serving " << metric << " " << b_source0
2591 : : << " file " << b_source1
2592 : : << " section=" << section
2593 [ + - + - : 998 : << " IMA signature=" << ima_sig << endl;
+ - + - +
- + - + -
+ - + - ]
2594 : : /* libmicrohttpd will close fd. */
2595 : : }
2596 : : return r;
2597 : : }
2598 : :
2599 : : static struct MHD_Response*
2600 : 1058 : handle_buildid_r_match (bool internal_req_p,
2601 : : int64_t b_mtime,
2602 : : const string& b_source0,
2603 : : const string& b_source1,
2604 : : int64_t b_id0,
2605 : : int64_t b_id1,
2606 : : const string& section,
2607 : : int *result_fd)
2608 : : {
2609 : 1058 : struct timespec extract_begin;
2610 : 1058 : clock_gettime (CLOCK_MONOTONIC, &extract_begin);
2611 : :
2612 : 1058 : struct stat fs;
2613 : 1058 : int rc = stat (b_source0.c_str(), &fs);
2614 [ + + ]: 1058 : if (rc != 0)
2615 [ + - + - : 116 : throw libc_exception (errno, string("stat ") + b_source0);
+ - - + ]
2616 : :
2617 [ - + ]: 1000 : if ((int64_t) fs.st_mtime != b_mtime)
2618 : : {
2619 [ # # ]: 0 : if (verbose)
2620 [ # # # # ]: 0 : obatched(clog) << "mtime mismatch for " << b_source0 << endl;
2621 : 0 : return 0;
2622 : : }
2623 : :
2624 : : // Extract the IMA per-file signature (if it exists)
2625 : 1000 : string ima_sig = "";
2626 : : #ifdef ENABLE_IMA_VERIFICATION
2627 : : do
2628 : : {
2629 : : FD_t rpm_fd;
2630 : : if(!(rpm_fd = Fopen(b_source0.c_str(), "r.ufdio"))) // read, uncompressed, rpm/rpmio.h
2631 : : {
2632 : : if (verbose) obatched(clog) << "There was an error while opening " << b_source0 << endl;
2633 : : break; // Exit IMA extraction
2634 : : }
2635 : :
2636 : : Header rpm_hdr;
2637 : : if(RPMRC_FAIL == rpmReadPackageFile(NULL, rpm_fd, b_source0.c_str(), &rpm_hdr))
2638 : : {
2639 : : if (verbose) obatched(clog) << "There was an error while reading the header of " << b_source0 << endl;
2640 : : Fclose(rpm_fd);
2641 : : break; // Exit IMA extraction
2642 : : }
2643 : :
2644 : : // Fill sig_tag_data with an alloc'd copy of the array of IMA signatures (if they exist)
2645 : : struct rpmtd_s sig_tag_data;
2646 : : rpmtdReset(&sig_tag_data);
2647 : : do{ /* A do-while so we can break out of the koji sigcache checking on failure */
2648 : : if(requires_koji_sigcache_mapping)
2649 : : {
2650 : : /* NB: Koji builds result in a directory structure like the following
2651 : : - PACKAGE/VERSION/RELEASE
2652 : : - ARCH1
2653 : : - foo.rpm // The rpm known by debuginfod
2654 : : - ...
2655 : : - ARCHN
2656 : : - data
2657 : : - signed // Periodically purged (and not scanned by debuginfod)
2658 : : - sigcache
2659 : : - ARCH1
2660 : : - foo.rpm.sig // An empty rpm header
2661 : : - ...
2662 : : - ARCHN
2663 : : - PACKAGE_KEYID1
2664 : : - ARCH1
2665 : : - foo.rpm.sig // The header of the signed rpm. This is the file we need to extract the IMA signatures
2666 : : - ...
2667 : : - ARCHN
2668 : : - ...
2669 : : - PACKAGE_KEYIDn
2670 : :
2671 : : We therefore need to do a mapping:
2672 : :
2673 : : P/V/R/A/N-V-R.A.rpm ->
2674 : : P/V/R/data/sigcache/KEYID/A/N-V-R.A.rpm.sig
2675 : :
2676 : : There are 2 key insights here
2677 : :
2678 : : 1. We need to go 2 directories down from sigcache to get to the
2679 : : rpm header. So to distinguish ARCH1/foo.rpm.sig and
2680 : : PACKAGE_KEYID1/ARCH1/foo.rpm.sig we can look 2 directories down
2681 : :
2682 : : 2. It's safe to assume that the user will have all of the
2683 : : required verification certs. So we can pick from any of the
2684 : : PACKAGE_KEYID* directories. For simplicity we choose first we
2685 : : match against
2686 : :
2687 : : See: https://pagure.io/koji/issue/3670
2688 : : */
2689 : :
2690 : : // Do the mapping from b_source0 to the koji path for the signed rpm header
2691 : : string signed_rpm_path = b_source0;
2692 : : size_t insert_pos = string::npos;
2693 : : for(int i = 0; i < 2; i++) insert_pos = signed_rpm_path.rfind("/", insert_pos) - 1;
2694 : : string globbed_path = signed_rpm_path.insert(insert_pos + 1, "/data/sigcache/*").append(".sig"); // The globbed path we're seeking
2695 : : glob_t pglob;
2696 : : int grc;
2697 : : if(0 != (grc = glob(globbed_path.c_str(), GLOB_NOSORT, NULL, &pglob)))
2698 : : {
2699 : : // Break out, but only report real errors
2700 : : if (verbose && grc != GLOB_NOMATCH) obatched(clog) << "There was an error (" << strerror(errno) << ") globbing " << globbed_path << endl;
2701 : : break; // Exit koji sigcache check
2702 : : }
2703 : : signed_rpm_path = pglob.gl_pathv[0]; // See insight 2 above
2704 : : globfree(&pglob);
2705 : :
2706 : : if (verbose > 2) obatched(clog) << "attempting IMA signature extraction from koji header " << signed_rpm_path << endl;
2707 : :
2708 : : FD_t sig_rpm_fd;
2709 : : if(NULL == (sig_rpm_fd = Fopen(signed_rpm_path.c_str(), "r")))
2710 : : {
2711 : : if (verbose) obatched(clog) << "There was an error while opening " << signed_rpm_path << endl;
2712 : : break; // Exit koji sigcache check
2713 : : }
2714 : :
2715 : : Header sig_hdr = headerRead(sig_rpm_fd, HEADER_MAGIC_YES /* Validate magic too */ );
2716 : : if (!sig_hdr || 1 != headerGet(sig_hdr, RPMSIGTAG_FILESIGNATURES, &sig_tag_data, HEADERGET_ALLOC))
2717 : : {
2718 : : if (verbose) obatched(clog) << "Unable to extract RPMSIGTAG_FILESIGNATURES from " << signed_rpm_path << endl;
2719 : : }
2720 : : headerFree(sig_hdr); // We can free here since sig_tag_data has an alloc'd copy of the data
2721 : : Fclose(sig_rpm_fd);
2722 : : }
2723 : : }while(false);
2724 : :
2725 : : if(0 == sig_tag_data.count)
2726 : : {
2727 : : // In the general case (or a fallback from the koji sigcache mapping not finding signatures)
2728 : : // we can just (try) extract the signatures from the rpm header
2729 : : if (1 != headerGet(rpm_hdr, RPMTAG_FILESIGNATURES, &sig_tag_data, HEADERGET_ALLOC))
2730 : : {
2731 : : if (verbose) obatched(clog) << "Unable to extract RPMTAG_FILESIGNATURES from " << b_source0 << endl;
2732 : : }
2733 : : }
2734 : : // Search the array for the signature coresponding to b_source1
2735 : : int idx = -1;
2736 : : char *sig = NULL;
2737 : : rpmfi hdr_fi = rpmfiNew(NULL, rpm_hdr, RPMTAG_BASENAMES, RPMFI_FLAGS_QUERY);
2738 : : do
2739 : : {
2740 : : sig = (char*)rpmtdNextString(&sig_tag_data);
2741 : : idx = rpmfiNext(hdr_fi);
2742 : : }
2743 : : while (idx != -1 && 0 != strcmp(b_source1.c_str(), rpmfiFN(hdr_fi)));
2744 : : rpmfiFree(hdr_fi);
2745 : :
2746 : : if(sig && 0 != strlen(sig) && idx != -1)
2747 : : {
2748 : : if (verbose > 2) obatched(clog) << "Found IMA signature for " << b_source1 << ":\n" << sig << endl;
2749 : : ima_sig = sig;
2750 : : inc_metric("http_responses_total","extra","ima-sigs-extracted");
2751 : : }
2752 : : else
2753 : : {
2754 : : if (verbose > 2) obatched(clog) << "Could not find IMA signature for " << b_source1 << endl;
2755 : : }
2756 : :
2757 : : rpmtdFreeData (&sig_tag_data);
2758 : : headerFree(rpm_hdr);
2759 : : Fclose(rpm_fd);
2760 : : } while(false);
2761 : : #endif
2762 : :
2763 : : // check for a match in the fdcache first
2764 [ + - ]: 1000 : int fd = fdcache.lookup(b_source0, b_source1);
2765 [ + + ]: 1000 : while (fd >= 0) // got one!; NB: this is really an if() with a possible branch out to the end
2766 : : {
2767 : 772 : rc = fstat(fd, &fs);
2768 [ - + ]: 772 : if (rc < 0) // disappeared?
2769 : : {
2770 [ # # ]: 0 : if (verbose)
2771 [ # # # # : 0 : obatched(clog) << "cannot fstat fdcache " << b_source0 << endl;
# # ]
2772 [ # # ]: 0 : close(fd);
2773 [ # # ]: 0 : fdcache.clear(b_source0, b_source1);
2774 : : break; // branch out of if "loop", to try new libarchive fetch attempt
2775 : : }
2776 : :
2777 [ + - + - : 772 : struct MHD_Response* r = create_buildid_r_response (b_mtime, b_source0,
- + - - ]
2778 : : b_source1, section,
2779 : : ima_sig, NULL, fd,
2780 : : fs.st_size,
2781 : : fs.st_mtime,
2782 : : "archive fdcache",
2783 : : extract_begin);
2784 [ + + ]: 772 : if (r == 0)
2785 : : break; // branch out of if "loop", to try new libarchive fetch attempt
2786 [ + - ]: 770 : if (result_fd)
2787 : 770 : *result_fd = fd;
2788 : : return r;
2789 : : // NB: see, we never go around the 'loop' more than once
2790 : : }
2791 : :
2792 : : // no match ... look for a seekable entry
2793 : 230 : bool populate_seekable = ! passive_p;
2794 : 230 : unique_ptr<sqlite_ps> pp (new sqlite_ps (internal_req_p ? db : dbq,
2795 : : "rpm-seekable-query",
2796 : : "select type, size, offset, mtime from " BUILDIDS "_r_seekable "
2797 [ + - + - : 460 : "where file = ? and content = ?"));
+ - + + +
- + - + -
- - ]
2798 [ + - + - : 230 : rc = pp->reset().bind(1, b_id0).bind(2, b_id1).step();
+ - + - ]
2799 [ + + ]: 230 : if (rc != SQLITE_DONE)
2800 : : {
2801 [ - + ]: 94 : if (rc != SQLITE_ROW)
2802 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
2803 : : // if we found a match in _r_seekable but we fail to extract it, don't
2804 : : // bother populating it again
2805 : 94 : populate_seekable = false;
2806 [ + - ]: 94 : const char* seekable_type = (const char*) sqlite3_column_text (*pp, 0);
2807 [ + - - + ]: 94 : if (seekable_type != NULL && strcmp (seekable_type, "xz") == 0)
2808 : : {
2809 [ + - ]: 94 : int64_t seekable_size = sqlite3_column_int64 (*pp, 1);
2810 [ + - ]: 94 : int64_t seekable_offset = sqlite3_column_int64 (*pp, 2);
2811 [ + - ]: 94 : int64_t seekable_mtime = sqlite3_column_int64 (*pp, 3);
2812 : :
2813 : 94 : char* tmppath = NULL;
2814 [ - + ]: 94 : if (asprintf (&tmppath, "%s/debuginfod-fdcache.XXXXXX", tmpdir.c_str()) < 0)
2815 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
2816 : 94 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
2817 : :
2818 [ + - ]: 94 : fd = extract_from_seekable_archive (b_source0, tmppath,
2819 : : seekable_offset, seekable_size);
2820 [ + - ]: 94 : if (fd >= 0)
2821 : : {
2822 : : // Set the mtime so the fdcache file mtimes propagate to future webapi
2823 : : // clients.
2824 : 94 : struct timespec tvs[2];
2825 : 94 : tvs[0].tv_sec = 0;
2826 : 94 : tvs[0].tv_nsec = UTIME_OMIT;
2827 : 94 : tvs[1].tv_sec = seekable_mtime;
2828 : 94 : tvs[1].tv_nsec = 0;
2829 : 94 : (void) futimens (fd, tvs); /* best effort */
2830 [ + - + - : 94 : struct MHD_Response* r = create_buildid_r_response (b_mtime,
+ - ]
2831 : : b_source0,
2832 : : b_source1,
2833 : : section,
2834 : : ima_sig,
2835 : : tmppath, fd,
2836 : : seekable_size,
2837 : : seekable_mtime,
2838 : : "seekable xz archive",
2839 : : extract_begin);
2840 [ + - ]: 94 : if (r != 0 && result_fd)
2841 : 94 : *result_fd = fd;
2842 : 94 : return r;
2843 : : }
2844 : 94 : }
2845 : : }
2846 : 136 : pp.reset();
2847 : :
2848 : : // still no match ... grumble, must process the archive
2849 [ + - ]: 136 : string archive_decoder = "/dev/null";
2850 [ + - - - ]: 136 : string archive_extension = "";
2851 [ + + ]: 310 : for (auto&& arch : scan_archives)
2852 [ + + ]: 174 : if (string_endswith(b_source0, arch.first))
2853 : : {
2854 [ + - ]: 136 : archive_extension = arch.first;
2855 [ + - ]: 310 : archive_decoder = arch.second;
2856 : : }
2857 : 136 : FILE* fp;
2858 : :
2859 : 136 : defer_dtor<FILE*,int>::dtor_fn dfn;
2860 [ + + ]: 136 : if (archive_decoder != "cat")
2861 : : {
2862 [ + - + - : 48 : string popen_cmd = archive_decoder + " " + shell_escape(b_source0);
+ - - + -
- - - ]
2863 [ + - ]: 24 : fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
2864 : 24 : dfn = pclose;
2865 [ - + ]: 24 : if (fp == NULL)
2866 [ # # # # : 0 : throw libc_exception (errno, string("popen ") + popen_cmd);
# # # # ]
2867 : 24 : }
2868 : : else
2869 : : {
2870 [ + - ]: 112 : fp = fopen (b_source0.c_str(), "r");
2871 : 112 : dfn = fclose;
2872 [ - + ]: 112 : if (fp == NULL)
2873 [ # # # # : 0 : throw libc_exception (errno, string("fopen ") + b_source0);
# # # # ]
2874 : : }
2875 : 136 : defer_dtor<FILE*,int> fp_closer (fp, dfn);
2876 : :
2877 : 136 : struct archive *a;
2878 [ + - ]: 136 : a = archive_read_new();
2879 [ - + ]: 136 : if (a == NULL)
2880 [ # # # # ]: 0 : throw archive_exception("cannot create archive reader");
2881 : 136 : defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
2882 : :
2883 [ + - ]: 136 : rc = archive_read_support_format_all(a);
2884 [ - + ]: 136 : if (rc != ARCHIVE_OK)
2885 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all format");
2886 [ + - ]: 136 : rc = archive_read_support_filter_all(a);
2887 [ - + ]: 136 : if (rc != ARCHIVE_OK)
2888 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all filters");
2889 : :
2890 [ + - ]: 136 : rc = archive_read_open_FILE (a, fp);
2891 [ - + ]: 136 : if (rc != ARCHIVE_OK)
2892 : : {
2893 [ # # # # : 0 : obatched(clog) << "cannot open archive from pipe " << b_source0 << endl;
# # ]
2894 [ # # # # ]: 0 : throw archive_exception(a, "cannot open archive from pipe");
2895 : : }
2896 : :
2897 : : // If the archive was scanned in a version without _r_seekable, then we may
2898 : : // need to populate _r_seekable now. This can be removed the next time
2899 : : // BUILDIDS is updated.
2900 [ + + ]: 136 : if (populate_seekable)
2901 : : {
2902 [ + - ]: 134 : populate_seekable = is_seekable_archive (b_source0, a);
2903 [ + - ]: 134 : if (populate_seekable)
2904 : : {
2905 : : // NB: the names are already interned
2906 [ # # ]: 0 : pp.reset(new sqlite_ps (db, "rpm-seekable-insert2",
2907 : : "insert or ignore into " BUILDIDS "_r_seekable (file, content, type, size, offset, mtime) "
2908 : : "values (?, "
2909 : : "(select id from " BUILDIDS "_files "
2910 : : "where dirname = (select id from " BUILDIDS "_fileparts where name = ?) "
2911 : : "and basename = (select id from " BUILDIDS "_fileparts where name = ?) "
2912 [ # # # # : 0 : "), 'xz', ?, ?, ?)"));
# # # # #
# # # ]
2913 : : }
2914 : : }
2915 : :
2916 : : // archive traversal is in five stages:
2917 : : // 1) before we find a matching entry, insert it into _r_seekable if needed or
2918 : : // skip it otherwise
2919 : : // 2) extract the matching entry (set r = result). Also insert it into
2920 : : // _r_seekable if needed
2921 : : // 3) extract some number of prefetched entries (just into fdcache). Also
2922 : : // insert them into _r_seekable if needed
2923 : : // 4) if needed, insert all of the remaining entries into _r_seekable
2924 : : // 5) abort any further processing
2925 : 136 : struct MHD_Response* r = 0; // will set in stage 2
2926 [ + + ]: 136 : unsigned prefetch_count =
2927 : : internal_req_p ? 0 : fdcache_prefetch; // will decrement in stage 3
2928 : :
2929 [ + + - + ]: 1446 : while(r == 0 || prefetch_count > 0 || populate_seekable) // stage 1-4
2930 : : {
2931 [ + - ]: 1426 : if (interrupted)
2932 : : break;
2933 : :
2934 : 1426 : struct archive_entry *e;
2935 [ + - ]: 1426 : rc = archive_read_next_header (a, &e);
2936 [ + + ]: 1426 : if (rc != ARCHIVE_OK)
2937 : : break;
2938 : :
2939 [ + - + + ]: 1312 : if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
2940 : 1038 : continue;
2941 : :
2942 [ + - ]: 274 : string fn = canonicalized_archive_entry_pathname (e);
2943 : :
2944 [ - + ]: 274 : if (populate_seekable)
2945 : : {
2946 : 0 : string dn, bn;
2947 : 0 : size_t slash = fn.rfind('/');
2948 [ # # ]: 0 : if (slash == std::string::npos) {
2949 [ # # ]: 0 : dn = "";
2950 [ # # ]: 0 : bn = fn;
2951 : : } else {
2952 [ # # # # ]: 0 : dn = fn.substr(0, slash);
2953 [ # # # # ]: 0 : bn = fn.substr(slash + 1);
2954 : : }
2955 : :
2956 [ # # ]: 0 : int64_t seekable_size = archive_entry_size (e);
2957 [ # # ]: 0 : int64_t seekable_offset = archive_filter_bytes (a, 0);
2958 [ # # ]: 0 : time_t seekable_mtime = archive_entry_mtime (e);
2959 : :
2960 [ # # ]: 0 : pp->reset();
2961 [ # # ]: 0 : pp->bind(1, b_id0);
2962 [ # # ]: 0 : pp->bind(2, dn);
2963 [ # # ]: 0 : pp->bind(3, bn);
2964 [ # # ]: 0 : pp->bind(4, seekable_size);
2965 [ # # ]: 0 : pp->bind(5, seekable_offset);
2966 [ # # ]: 0 : pp->bind(6, seekable_mtime);
2967 [ # # ]: 0 : rc = pp->step();
2968 [ # # ]: 0 : if (rc != SQLITE_DONE)
2969 [ # # # # ]: 0 : obatched(clog) << "recording seekable file=" << fn
2970 [ # # # # : 0 : << " sqlite3 error: " << (sqlite3_errstr(rc) ?: "?") << endl;
# # # # #
# ]
2971 [ # # ]: 0 : else if (verbose > 2)
2972 [ # # # # : 0 : obatched(clog) << "recorded seekable file=" << fn
# # ]
2973 [ # # # # ]: 0 : << " size=" << seekable_size
2974 [ # # # # ]: 0 : << " offset=" << seekable_offset
2975 [ # # # # : 0 : << " mtime=" << seekable_mtime << endl;
# # ]
2976 [ # # ]: 0 : if (r != 0 && prefetch_count == 0) // stage 4
2977 [ # # ]: 0 : continue;
2978 [ # # # # ]: 0 : }
2979 : :
2980 [ + + + + ]: 274 : if ((r == 0) && (fn != b_source1)) // stage 1
2981 : 68 : continue;
2982 : :
2983 [ + - + + ]: 206 : if (fdcache.probe (b_source0, fn) && // skip if already interned
2984 [ + + ]: 26 : fn != b_source1) // but only if we'd just be prefetching, PR29474
2985 : 24 : continue;
2986 : :
2987 : : // extract this file to a temporary file
2988 : 182 : char* tmppath = NULL;
2989 : 182 : rc = asprintf (&tmppath, "%s/debuginfod-fdcache.XXXXXX", tmpdir.c_str());
2990 [ - + ]: 182 : if (rc < 0)
2991 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
2992 : 182 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
2993 [ + - ]: 182 : fd = mkstemp (tmppath);
2994 [ - + ]: 182 : if (fd < 0)
2995 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
2996 : : // NB: don't unlink (tmppath), as fdcache will take charge of it.
2997 : :
2998 : : // NB: this can take many uninterruptible seconds for a huge file
2999 [ + - ]: 182 : rc = archive_read_data_into_fd (a, fd);
3000 [ - + ]: 182 : if (rc != ARCHIVE_OK) // e.g. ENOSPC!
3001 : : {
3002 [ # # ]: 0 : close (fd);
3003 : 0 : unlink (tmppath);
3004 [ # # # # ]: 0 : throw archive_exception(a, "cannot extract file");
3005 : : }
3006 : :
3007 : : // Set the mtime so the fdcache file mtimes, even prefetched ones,
3008 : : // propagate to future webapi clients.
3009 : 182 : struct timespec tvs[2];
3010 : 182 : tvs[0].tv_sec = 0;
3011 : 182 : tvs[0].tv_nsec = UTIME_OMIT;
3012 [ + - ]: 182 : tvs[1].tv_sec = archive_entry_mtime(e);
3013 [ + - ]: 182 : tvs[1].tv_nsec = archive_entry_mtime_nsec(e);
3014 : 182 : (void) futimens (fd, tvs); /* best effort */
3015 : :
3016 [ + + ]: 182 : if (r != 0) // stage 3
3017 : : {
3018 : 46 : struct timespec extract_end;
3019 : 46 : clock_gettime (CLOCK_MONOTONIC, &extract_end);
3020 : 46 : double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
3021 : 46 : + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
3022 : : // NB: now we know we have a complete reusable file; make fdcache
3023 : : // responsible for unlinking it later.
3024 [ + - + - : 46 : fdcache.intern(b_source0, fn,
+ - ]
3025 : : tmppath, archive_entry_size(e),
3026 : : false, extract_time); // prefetched ones go to the prefetch cache
3027 : 46 : prefetch_count --;
3028 [ + - ]: 46 : close (fd); // we're not saving this fd to make a mhd-response from!
3029 : 46 : continue;
3030 : 46 : }
3031 : :
3032 [ + - + - : 136 : r = create_buildid_r_response (b_mtime, b_source0, b_source1, section,
+ - + + ]
3033 : : ima_sig, tmppath, fd,
3034 : : archive_entry_size(e),
3035 : : archive_entry_mtime(e),
3036 [ + - ]: 136 : archive_extension + " archive",
3037 : : extract_begin);
3038 [ + + ]: 136 : if (r == 0)
3039 : : break; // assume no chance of better luck around another iteration; no other copies of same file
3040 [ + - ]: 134 : if (result_fd)
3041 : 134 : *result_fd = fd;
3042 [ + - + - : 1700 : }
+ + ]
3043 : :
3044 : : // XXX: rpm/file not found: delete this R entry?
3045 : 136 : return r;
3046 [ - + + + ]: 1366 : }
3047 : :
3048 : : void
3049 : 650 : add_client_federation_headers(debuginfod_client *client, MHD_Connection* conn){
3050 : : // Transcribe incoming User-Agent:
3051 [ - + ]: 650 : string ua = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
3052 [ + - + - : 654 : string ua_complete = string("User-Agent: ") + ua;
+ - ]
3053 [ + - ]: 650 : debuginfod_add_http_header (client, ua_complete.c_str());
3054 : :
3055 : : // Compute larger XFF:, for avoiding info loss during
3056 : : // federation, and for future cyclicity detection.
3057 [ + - + + : 1278 : string xff = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
+ - + - ]
3058 [ + + ]: 650 : if (xff != "")
3059 [ + - - + ]: 52 : xff += string(", "); // comma separated list
3060 : :
3061 : 650 : unsigned int xff_count = 0;
3062 [ + + ]: 978 : for (auto&& i : xff){
3063 [ + + ]: 328 : if (i == ',') xff_count++;
3064 : : }
3065 : :
3066 : : // if X-Forwarded-For: exceeds N hops,
3067 : : // do not delegate a local lookup miss to upstream debuginfods.
3068 [ + + ]: 650 : if (xff_count >= forwarded_ttl_limit)
3069 [ + - + - ]: 8 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found, --forwared-ttl-limit reached \
3070 : 8 : and will not query the upstream servers");
3071 : :
3072 : : // Compute the client's numeric IP address only - so can't merge with conninfo()
3073 [ + - ]: 646 : const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
3074 : : MHD_CONNECTION_INFO_CLIENT_ADDRESS);
3075 [ + - ]: 646 : struct sockaddr *so = u ? u->client_addr : 0;
3076 : 646 : char hostname[256] = ""; // RFC1035
3077 [ + - - + ]: 646 : if (so && so->sa_family == AF_INET) {
3078 [ # # ]: 0 : (void) getnameinfo (so, sizeof (struct sockaddr_in), hostname, sizeof (hostname), NULL, 0,
3079 : : NI_NUMERICHOST);
3080 [ + - ]: 646 : } else if (so && so->sa_family == AF_INET6) {
3081 : 646 : struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
3082 [ + - + - : 646 : if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
- + ]
3083 : 646 : struct sockaddr_in addr4;
3084 [ + - ]: 646 : memset (&addr4, 0, sizeof(addr4));
3085 : 646 : addr4.sin_family = AF_INET;
3086 : 646 : addr4.sin_port = addr6->sin6_port;
3087 [ + - ]: 646 : memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
3088 [ + - ]: 646 : (void) getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
3089 : : hostname, sizeof (hostname), NULL, 0,
3090 : : NI_NUMERICHOST);
3091 : : } else {
3092 [ # # ]: 0 : (void) getnameinfo (so, sizeof (struct sockaddr_in6), hostname, sizeof (hostname), NULL, 0,
3093 : : NI_NUMERICHOST);
3094 : : }
3095 : : }
3096 : :
3097 [ + - + - : 1296 : string xff_complete = string("X-Forwarded-For: ")+xff+string(hostname);
+ - + - -
+ - + - -
- + ]
3098 [ + - ]: 646 : debuginfod_add_http_header (client, xff_complete.c_str());
3099 [ + + + - : 1368 : }
+ + ]
3100 : :
3101 : : static struct MHD_Response*
3102 : 2186 : handle_buildid_match (bool internal_req_p,
3103 : : int64_t b_mtime,
3104 : : const string& b_stype,
3105 : : const string& b_source0,
3106 : : const string& b_source1,
3107 : : int64_t b_id0,
3108 : : int64_t b_id1,
3109 : : const string& section,
3110 : : int *result_fd)
3111 : : {
3112 : 2186 : try
3113 : : {
3114 [ + + ]: 2186 : if (b_stype == "F")
3115 [ + - ]: 1128 : return handle_buildid_f_match(internal_req_p, b_mtime, b_source0,
3116 : : section, result_fd);
3117 [ + - ]: 1058 : else if (b_stype == "R")
3118 [ + + ]: 1058 : return handle_buildid_r_match(internal_req_p, b_mtime, b_source0,
3119 : : b_source1, b_id0, b_id1, section,
3120 : : result_fd);
3121 : : }
3122 [ - + ]: 58 : catch (const reportable_exception &e)
3123 : : {
3124 [ + - ]: 58 : e.report(clog);
3125 : : // Report but swallow libc etc. errors here; let the caller
3126 : : // iterate to other matches of the content.
3127 : 58 : }
3128 : :
3129 : : return 0;
3130 : : }
3131 : :
3132 : :
3133 : : static int
3134 : 4 : debuginfod_find_progress (debuginfod_client *, long a, long b)
3135 : : {
3136 [ - + ]: 4 : if (verbose > 4)
3137 [ # # # # : 0 : obatched(clog) << "federated debuginfod progress=" << a << "/" << b << endl;
# # # # ]
3138 : :
3139 : 4 : return interrupted;
3140 : : }
3141 : :
3142 : :
3143 : : // a little lru pool of debuginfod_client*s for reuse between query threads
3144 : :
3145 : : mutex dc_pool_lock;
3146 : : deque<debuginfod_client*> dc_pool;
3147 : :
3148 : 670 : debuginfod_client* debuginfod_pool_begin()
3149 : : {
3150 : 670 : unique_lock<mutex> lock(dc_pool_lock);
3151 [ + + ]: 670 : if (dc_pool.size() > 0)
3152 : : {
3153 [ + - + - : 1276 : inc_metric("dc_pool_op_count","op","begin-reuse");
+ - + - -
+ - + - -
- - ]
3154 : 638 : debuginfod_client *c = dc_pool.front();
3155 : 638 : dc_pool.pop_front();
3156 : 638 : return c;
3157 : : }
3158 [ + - + - : 64 : inc_metric("dc_pool_op_count","op","begin-new");
+ - + - -
+ - + - -
- - ]
3159 [ + - ]: 32 : return debuginfod_begin();
3160 : 670 : }
3161 : :
3162 : :
3163 : 158 : void debuginfod_pool_groom()
3164 : : {
3165 : 158 : unique_lock<mutex> lock(dc_pool_lock);
3166 [ + + ]: 190 : while (dc_pool.size() > 0)
3167 : : {
3168 [ + - + - : 64 : inc_metric("dc_pool_op_count","op","end");
+ - + - -
+ - + - -
- - ]
3169 [ + - ]: 32 : debuginfod_end(dc_pool.front());
3170 : 32 : dc_pool.pop_front();
3171 : : }
3172 : 158 : }
3173 : :
3174 : :
3175 : 670 : void debuginfod_pool_end(debuginfod_client* c)
3176 : : {
3177 : 670 : unique_lock<mutex> lock(dc_pool_lock);
3178 [ + - + - : 1340 : inc_metric("dc_pool_op_count","op","end-save");
+ - + - -
+ - + - -
- - ]
3179 [ + - ]: 670 : dc_pool.push_front(c); // accelerate reuse, vs. push_back
3180 : 670 : }
3181 : :
3182 : :
3183 : : static struct MHD_Response*
3184 : 2774 : handle_buildid (MHD_Connection* conn,
3185 : : const string& buildid /* unsafe */,
3186 : : string& artifacttype /* unsafe, cleanse on exception/return */,
3187 : : const string& suffix /* unsafe */,
3188 : : int *result_fd)
3189 : : {
3190 : : // validate artifacttype
3191 : 2774 : string atype_code;
3192 [ + + + - ]: 2774 : if (artifacttype == "debuginfo") atype_code = "D";
3193 [ + + + - ]: 1806 : else if (artifacttype == "executable") atype_code = "E";
3194 [ + + + - ]: 1114 : else if (artifacttype == "source") atype_code = "S";
3195 [ + + + - ]: 12 : else if (artifacttype == "section") atype_code = "I";
3196 : : else {
3197 [ + - ]: 4 : artifacttype = "invalid"; // PR28242 ensure http_resposes metrics don't propagate unclean user data
3198 [ + - + - ]: 12 : throw reportable_exception("invalid artifacttype");
3199 : : }
3200 : :
3201 [ + + ]: 2770 : if (conn != 0)
3202 [ + - + - : 5786 : inc_metric("http_requests_total", "type", artifacttype);
+ - - + -
- - + ]
3203 : :
3204 : 2770 : string section;
3205 [ + + ]: 2770 : if (atype_code == "I")
3206 : : {
3207 [ - + ]: 8 : if (suffix.size () < 2)
3208 [ # # # # ]: 0 : throw reportable_exception ("invalid section suffix");
3209 : :
3210 : : // Remove leading '/'
3211 [ + - - + ]: 8 : section = suffix.substr(1);
3212 : : }
3213 : :
3214 [ + + - + ]: 3872 : if (atype_code == "S" && suffix == "")
3215 [ # # # # ]: 0 : throw reportable_exception("invalid source suffix");
3216 : :
3217 : : // validate buildid
3218 [ + + ]: 2770 : if ((buildid.size() < 2) || // not empty
3219 [ + + + - : 5534 : (buildid.size() % 2) || // even number
+ - ]
3220 : 2764 : (buildid.find_first_not_of("0123456789abcdef") != string::npos)) // pure tasty lowercase hex
3221 [ + - - + ]: 12 : throw reportable_exception("invalid buildid");
3222 : :
3223 [ + - ]: 2764 : if (verbose > 1)
3224 [ + - + - ]: 8292 : obatched(clog) << "searching for buildid=" << buildid << " artifacttype=" << artifacttype
3225 [ + - + - : 2764 : << " suffix=" << suffix << endl;
+ - + - +
- ]
3226 : :
3227 : : // If invoked from the scanner threads, use the scanners' read-write
3228 : : // connection. Otherwise use the web query threads' read-only connection.
3229 [ + + ]: 2764 : sqlite3 *thisdb = (conn == 0) ? db : dbq;
3230 : :
3231 : 2764 : sqlite_ps *pp = 0;
3232 : :
3233 [ + + ]: 2764 : if (atype_code == "D")
3234 : : {
3235 [ - + ]: 968 : pp = new sqlite_ps (thisdb, "mhd-query-d",
3236 : : "select mtime, sourcetype, source0, source1, id0, id1 from " BUILDIDS "_query_d2 where buildid = ? "
3237 [ + - + - : 1936 : "order by mtime desc");
+ - + - +
- - - ]
3238 [ + - ]: 968 : pp->reset();
3239 [ + - ]: 968 : pp->bind(1, buildid);
3240 : : }
3241 [ + + ]: 1796 : else if (atype_code == "E")
3242 : : {
3243 [ - + ]: 686 : pp = new sqlite_ps (thisdb, "mhd-query-e",
3244 : : "select mtime, sourcetype, source0, source1, id0, id1 from " BUILDIDS "_query_e2 where buildid = ? "
3245 [ + - + - : 1372 : "order by mtime desc");
+ - + - +
- - - ]
3246 [ + - ]: 686 : pp->reset();
3247 [ + - ]: 686 : pp->bind(1, buildid);
3248 : : }
3249 [ + + ]: 1110 : else if (atype_code == "S")
3250 : : {
3251 : : // PR25548
3252 : : // Incoming source queries may come in with either dwarf-level OR canonicalized paths.
3253 : : // We let the query pass with either one.
3254 : :
3255 [ - + ]: 1102 : pp = new sqlite_ps (thisdb, "mhd-query-s",
3256 : : "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_s where buildid = ? and artifactsrc in (?,?) "
3257 [ + - + - : 2204 : "order by sharedprefix(source0,source0ref) desc, mtime desc");
+ - + - +
- - - ]
3258 [ + - ]: 1102 : pp->reset();
3259 [ + - ]: 1102 : pp->bind(1, buildid);
3260 : : // NB: we don't store the non-canonicalized path names any more, but old databases
3261 : : // might have them (and no canon ones), so we keep searching for both.
3262 [ + - ]: 1102 : pp->bind(2, suffix);
3263 [ + - + - : 2846 : pp->bind(3, canon_pathname(suffix));
- + ]
3264 : : }
3265 [ + - ]: 8 : else if (atype_code == "I")
3266 : : {
3267 [ - + ]: 8 : pp = new sqlite_ps (thisdb, "mhd-query-i",
3268 : : "select mtime, sourcetype, source0, source1, 1 as debug_p from " BUILDIDS "_query_d2 where buildid = ? "
3269 : : "union all "
3270 : : "select mtime, sourcetype, source0, source1, 0 as debug_p from " BUILDIDS "_query_e2 where buildid = ? "
3271 [ + - + - : 16 : "order by debug_p desc, mtime desc");
+ - + - +
- - - ]
3272 [ + - ]: 8 : pp->reset();
3273 [ + - ]: 8 : pp->bind(1, buildid);
3274 [ + - ]: 8 : pp->bind(2, buildid);
3275 : : }
3276 : 2764 : unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
3277 : :
3278 : 2764 : bool do_upstream_section_query = true;
3279 : :
3280 : : // consume all the rows
3281 : 2826 : while (1)
3282 : : {
3283 [ + - ]: 2826 : int rc = pp->step();
3284 [ + + ]: 2826 : if (rc == SQLITE_DONE) break;
3285 [ - + ]: 2186 : if (rc != SQLITE_ROW)
3286 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
3287 : :
3288 [ + - ]: 2186 : int64_t b_mtime = sqlite3_column_int64 (*pp, 0);
3289 [ + - - + : 2186 : string b_stype = string((const char*) sqlite3_column_text (*pp, 1) ?: ""); /* by DDL may not be NULL */
+ - ]
3290 [ + - - + : 2186 : string b_source0 = string((const char*) sqlite3_column_text (*pp, 2) ?: ""); /* may be NULL */
+ - - - ]
3291 [ + - + + : 3314 : string b_source1 = string((const char*) sqlite3_column_text (*pp, 3) ?: ""); /* may be NULL */
+ - - - ]
3292 : 2186 : int64_t b_id0 = 0, b_id1 = 0;
3293 [ + + + + ]: 3454 : if (atype_code == "D" || atype_code == "E")
3294 : : {
3295 [ + - ]: 1070 : b_id0 = sqlite3_column_int64 (*pp, 4);
3296 [ + - ]: 1070 : b_id1 = sqlite3_column_int64 (*pp, 5);
3297 : : }
3298 : :
3299 [ + - ]: 2186 : if (verbose > 1)
3300 [ + - + - : 6558 : obatched(clog) << "found mtime=" << b_mtime << " stype=" << b_stype
- - ]
3301 [ + - + - : 2186 : << " source0=" << b_source0 << " source1=" << b_source1 << endl;
+ - + - +
- + - +
- ]
3302 : :
3303 : : // Try accessing the located match.
3304 : : // XXX: in case of multiple matches, attempt them in parallel?
3305 [ + - ]: 2186 : auto r = handle_buildid_match (conn ? false : true,
3306 : : b_mtime, b_stype, b_source0, b_source1,
3307 : : b_id0, b_id1, section, result_fd);
3308 [ + + ]: 2186 : if (r)
3309 [ + + ]: 2124 : return r;
3310 : :
3311 : : // If a debuginfo file matching BUILDID was found but didn't contain
3312 : : // the desired section, then the section should not exist. Don't
3313 : : // bother querying upstream servers.
3314 [ + + + - : 62 : if (!section.empty () && (sqlite3_column_int (*pp, 4) == 1))
- + ]
3315 : : {
3316 : 4 : struct stat st;
3317 : :
3318 : : // For "F" sourcetype, check if the debuginfo exists. For "R"
3319 : : // sourcetype, check if the debuginfo was interned into the fdcache.
3320 [ - + ]: 6 : if ((b_stype == "F" && (stat (b_source0.c_str (), &st) == 0))
3321 [ + + + - : 6 : || (b_stype == "R" && fdcache.probe (b_source0, b_source1)))
+ - - + ]
3322 : : do_upstream_section_query = false;
3323 : : }
3324 [ + - - + : 4372 : }
+ - - + ]
3325 [ + - ]: 640 : pp->reset();
3326 : :
3327 [ - + ]: 640 : if (!do_upstream_section_query)
3328 [ # # # # ]: 0 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
3329 : :
3330 : : // We couldn't find it in the database. Last ditch effort
3331 : : // is to defer to other debuginfo servers.
3332 : :
3333 : 640 : int fd = -1;
3334 [ + - ]: 640 : debuginfod_client *client = debuginfod_pool_begin ();
3335 [ - + ]: 640 : if (client == NULL)
3336 [ # # # # ]: 0 : throw libc_exception(errno, "debuginfod client pool alloc");
3337 : 640 : defer_dtor<debuginfod_client*,void> client_closer (client, debuginfod_pool_end);
3338 : :
3339 [ + - ]: 640 : debuginfod_set_progressfn (client, & debuginfod_find_progress);
3340 : :
3341 [ + + ]: 640 : if (conn)
3342 [ + + ]: 620 : add_client_federation_headers(client, conn);
3343 : :
3344 [ + + ]: 636 : if (artifacttype == "debuginfo")
3345 [ + - ]: 88 : fd = debuginfod_find_debuginfo (client,
3346 [ + - ]: 88 : (const unsigned char*) buildid.c_str(),
3347 : : 0, NULL);
3348 [ + + ]: 548 : else if (artifacttype == "executable")
3349 [ + - ]: 546 : fd = debuginfod_find_executable (client,
3350 [ + - ]: 546 : (const unsigned char*) buildid.c_str(),
3351 : : 0, NULL);
3352 [ + - ]: 2 : else if (artifacttype == "source")
3353 [ + - ]: 2 : fd = debuginfod_find_source (client,
3354 [ + - ]: 2 : (const unsigned char*) buildid.c_str(),
3355 : : 0, suffix.c_str(), NULL);
3356 [ # # ]: 0 : else if (artifacttype == "section")
3357 [ # # ]: 0 : fd = debuginfod_find_section (client,
3358 [ # # ]: 0 : (const unsigned char*) buildid.c_str(),
3359 : : 0, section.c_str(), NULL);
3360 : :
3361 [ + + ]: 636 : if (fd >= 0)
3362 : : {
3363 [ + - ]: 4 : if (conn != 0)
3364 [ + - + - : 644 : inc_metric ("http_responses_total","result","upstream");
+ - + - -
+ - + - -
- - ]
3365 : 4 : struct stat s;
3366 : 4 : int rc = fstat (fd, &s);
3367 [ + - ]: 4 : if (rc == 0)
3368 : : {
3369 [ + - ]: 4 : auto r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
3370 [ + - ]: 4 : if (r)
3371 : : {
3372 [ + - ]: 4 : add_mhd_response_header (r, "Content-Type",
3373 : : "application/octet-stream");
3374 : : // Copy the incoming headers
3375 [ + - ]: 4 : const char * hdrs = debuginfod_get_headers(client);
3376 [ + - ]: 4 : string header_dup;
3377 [ + - ]: 4 : if (hdrs)
3378 [ + - - + ]: 4 : header_dup = string(hdrs);
3379 : : // Parse the "header: value\n" lines into (h,v) tuples and pass on
3380 : 20 : while(1)
3381 : : {
3382 : 12 : size_t newline = header_dup.find('\n');
3383 [ + + ]: 12 : if (newline == string::npos) break;
3384 : 8 : size_t colon = header_dup.find(':');
3385 [ + - ]: 8 : if (colon == string::npos) break;
3386 [ + - ]: 8 : string header = header_dup.substr(0,colon);
3387 [ + - ]: 8 : string value = header_dup.substr(colon+1,newline-colon-1);
3388 : : // strip leading spaces from value
3389 : 8 : size_t nonspace = value.find_first_not_of(" ");
3390 [ + - ]: 8 : if (nonspace != string::npos)
3391 [ + - + + ]: 12 : value = value.substr(nonspace);
3392 [ + - ]: 8 : add_mhd_response_header(r, header.c_str(), value.c_str());
3393 [ + - + + : 12 : header_dup = header_dup.substr(newline+1);
+ + - - ]
3394 [ + - ]: 16 : }
3395 : :
3396 [ + - ]: 4 : add_mhd_last_modified (r, s.st_mtime);
3397 [ + - ]: 4 : if (verbose > 1)
3398 [ + - + - : 8 : obatched(clog) << "serving file from upstream debuginfod/cache" << endl;
- - ]
3399 [ + - ]: 4 : if (result_fd)
3400 : 4 : *result_fd = fd;
3401 [ + - ]: 4 : return r; // NB: don't close fd; libmicrohttpd will
3402 : 4 : }
3403 : : }
3404 [ # # ]: 0 : close (fd);
3405 : : }
3406 : : else
3407 [ + + ]: 632 : switch(fd)
3408 : : {
3409 : : case -ENOSYS:
3410 : : break;
3411 : : case -ENOENT:
3412 : : break;
3413 : 532 : default: // some more tricky error
3414 [ + - + - ]: 1064 : throw libc_exception(-fd, "upstream debuginfod query failed");
3415 : : }
3416 : :
3417 [ + - - + ]: 200 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
3418 [ - + - + ]: 3406 : }
3419 : :
3420 : :
3421 : : ////////////////////////////////////////////////////////////////////////
3422 : :
3423 : : static map<string,double> metrics; // arbitrary data for /metrics query
3424 : : // NB: store int64_t since all our metrics are integers; prometheus accepts double
3425 : : static mutex metrics_lock;
3426 : : // NB: these objects get released during the process exit via global dtors
3427 : : // do not call them from within other global dtors
3428 : :
3429 : : // utility function for assembling prometheus-compatible
3430 : : // name="escaped-value" strings
3431 : : // https://prometheus.io/docs/instrumenting/exposition_formats/
3432 : : static string
3433 : 788645 : metric_label(const string& name, const string& value)
3434 : : {
3435 : 788645 : string x = name + "=\"";
3436 [ + + ]: 13605543 : for (auto&& c : value)
3437 [ - - - + ]: 12817390 : switch(c)
3438 : : {
3439 [ # # ]: 0 : case '\\': x += "\\\\"; break;
3440 [ # # ]: 0 : case '\"': x += "\\\""; break;
3441 [ # # ]: 0 : case '\n': x += "\\n"; break;
3442 [ + - ]: 25634545 : default: x += c; break;
3443 : : }
3444 [ + - ]: 788153 : x += "\"";
3445 : 788267 : return x;
3446 : 0 : }
3447 : :
3448 : :
3449 : : // add prometheus-format metric name + label tuple (if any) + value
3450 : :
3451 : : static void
3452 : 1608 : set_metric(const string& metric, double value)
3453 : : {
3454 : 1608 : unique_lock<mutex> lock(metrics_lock);
3455 [ + - ]: 1608 : metrics[metric] = value;
3456 : 1608 : }
3457 : : static void
3458 : 784 : inc_metric(const string& metric)
3459 : : {
3460 : 784 : unique_lock<mutex> lock(metrics_lock);
3461 [ + - ]: 784 : metrics[metric] ++;
3462 : 784 : }
3463 : : static void
3464 : 7050 : set_metric(const string& metric,
3465 : : const string& lname, const string& lvalue,
3466 : : double value)
3467 : : {
3468 [ + - + - : 14101 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + - + +
+ - - ]
3469 [ + - ]: 7051 : unique_lock<mutex> lock(metrics_lock);
3470 [ + - ]: 7052 : metrics[key] = value;
3471 [ + - ]: 14104 : }
3472 : :
3473 : : static void
3474 : 376878 : inc_metric(const string& metric,
3475 : : const string& lname, const string& lvalue)
3476 : : {
3477 [ + - + - : 819707 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + + + +
+ - - ]
3478 [ + - ]: 376870 : unique_lock<mutex> lock(metrics_lock);
3479 [ + - ]: 376882 : metrics[key] ++;
3480 [ + - ]: 753737 : }
3481 : : static void
3482 : 364577 : add_metric(const string& metric,
3483 : : const string& lname, const string& lvalue,
3484 : : double value)
3485 : : {
3486 [ + - + - : 795116 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + + + +
+ - - ]
3487 [ + - ]: 364577 : unique_lock<mutex> lock(metrics_lock);
3488 [ + - ]: 364622 : metrics[key] += value;
3489 [ + - ]: 729237 : }
3490 : : static void
3491 : 784 : add_metric(const string& metric,
3492 : : double value)
3493 : : {
3494 : 784 : unique_lock<mutex> lock(metrics_lock);
3495 [ + - ]: 784 : metrics[metric] += value;
3496 : 784 : }
3497 : :
3498 : :
3499 : : // and more for higher arity labels if needed
3500 : :
3501 : : static void
3502 : 10062 : inc_metric(const string& metric,
3503 : : const string& lname, const string& lvalue,
3504 : : const string& rname, const string& rvalue)
3505 : : {
3506 [ + - - + : 20124 : string key = (metric + "{"
- - ]
3507 [ + - + - : 40248 : + metric_label(lname, lvalue) + ","
- + - + +
+ - - ]
3508 [ + - - + : 30186 : + metric_label(rname, rvalue) + "}");
- + ]
3509 [ + - ]: 10062 : unique_lock<mutex> lock(metrics_lock);
3510 [ + - ]: 10062 : metrics[key] ++;
3511 [ + - ]: 20124 : }
3512 : : static void
3513 : 10062 : add_metric(const string& metric,
3514 : : const string& lname, const string& lvalue,
3515 : : const string& rname, const string& rvalue,
3516 : : double value)
3517 : : {
3518 [ + - - + : 20124 : string key = (metric + "{"
- - ]
3519 [ + - + - : 40248 : + metric_label(lname, lvalue) + ","
- + - + +
+ - - ]
3520 [ + - - + : 30186 : + metric_label(rname, rvalue) + "}");
- + ]
3521 [ + - ]: 10062 : unique_lock<mutex> lock(metrics_lock);
3522 [ + - ]: 10062 : metrics[key] += value;
3523 [ + - ]: 20124 : }
3524 : :
3525 : : static struct MHD_Response*
3526 : 744 : handle_metrics (off_t* size)
3527 : : {
3528 : 744 : stringstream o;
3529 : 744 : {
3530 [ + - ]: 744 : unique_lock<mutex> lock(metrics_lock);
3531 [ + + ]: 79895 : for (auto&& i : metrics)
3532 [ + - ]: 79151 : o << i.first
3533 : : << " "
3534 [ + - + - ]: 79151 : << std::setprecision(std::numeric_limits<double>::digits10 + 1)
3535 [ + - + - ]: 79151 : << i.second
3536 : 79151 : << endl;
3537 : 0 : }
3538 [ + - ]: 744 : const string& os = o.str();
3539 [ + - ]: 744 : MHD_Response* r = MHD_create_response_from_buffer (os.size(),
3540 [ + - ]: 744 : (void*) os.c_str(),
3541 : : MHD_RESPMEM_MUST_COPY);
3542 [ + - ]: 744 : if (r != NULL)
3543 : : {
3544 [ + - ]: 744 : *size = os.size();
3545 [ + - ]: 744 : add_mhd_response_header (r, "Content-Type", "text/plain");
3546 : : }
3547 [ + - ]: 1488 : return r;
3548 : 744 : }
3549 : :
3550 : :
3551 : : static struct MHD_Response*
3552 : 30 : handle_metadata (MHD_Connection* conn,
3553 : : string key, string value, off_t* size)
3554 : : {
3555 : 30 : MHD_Response* r;
3556 : : // Because this query can take on the order of many seconds, we need
3557 : : // to prevent DoS against the other normal quick queries, so we use
3558 : : // a dedicated database connection.
3559 : 30 : sqlite3 *thisdb = 0;
3560 : 30 : int rc = sqlite3_open_v2 (db_path.c_str(), &thisdb, (SQLITE_OPEN_READONLY
3561 : : |SQLITE_OPEN_URI
3562 : : |SQLITE_OPEN_PRIVATECACHE
3563 : : |SQLITE_OPEN_NOMUTEX), /* private to us */
3564 : : NULL);
3565 [ - + ]: 30 : if (rc)
3566 [ # # # # ]: 0 : throw sqlite_exception(rc, "cannot open database for metadata query");
3567 : 30 : defer_dtor<sqlite3*,int> sqlite_db_closer (thisdb, sqlite3_close_v2);
3568 : :
3569 : : // Query locally for matching e, d files
3570 : 30 : string op;
3571 [ + + ]: 30 : if (key == "glob")
3572 [ + - ]: 26 : op = "glob";
3573 [ + - ]: 4 : else if (key == "file")
3574 [ + - ]: 4 : op = "=";
3575 : : else
3576 [ # # # # ]: 0 : throw reportable_exception("/metadata webapi error, unsupported key");
3577 : :
3578 : : // Since PR30378, the file names are segmented into two tables. We
3579 : : // could do a glob/= search over the _files_v view that combines
3580 : : // them, but that means that the entire _files_v thing has to be
3581 : : // materialized & scanned to do the query. Slow! Instead, we can
3582 : : // segment the incoming file/glob pattern into dirname / basename
3583 : : // parts, and apply them to the corresponding table. This is done
3584 : : // by splitting the value at the last "/". If absent, the same
3585 : : // convention as is used in register_file_name().
3586 : :
3587 : 30 : string dirname, bname; // basename is a "poisoned" identifier on some distros
3588 : 30 : size_t slash = value.rfind('/');
3589 [ - + ]: 30 : if (slash == std::string::npos) {
3590 [ # # ]: 0 : dirname = "";
3591 [ # # ]: 0 : bname = value;
3592 : : } else {
3593 [ + - - + ]: 30 : dirname = value.substr(0, slash);
3594 [ + - - + ]: 30 : bname = value.substr(slash+1);
3595 : : }
3596 : :
3597 : : // NB: further optimization is possible: replacing the 'glob' op
3598 : : // with simple equality, if the corresponding value segment lacks
3599 : : // metacharacters. sqlite may or may not be smart enough to do so,
3600 : : // so we help out.
3601 [ + - - - ]: 30 : string metacharacters = "[]*?";
3602 [ + + + + : 56 : string dop = (op == "glob" && dirname.find_first_of(metacharacters) == string::npos) ? "=" : op;
+ - + - -
- ]
3603 [ + + - + : 56 : string bop = (op == "glob" && bname.find_first_of(metacharacters) == string::npos) ? "=" : op;
- - + - -
- ]
3604 : :
3605 : 30 : string sql = string(
3606 : : // explicit query r_de and f_de once here, rather than the query_d and query_e
3607 : : // separately, because they scan the same tables, so we'd double the work
3608 : : "select d1.executable_p, d1.debuginfo_p, 0 as source_p, "
3609 : : " b1.hex, f1d.name || '/' || f1b.name as file, a1.name as archive "
3610 : : "from " BUILDIDS "_r_de d1, " BUILDIDS "_files f1, " BUILDIDS "_fileparts f1b, " BUILDIDS "_fileparts f1d, "
3611 : : BUILDIDS "_buildids b1, " BUILDIDS "_files_v a1 "
3612 : : "where f1.id = d1.content and a1.id = d1.file and d1.buildid = b1.id "
3613 [ + - + - : 90 : " and f1d.name " + dop + " ? and f1b.name " + bop + " ? and f1.dirname = f1d.id and f1.basename = f1b.id "
- + - + -
+ ]
3614 : : "union all \n"
3615 : : "select d2.executable_p, d2.debuginfo_p, 0, "
3616 : : " b2.hex, f2d.name || '/' || f2b.name, NULL "
3617 : : "from " BUILDIDS "_f_de d2, " BUILDIDS "_files f2, " BUILDIDS "_fileparts f2b, " BUILDIDS "_fileparts f2d, "
3618 : : BUILDIDS "_buildids b2 "
3619 : : "where f2.id = d2.file and d2.buildid = b2.id "
3620 [ + - + - : 90 : " and f2d.name " + dop + " ? and f2b.name " + bop + " ? "
- + - + -
+ - - ]
3621 [ - + ]: 30 : " and f2.dirname = f2d.id and f2.basename = f2b.id");
3622 : :
3623 : : // NB: we could query source file names too, thusly:
3624 : : //
3625 : : // select * from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f1, " BUILDIDS "_r_sref sr
3626 : : // where b.id = sr.buildid and f1.id = sr.artifactsrc and f1.name " + op + "?"
3627 : : // UNION ALL something with BUILDIDS "_f_s"
3628 : : //
3629 : : // But the first part of this query cannot run fast without the same index temp-created
3630 : : // during "maxigroom":
3631 : : // create index " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);
3632 : : // and unfortunately this index is HUGE. It's similar to the size of the _r_sref
3633 : : // table, which is already the largest part of a debuginfod index. Adding that index
3634 : : // would nearly double the .sqlite db size.
3635 : :
3636 [ + - + - : 30 : sqlite_ps *pp = new sqlite_ps (thisdb, "mhd-query-meta-glob", sql);
+ - + - ]
3637 [ + - ]: 30 : pp->reset();
3638 [ + - ]: 30 : pp->bind(1, dirname);
3639 [ + - ]: 30 : pp->bind(2, bname);
3640 [ + - ]: 30 : pp->bind(3, dirname);
3641 [ + - ]: 30 : pp->bind(4, bname);
3642 : 30 : unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
3643 : 30 : pp->reset_timeout(metadata_maxtime_s);
3644 : :
3645 [ + - ]: 30 : json_object *metadata = json_object_new_object();
3646 [ - + - - : 30 : if (!metadata) throw libc_exception(ENOMEM, "json allocation");
- - ]
3647 : 30 : defer_dtor<json_object*,int> metadata_d(metadata, json_object_put);
3648 [ + - ]: 30 : json_object *metadata_arr = json_object_new_array();
3649 [ - + - - : 30 : if (!metadata_arr) throw libc_exception(ENOMEM, "json allocation");
- - ]
3650 [ + - ]: 30 : json_object_object_add(metadata, "results", metadata_arr);
3651 : : // consume all the rows
3652 : :
3653 : 48 : bool metadata_complete = true;
3654 : 48 : while (1)
3655 : : {
3656 [ + - ]: 48 : rc = pp->step_timeout();
3657 [ + + ]: 48 : if (rc == SQLITE_DONE) // success
3658 : : break;
3659 [ + - ]: 18 : if (rc == SQLITE_ABORT || rc == SQLITE_INTERRUPT) // interrupted such as by timeout
3660 : : {
3661 : : metadata_complete = false;
3662 : : break;
3663 : : }
3664 [ - + ]: 18 : if (rc != SQLITE_ROW) // error
3665 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
3666 : :
3667 [ + - ]: 18 : int m_executable_p = sqlite3_column_int (*pp, 0);
3668 [ + - ]: 18 : int m_debuginfo_p = sqlite3_column_int (*pp, 1);
3669 [ + - ]: 18 : int m_source_p = sqlite3_column_int (*pp, 2);
3670 [ + - - + : 18 : string m_buildid = (const char*) sqlite3_column_text (*pp, 3) ?: ""; // should always be non-null
+ - ]
3671 [ + - - + : 18 : string m_file = (const char*) sqlite3_column_text (*pp, 4) ?: "";
+ - - - ]
3672 [ + - - + : 18 : string m_archive = (const char*) sqlite3_column_text (*pp, 5) ?: "";
+ - - - ]
3673 : :
3674 : : // Confirm that m_file matches in the fnmatch(FNM_PATHNAME)
3675 : : // sense, since sqlite's GLOB operator is a looser filter.
3676 [ + - + - : 18 : if (key == "glob" && fnmatch(value.c_str(), m_file.c_str(), FNM_PATHNAME) != 0)
- + ]
3677 [ # # ]: 0 : continue;
3678 : :
3679 : 54 : auto add_metadata = [metadata_arr, m_buildid, m_file, m_archive](const string& type) {
3680 : 18 : json_object* entry = json_object_new_object();
3681 [ - + - - : 18 : if (NULL == entry) throw libc_exception (ENOMEM, "cannot allocate json");
- - ]
3682 : 18 : defer_dtor<json_object*,int> entry_d(entry, json_object_put);
3683 : :
3684 : 162 : auto add_entry_metadata = [entry](const char* k, string v) {
3685 : 72 : json_object* s;
3686 [ + - ]: 72 : if(v != "") {
3687 : 72 : s = json_object_new_string(v.c_str());
3688 [ - + - - : 72 : if (NULL == s) throw libc_exception (ENOMEM, "cannot allocate json");
- - ]
3689 : 72 : json_object_object_add(entry, k, s);
3690 : : }
3691 : 72 : };
3692 : :
3693 [ + - + - ]: 18 : add_entry_metadata("type", type.c_str());
3694 [ + - + - ]: 18 : add_entry_metadata("buildid", m_buildid);
3695 [ + - + - ]: 18 : add_entry_metadata("file", m_file);
3696 [ + - + - : 36 : if (m_archive != "") add_entry_metadata("archive", m_archive);
+ - ]
3697 [ - + ]: 18 : if (verbose > 3)
3698 [ # # ]: 0 : obatched(clog) << "metadata found local "
3699 : : << json_object_to_json_string_ext(entry,
3700 [ # # # # : 0 : JSON_C_TO_STRING_PRETTY)
# # ]
3701 : 0 : << endl;
3702 : :
3703 : : // Increase ref count to switch its ownership
3704 [ + - + - ]: 18 : json_object_array_add(metadata_arr, json_object_get(entry));
3705 [ + - + - : 36 : };
+ - ]
3706 : :
3707 [ + - + - : 36 : if (m_executable_p) add_metadata("executable");
+ - ]
3708 [ - + - - : 18 : if (m_debuginfo_p) add_metadata("debuginfo");
- - ]
3709 [ - + - - : 18 : if (m_source_p) add_metadata("source");
- - ]
3710 [ - - - - : 72 : }
+ - + - +
- ]
3711 [ + - ]: 30 : pp->reset();
3712 : :
3713 [ + - ]: 30 : unsigned num_local_results = json_object_array_length(metadata_arr);
3714 : :
3715 : : // Query upstream as well
3716 [ + - ]: 30 : debuginfod_client *client = debuginfod_pool_begin();
3717 [ + - ]: 30 : if (client != NULL)
3718 : : {
3719 [ + - ]: 30 : add_client_federation_headers(client, conn);
3720 : :
3721 : 30 : int upstream_metadata_fd;
3722 : 30 : char *upstream_metadata_file = NULL;
3723 [ + - ]: 30 : upstream_metadata_fd = debuginfod_find_metadata(client, key.c_str(), (char*)value.c_str(),
3724 : : &upstream_metadata_file);
3725 [ + + ]: 30 : if (upstream_metadata_fd >= 0) {
3726 : : /* json-c >= 0.13 has json_object_from_fd(). */
3727 [ + - ]: 18 : json_object *upstream_metadata_json = json_object_from_file(upstream_metadata_file);
3728 : 18 : free (upstream_metadata_file);
3729 : 18 : json_object *upstream_metadata_json_arr;
3730 : 18 : json_object *upstream_complete;
3731 [ - + ]: 18 : if (NULL != upstream_metadata_json &&
3732 [ + - + - : 36 : json_object_object_get_ex(upstream_metadata_json, "results", &upstream_metadata_json_arr) &&
- + ]
3733 [ + - ]: 18 : json_object_object_get_ex(upstream_metadata_json, "complete", &upstream_complete))
3734 : : {
3735 [ + - ]: 18 : metadata_complete &= json_object_get_boolean(upstream_complete);
3736 [ + - + + ]: 22 : for (int i = 0, n = json_object_array_length(upstream_metadata_json_arr); i < n; i++)
3737 : : {
3738 [ + - ]: 4 : json_object *entry = json_object_array_get_idx(upstream_metadata_json_arr, i);
3739 [ - + ]: 4 : if (verbose > 3)
3740 [ # # ]: 0 : obatched(clog) << "metadata found remote "
3741 : : << json_object_to_json_string_ext(entry,
3742 [ # # # # : 0 : JSON_C_TO_STRING_PRETTY)
# # ]
3743 : 0 : << endl;
3744 : :
3745 [ + - ]: 4 : json_object_get(entry); // increment reference count
3746 [ + - ]: 4 : json_object_array_add(metadata_arr, entry);
3747 : : }
3748 [ + - ]: 18 : json_object_put(upstream_metadata_json);
3749 : : }
3750 [ + - ]: 18 : close(upstream_metadata_fd);
3751 : : }
3752 [ + - ]: 30 : debuginfod_pool_end (client);
3753 : : }
3754 : :
3755 [ + - ]: 30 : unsigned num_total_results = json_object_array_length(metadata_arr);
3756 : :
3757 [ + - ]: 30 : if (verbose > 2)
3758 [ + - + - ]: 90 : obatched(clog) << "metadata found local=" << num_local_results
3759 [ + - + - ]: 30 : << " remote=" << (num_total_results-num_local_results)
3760 [ + - + - : 30 : << " total=" << num_total_results
+ - ]
3761 : 30 : << endl;
3762 : :
3763 [ + - + - ]: 30 : json_object_object_add(metadata, "complete", json_object_new_boolean(metadata_complete));
3764 [ + - ]: 30 : const char* metadata_str = json_object_to_json_string(metadata);
3765 [ - + ]: 30 : if (!metadata_str)
3766 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate json");
3767 [ + - ]: 30 : r = MHD_create_response_from_buffer (strlen(metadata_str),
3768 : : (void*) metadata_str,
3769 : : MHD_RESPMEM_MUST_COPY);
3770 : 30 : *size = strlen(metadata_str);
3771 [ + - ]: 30 : if (r)
3772 [ + - ]: 30 : add_mhd_response_header(r, "Content-Type", "application/json");
3773 : 30 : return r;
3774 [ + - - + : 60 : }
- + - + -
+ - + -
+ ]
3775 : :
3776 : :
3777 : : static struct MHD_Response*
3778 : 0 : handle_root (off_t* size)
3779 : : {
3780 [ # # # # : 0 : static string version = "debuginfod (" + string (PACKAGE_NAME) + ") "
# # # # #
# # # ]
3781 [ # # # # : 0 : + string (PACKAGE_VERSION);
# # # # #
# ]
3782 : 0 : MHD_Response* r = MHD_create_response_from_buffer (version.size (),
3783 : 0 : (void *) version.c_str (),
3784 : : MHD_RESPMEM_PERSISTENT);
3785 [ # # ]: 0 : if (r != NULL)
3786 : : {
3787 : 0 : *size = version.size ();
3788 : 0 : add_mhd_response_header (r, "Content-Type", "text/plain");
3789 : : }
3790 : 0 : return r;
3791 : : }
3792 : :
3793 : :
3794 : : static struct MHD_Response*
3795 : 2 : handle_options (off_t* size)
3796 : : {
3797 : 2 : static char empty_body[] = " ";
3798 : 2 : MHD_Response* r = MHD_create_response_from_buffer (1, empty_body,
3799 : : MHD_RESPMEM_PERSISTENT);
3800 [ + - ]: 2 : if (r != NULL)
3801 : : {
3802 : 2 : *size = 1;
3803 : 2 : add_mhd_response_header (r, "Access-Control-Allow-Origin", "*");
3804 : 2 : add_mhd_response_header (r, "Access-Control-Allow-Methods", "GET, OPTIONS");
3805 : 2 : add_mhd_response_header (r, "Access-Control-Allow-Headers", "cache-control");
3806 : : }
3807 : 2 : return r;
3808 : : }
3809 : :
3810 : :
3811 : : ////////////////////////////////////////////////////////////////////////
3812 : :
3813 : :
3814 : : /* libmicrohttpd callback */
3815 : : static MHD_RESULT
3816 : 6712 : handler_cb (void * /*cls*/,
3817 : : struct MHD_Connection *connection,
3818 : : const char *url,
3819 : : const char *method,
3820 : : const char * /*version*/,
3821 : : const char * /*upload_data*/,
3822 : : size_t * /*upload_data_size*/,
3823 : : void ** ptr)
3824 : : {
3825 : 6712 : struct MHD_Response *r = NULL;
3826 : 6712 : string url_copy = url;
3827 : :
3828 : : /* libmicrohttpd always makes (at least) two callbacks: once just
3829 : : past the headers, and one after the request body is finished
3830 : : being received. If we process things early (first callback) and
3831 : : queue a response, libmicrohttpd would suppress http keep-alive
3832 : : (via connection->read_closed = true). */
3833 : 6708 : static int aptr; /* just some random object to use as a flag */
3834 [ + + ]: 6708 : if (&aptr != *ptr)
3835 : : {
3836 : : /* do never respond on first call */
3837 : 3354 : *ptr = &aptr;
3838 : 3354 : return MHD_YES;
3839 : : }
3840 : 3354 : *ptr = NULL; /* reset when done */
3841 : :
3842 [ + - ]: 3354 : const char *maxsize_string = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "X-DEBUGINFOD-MAXSIZE");
3843 : 3356 : long maxsize = 0;
3844 [ + + + - ]: 3356 : if (maxsize_string != NULL && maxsize_string[0] != '\0')
3845 : 2 : maxsize = atol(maxsize_string);
3846 : : else
3847 : : maxsize = 0;
3848 : :
3849 : : #if MHD_VERSION >= 0x00097002
3850 : 3356 : enum MHD_Result rc;
3851 : : #else
3852 : : int rc = MHD_NO; // mhd
3853 : : #endif
3854 : 3356 : int http_code = 500;
3855 : 3356 : off_t http_size = -1;
3856 : 3356 : struct timespec ts_start, ts_end;
3857 : 3356 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
3858 : 3355 : double afteryou = 0.0;
3859 [ + + ]: 3355 : string artifacttype, suffix;
3860 : 3355 : string urlargs; // for logging
3861 : :
3862 : 3355 : try
3863 : : {
3864 [ + + + - : 4703 : if (webapi_cors && method == string("OPTIONS"))
+ + + + +
+ ]
3865 : : {
3866 [ + - + - : 4 : inc_metric("http_requests_total", "type", method);
+ - + - -
+ - + - -
- - ]
3867 [ + - ]: 2 : r = handle_options(& http_size);
3868 [ + - ]: 2 : rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
3869 : 2 : http_code = MHD_HTTP_OK;
3870 [ + - ]: 2 : MHD_destroy_response (r);
3871 : 2 : return rc;
3872 : : }
3873 [ + - - + : 7341 : else if (string(method) != "GET")
- + ]
3874 [ # # # # ]: 0 : throw reportable_exception(400, "we support OPTIONS+GET only");
3875 : :
3876 : : /* Start decoding the URL. */
3877 : 3354 : size_t slash1 = url_copy.find('/', 1);
3878 [ + - ]: 3354 : string url1 = url_copy.substr(0, slash1); // ok even if slash1 not found
3879 : :
3880 [ + + + - ]: 5926 : if (slash1 != string::npos && url1 == "/buildid")
3881 : : {
3882 : : // PR27863: block this thread awhile if another thread is already busy
3883 : : // fetching the exact same thing. This is better for Everyone.
3884 : : // The latecomer says "... after you!" and waits.
3885 [ + - + - : 5773 : add_metric ("thread_busy", "role", "http-buildid-after-you", 1);
+ - + - -
+ + - - -
- - ]
3886 : : #ifdef HAVE_PTHREAD_SETNAME_NP
3887 : 2574 : (void) pthread_setname_np (pthread_self(), "mhd-buildid-after-you");
3888 : : #endif
3889 : 2574 : struct timespec tsay_start, tsay_end;
3890 : 2574 : clock_gettime (CLOCK_MONOTONIC, &tsay_start);
3891 [ + + + - ]: 2574 : static unique_set<string> busy_urls;
3892 [ + - ]: 2574 : unique_set_reserver<string> after_you(busy_urls, url_copy);
3893 : 2574 : clock_gettime (CLOCK_MONOTONIC, &tsay_end);
3894 : 2574 : afteryou = (tsay_end.tv_sec - tsay_start.tv_sec) + (tsay_end.tv_nsec - tsay_start.tv_nsec)/1.e9;
3895 [ + - + - : 5148 : add_metric ("thread_busy", "role", "http-buildid-after-you", -1);
+ - + - -
+ + - - -
- - ]
3896 : :
3897 [ + - + - : 5148 : tmp_inc_metric m ("thread_busy", "role", "http-buildid");
+ - + - -
+ - + - -
- - ]
3898 : : #ifdef HAVE_PTHREAD_SETNAME_NP
3899 : 2574 : (void) pthread_setname_np (pthread_self(), "mhd-buildid");
3900 : : #endif
3901 : 2574 : size_t slash2 = url_copy.find('/', slash1+1);
3902 [ - + ]: 2574 : if (slash2 == string::npos)
3903 [ # # # # ]: 0 : throw reportable_exception("/buildid/ webapi error, need buildid");
3904 : :
3905 [ + - ]: 2574 : string buildid = url_copy.substr(slash1+1, slash2-slash1-1);
3906 : :
3907 : 2574 : size_t slash3 = url_copy.find('/', slash2+1);
3908 : :
3909 [ + + ]: 2574 : if (slash3 == string::npos)
3910 : : {
3911 [ + - - + ]: 1464 : artifacttype = url_copy.substr(slash2+1);
3912 [ + - ]: 1464 : suffix = "";
3913 : : }
3914 : : else
3915 : : {
3916 [ + - - + ]: 1110 : artifacttype = url_copy.substr(slash2+1, slash3-slash2-1);
3917 [ + - - + : 1736 : suffix = url_copy.substr(slash3); // include the slash in the suffix
+ + ]
3918 : : }
3919 : :
3920 : : // get the resulting fd so we can report its size
3921 : 2574 : int fd;
3922 [ + + ]: 2574 : r = handle_buildid (connection, buildid, artifacttype, suffix, &fd);
3923 [ + - ]: 1948 : if (r)
3924 : : {
3925 : 1948 : struct stat fs;
3926 [ + - ]: 1948 : if (fstat(fd, &fs) == 0)
3927 : 1948 : http_size = fs.st_size;
3928 : : // libmicrohttpd will close (fd);
3929 : : }
3930 : 3200 : }
3931 [ + + ]: 780 : else if (url1 == "/metrics")
3932 : : {
3933 [ + - + - : 1488 : tmp_inc_metric m ("thread_busy", "role", "http-metrics");
+ - + - -
+ - + - -
- - ]
3934 [ + - ]: 744 : artifacttype = "metrics";
3935 [ + - + - : 1488 : inc_metric("http_requests_total", "type", artifacttype);
+ - - + -
- ]
3936 [ + - ]: 744 : r = handle_metrics(& http_size);
3937 : 744 : }
3938 [ + + ]: 36 : else if (url1 == "/metadata")
3939 : : {
3940 [ + - + - : 60 : tmp_inc_metric m ("thread_busy", "role", "http-metadata");
+ - + - -
+ - + - -
- - ]
3941 [ + - ]: 30 : const char* key = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "key");
3942 [ + - ]: 30 : const char* value = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "value");
3943 [ - + ]: 30 : if (NULL == value || NULL == key)
3944 [ # # # # ]: 0 : throw reportable_exception("/metadata webapi error, need key and value");
3945 : :
3946 [ + - + - : 30 : urlargs = string("?key=") + string(key) + string("&value=") + string(value); // apprx., for logging
+ - + - +
- + - + -
- + - + -
+ - + - +
- + + + -
- - - -
- ]
3947 [ + - ]: 30 : artifacttype = "metadata";
3948 [ + - + - : 60 : inc_metric("http_requests_total", "type", artifacttype);
+ - - + -
- ]
3949 [ + - + - : 30 : r = handle_metadata(connection, key, value, &http_size);
+ - - + +
+ - - ]
3950 : 30 : }
3951 [ - + ]: 6 : else if (url1 == "/")
3952 : : {
3953 [ # # ]: 0 : artifacttype = "/";
3954 [ - - - - : 634 : inc_metric("http_requests_total", "type", artifacttype);
- - - - -
- - + ]
3955 [ # # ]: 0 : r = handle_root(& http_size);
3956 : : }
3957 : : else
3958 [ + - + - : 18 : throw reportable_exception("webapi error, unrecognized '" + url1 + "'");
+ - - + ]
3959 : :
3960 [ - + ]: 2722 : if (r == 0)
3961 [ # # # # ]: 0 : throw reportable_exception("internal error, missing response");
3962 : :
3963 [ + + + - ]: 2722 : if (maxsize > 0 && http_size > maxsize)
3964 : : {
3965 [ + - ]: 2 : MHD_destroy_response(r);
3966 [ + - + - : 6 : throw reportable_exception(406, "File too large, max size=" + std::to_string(maxsize));
+ - - + ]
3967 : : }
3968 : :
3969 [ + + ]: 2720 : if (webapi_cors)
3970 : : // add ACAO header for all successful requests
3971 [ + - ]: 132 : add_mhd_response_header (r, "Access-Control-Allow-Origin", "*");
3972 [ + - ]: 2720 : rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
3973 : 2720 : http_code = MHD_HTTP_OK;
3974 [ + - ]: 2720 : MHD_destroy_response (r);
3975 : 3354 : }
3976 [ - + ]: 634 : catch (const reportable_exception& e)
3977 : : {
3978 [ + - + - : 1268 : inc_metric("http_responses_total","result","error");
+ - + - -
+ - + - -
- - ]
3979 [ + - ]: 634 : e.report(clog);
3980 : 634 : http_code = e.code;
3981 [ + - ]: 634 : http_size = e.message.size();
3982 [ + - ]: 634 : rc = e.mhd_send_response (connection);
3983 : 634 : }
3984 : :
3985 : 3354 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
3986 : 3354 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
3987 : : // afteryou: delay waiting for other client's identical query to complete
3988 : : // deltas: total latency, including afteryou waiting
3989 [ + - + - : 6708 : obatched(clog) << conninfo(connection)
- - ]
3990 : : << ' ' << method << ' ' << url << urlargs
3991 [ + - + - : 3354 : << ' ' << http_code << ' ' << http_size
+ - + - +
- + - + -
+ - ]
3992 [ + - + - : 3354 : << ' ' << (int)(afteryou*1000) << '+' << (int)((deltas-afteryou)*1000) << "ms"
+ - + - +
- + - +
- ]
3993 [ + - ]: 3354 : << endl;
3994 : :
3995 : : // related prometheus metrics
3996 : 3354 : string http_code_str = to_string(http_code);
3997 [ + - + - : 6708 : add_metric("http_responses_transfer_bytes_sum",
+ - + - -
+ - + - -
- - ]
3998 : : "code", http_code_str, "type", artifacttype, http_size);
3999 [ + - + - : 6708 : inc_metric("http_responses_transfer_bytes_count",
+ - + - -
+ - + - -
- - ]
4000 : : "code", http_code_str, "type", artifacttype);
4001 : :
4002 [ + - + - : 6708 : add_metric("http_responses_duration_milliseconds_sum",
+ - + - -
+ - + - -
- - ]
4003 : : "code", http_code_str, "type", artifacttype, deltas*1000); // prometheus prefers _seconds and floating point
4004 [ + - + - : 6708 : inc_metric("http_responses_duration_milliseconds_count",
+ - + - -
+ - + - -
- - ]
4005 : : "code", http_code_str, "type", artifacttype);
4006 : :
4007 [ + - + - : 6708 : add_metric("http_responses_after_you_milliseconds_sum",
+ - + - -
+ - + - -
- - ]
4008 : : "code", http_code_str, "type", artifacttype, afteryou*1000);
4009 [ + - + - : 6708 : inc_metric("http_responses_after_you_milliseconds_count",
+ - + - -
+ - + - -
- - - - ]
4010 : : "code", http_code_str, "type", artifacttype);
4011 : :
4012 [ - + ]: 3354 : return rc;
4013 [ + + + + : 16345 : }
- + + + ]
4014 : :
4015 : :
4016 : : ////////////////////////////////////////////////////////////////////////
4017 : : // borrowed originally from src/nm.c get_local_names()
4018 : :
4019 : : static void
4020 : 412 : dwarf_extract_source_paths (Elf *elf, set<string>& debug_sourcefiles)
4021 : : noexcept // no exceptions - so we can simplify the altdbg resource release at end
4022 : : {
4023 : 412 : Dwarf* dbg = dwarf_begin_elf (elf, DWARF_C_READ, NULL);
4024 [ - + ]: 412 : if (dbg == NULL)
4025 : 0 : return;
4026 : :
4027 : 412 : Dwarf* altdbg = NULL;
4028 : 412 : int altdbg_fd = -1;
4029 : :
4030 : : // DWZ handling: if we have an unsatisfied debug-alt-link, add an
4031 : : // empty string into the outgoing sourcefiles set, so the caller
4032 : : // should know that our data is incomplete.
4033 : 412 : const char *alt_name_p;
4034 : 412 : const void *alt_build_id; // elfutils-owned memory
4035 : 412 : ssize_t sz = dwelf_dwarf_gnu_debugaltlink (dbg, &alt_name_p, &alt_build_id);
4036 [ + + ]: 412 : if (sz > 0) // got one!
4037 : : {
4038 : 200 : string buildid;
4039 : 200 : unsigned char* build_id_bytes = (unsigned char*) alt_build_id;
4040 [ + + ]: 4200 : for (ssize_t idx=0; idx<sz; idx++)
4041 : : {
4042 : 4000 : buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
4043 : 4000 : buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
4044 : : }
4045 : :
4046 [ + + ]: 200 : if (verbose > 3)
4047 : 156 : obatched(clog) << "Need altdebug buildid=" << buildid << endl;
4048 : :
4049 : : // but is it unsatisfied the normal elfutils ways?
4050 : 200 : Dwarf* alt = dwarf_getalt (dbg);
4051 [ + - ]: 200 : if (alt == NULL)
4052 : : {
4053 : : // Yup, unsatisfied the normal way. Maybe we can satisfy it
4054 : : // from our own debuginfod database.
4055 : 200 : int alt_fd;
4056 : 200 : struct MHD_Response *r = 0;
4057 : 200 : try
4058 : : {
4059 [ + - ]: 200 : string artifacttype = "debuginfo";
4060 [ + - + + : 220 : r = handle_buildid (0, buildid, artifacttype, "", &alt_fd);
- + - + -
+ ]
4061 : : // NB: no need for ACAO etc. headers; this is not getting sent to a client
4062 : 20 : }
4063 [ - + ]: 20 : catch (const reportable_exception& e)
4064 : : {
4065 : : // swallow exceptions
4066 : 20 : }
4067 : :
4068 : : // NB: this is not actually recursive! This invokes the web-query
4069 : : // path, which cannot get back into the scan code paths.
4070 [ + - ]: 180 : if (r)
4071 : : {
4072 : : // Found it!
4073 : 180 : altdbg_fd = dup(alt_fd); // ok if this fails, downstream failures ok
4074 : 180 : alt = altdbg = dwarf_begin (altdbg_fd, DWARF_C_READ);
4075 : : // NB: must close this dwarf and this fd at the bottom of the function!
4076 : 180 : MHD_destroy_response (r); // will close alt_fd
4077 [ + - ]: 180 : if (alt)
4078 : 180 : dwarf_setalt (dbg, alt);
4079 : : }
4080 : : }
4081 : : else
4082 : : {
4083 : : // NB: dwarf_setalt(alt) inappropriate - already done!
4084 : : // NB: altdbg will stay 0 so nothing tries to redundantly dealloc.
4085 : : }
4086 : :
4087 [ + + ]: 200 : if (alt)
4088 : : {
4089 [ + + ]: 180 : if (verbose > 3)
4090 : 156 : obatched(clog) << "Resolved altdebug buildid=" << buildid << endl;
4091 : : }
4092 : : else // (alt == NULL) - signal possible presence of poor debuginfo
4093 : : {
4094 [ - + ]: 20 : debug_sourcefiles.insert("");
4095 [ - + ]: 20 : if (verbose > 3)
4096 : 0 : obatched(clog) << "Unresolved altdebug buildid=" << buildid << endl;
4097 : : }
4098 : 200 : }
4099 : :
4100 : 412 : Dwarf_Off offset = 0;
4101 : 412 : Dwarf_Off old_offset;
4102 : 412 : size_t hsize;
4103 : :
4104 [ + + ]: 9260 : while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL, NULL) == 0)
4105 : : {
4106 : 8848 : Dwarf_Die cudie_mem;
4107 : 8848 : Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
4108 : :
4109 [ - + ]: 8847 : if (cudie == NULL)
4110 : 36 : continue;
4111 [ + + ]: 8847 : if (dwarf_tag (cudie) != DW_TAG_compile_unit)
4112 : 36 : continue;
4113 : :
4114 [ - + ]: 8812 : const char *cuname = dwarf_diename(cudie) ?: "unknown";
4115 : :
4116 : 8812 : Dwarf_Files *files;
4117 : 8812 : size_t nfiles;
4118 [ - + ]: 8812 : if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
4119 : 0 : continue;
4120 : :
4121 : : // extract DW_AT_comp_dir to resolve relative file names
4122 : 8812 : const char *comp_dir = "";
4123 : 8812 : const char *const *dirs;
4124 : 8812 : size_t ndirs;
4125 [ - + ]: 8812 : if (dwarf_getsrcdirs (files, &dirs, &ndirs) == 0 &&
4126 [ - + ]: 8812 : dirs[0] != NULL)
4127 : : comp_dir = dirs[0];
4128 : : if (comp_dir == NULL)
4129 : : comp_dir = "";
4130 : :
4131 [ + + ]: 8812 : if (verbose > 3)
4132 : 13556 : obatched(clog) << "searching for sources for cu=" << cuname << " comp_dir=" << comp_dir
4133 : 6778 : << " #files=" << nfiles << " #dirs=" << ndirs << endl;
4134 : :
4135 [ + - - - ]: 8812 : if (comp_dir[0] == '\0' && cuname[0] != '/')
4136 : : {
4137 [ # # ]: 0 : if (verbose > 3)
4138 : 0 : obatched(clog) << "skipping cu=" << cuname << " due to empty comp_dir" << endl;
4139 : 0 : continue;
4140 : : }
4141 : :
4142 [ + + ]: 143478 : for (size_t f = 1; f < nfiles; f++)
4143 : : {
4144 : 134666 : const char *hat = dwarf_filesrc (files, f, NULL, NULL);
4145 [ - + ]: 134691 : if (hat == NULL)
4146 : 0 : continue;
4147 : :
4148 [ + + ]: 134692 : if (string(hat) == "<built-in>"
4149 [ + + + + : 404033 : || string_endswith(hat, "<built-in>")) // gcc intrinsics, don't bother record
+ + + + ]
4150 : 1686 : continue;
4151 : :
4152 [ + + ]: 133006 : string waldo;
4153 [ + + ]: 133006 : if (hat[0] == '/') // absolute
4154 [ - + ]: 81718 : waldo = (string (hat));
4155 [ + - ]: 51288 : else if (comp_dir[0] != '\0') // comp_dir relative
4156 [ - + - + : 89563 : waldo = (string (comp_dir) + string("/") + string (hat));
- + - + +
+ ]
4157 : : else
4158 : : {
4159 [ # # ]: 0 : if (verbose > 3)
4160 : 0 : obatched(clog) << "skipping hat=" << hat << " due to empty comp_dir" << endl;
4161 [ # # ]: 0 : continue;
4162 : : }
4163 : :
4164 : : // NB: this is the 'waldo' that a dbginfo client will have
4165 : : // to supply for us to give them the file The comp_dir
4166 : : // prefixing is a definite complication. Otherwise we'd
4167 : : // have to return a setof comp_dirs (one per CU!) with
4168 : : // corresponding filesrc[] names, instead of one absolute
4169 : : // resoved set. Maybe we'll have to do that anyway. XXX
4170 : :
4171 [ + + ]: 133001 : if (verbose > 4)
4172 [ - + ]: 32 : obatched(clog) << waldo
4173 [ - + ]: 16 : << (debug_sourcefiles.find(waldo)==debug_sourcefiles.end() ? " new" : " dup") << endl;
4174 : :
4175 [ + - ]: 133001 : debug_sourcefiles.insert (waldo);
4176 : 134666 : }
4177 : : }
4178 : :
4179 : 412 : dwarf_end(dbg);
4180 [ + + ]: 412 : if (altdbg)
4181 : 180 : dwarf_end(altdbg);
4182 [ + + ]: 412 : if (altdbg_fd >= 0)
4183 : 180 : close(altdbg_fd);
4184 : : }
4185 : :
4186 : :
4187 : :
4188 : : static void
4189 : 1699 : elf_classify (int fd, bool &executable_p, bool &debuginfo_p, string &buildid, set<string>& debug_sourcefiles)
4190 : : {
4191 : 1699 : Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
4192 [ + - ]: 1700 : if (elf == NULL)
4193 : : return;
4194 : :
4195 : 1700 : try // catch our types of errors and clean up the Elf* object
4196 : : {
4197 [ + - + + ]: 1700 : if (elf_kind (elf) != ELF_K_ELF)
4198 : : {
4199 [ + - ]: 898 : elf_end (elf);
4200 : 938 : return;
4201 : : }
4202 : :
4203 : 802 : GElf_Ehdr ehdr_storage;
4204 [ + - ]: 802 : GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_storage);
4205 [ - + ]: 802 : if (ehdr == NULL)
4206 : : {
4207 [ # # ]: 0 : elf_end (elf);
4208 : : return;
4209 : : }
4210 : 802 : auto elf_type = ehdr->e_type;
4211 : :
4212 : 802 : const void *build_id; // elfutils-owned memory
4213 [ + - ]: 802 : ssize_t sz = dwelf_elf_gnu_build_id (elf, & build_id);
4214 [ + + ]: 799 : if (sz <= 0)
4215 : : {
4216 : : // It's not a diagnostic-worthy error for an elf file to lack build-id.
4217 : : // It might just be very old.
4218 [ + - ]: 40 : elf_end (elf);
4219 : : return;
4220 : : }
4221 : :
4222 : : // build_id is a raw byte array; convert to hexadecimal *lowercase*
4223 : 759 : unsigned char* build_id_bytes = (unsigned char*) build_id;
4224 [ + + ]: 15976 : for (ssize_t idx=0; idx<sz; idx++)
4225 : : {
4226 [ + - ]: 15215 : buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
4227 [ + - ]: 30432 : buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
4228 : : }
4229 : :
4230 : : // now decide whether it's an executable - namely, any allocatable section has
4231 : : // PROGBITS;
4232 [ + + ]: 761 : if (elf_type == ET_EXEC || elf_type == ET_DYN)
4233 : : {
4234 : 700 : size_t shnum;
4235 [ + - ]: 700 : int rc = elf_getshdrnum (elf, &shnum);
4236 [ - + ]: 699 : if (rc < 0)
4237 [ # # # # ]: 0 : throw elfutils_exception(rc, "getshdrnum");
4238 : :
4239 : 699 : executable_p = false;
4240 [ + + ]: 13192 : for (size_t sc = 0; sc < shnum; sc++)
4241 : : {
4242 [ + - ]: 12866 : Elf_Scn *scn = elf_getscn (elf, sc);
4243 [ - + ]: 12862 : if (scn == NULL)
4244 : 0 : continue;
4245 : :
4246 : 12862 : GElf_Shdr shdr_mem;
4247 [ + - ]: 12862 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
4248 [ - + ]: 12867 : if (shdr == NULL)
4249 : 0 : continue;
4250 : :
4251 : : // allocated (loadable / vm-addr-assigned) section with available content?
4252 [ + + + + ]: 12867 : if ((shdr->sh_type == SHT_PROGBITS) && (shdr->sh_flags & SHF_ALLOC))
4253 : : {
4254 [ - + ]: 374 : if (verbose > 4)
4255 [ # # # # : 0 : obatched(clog) << "executable due to SHF_ALLOC SHT_PROGBITS sc=" << sc << endl;
# # ]
4256 : 374 : executable_p = true;
4257 : 374 : break; // no need to keep looking for others
4258 : : }
4259 : : } // iterate over sections
4260 : : } // executable_p classification
4261 : :
4262 : : // now decide whether it's a debuginfo - namely, if it has any .debug* or .zdebug* sections
4263 : : // logic mostly stolen from fweimer@redhat.com's elfclassify drafts
4264 : 761 : size_t shstrndx;
4265 [ + - ]: 761 : int rc = elf_getshdrstrndx (elf, &shstrndx);
4266 [ - + ]: 762 : if (rc < 0)
4267 [ # # # # ]: 0 : throw elfutils_exception(rc, "getshdrstrndx");
4268 : :
4269 : : Elf_Scn *scn = NULL;
4270 : : bool symtab_p = false;
4271 : : bool bits_alloc_p = false;
4272 : 40878 : while (true)
4273 : : {
4274 [ + - ]: 20820 : scn = elf_nextscn (elf, scn);
4275 [ + + ]: 20712 : if (scn == NULL)
4276 : : break;
4277 : 20362 : GElf_Shdr shdr_storage;
4278 [ + - ]: 20362 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
4279 [ - + ]: 20363 : if (shdr == NULL)
4280 : : break;
4281 [ + - ]: 20363 : const char *section_name = elf_strptr (elf, shstrndx, shdr->sh_name);
4282 [ - + ]: 20470 : if (section_name == NULL)
4283 : : break;
4284 [ + + ]: 20470 : if (startswith (section_name, ".debug_line") ||
4285 [ - + ]: 20058 : startswith (section_name, ".zdebug_line"))
4286 : : {
4287 : 412 : debuginfo_p = true;
4288 [ + - ]: 412 : if (scan_source_info)
4289 : 412 : dwarf_extract_source_paths (elf, debug_sourcefiles);
4290 : : break; // expecting only one .*debug_line, so no need to look for others
4291 : : }
4292 [ + + ]: 20058 : else if (startswith (section_name, ".debug_") ||
4293 [ + # ]: 18719 : startswith (section_name, ".zdebug_"))
4294 : : {
4295 : 1250 : debuginfo_p = true;
4296 : : // NB: don't break; need to parse .debug_line for sources
4297 : : }
4298 [ + + ]: 18808 : else if (shdr->sh_type == SHT_SYMTAB)
4299 : : {
4300 : : symtab_p = true;
4301 : : }
4302 : 18784 : else if (shdr->sh_type != SHT_NOBITS
4303 [ + + ]: 18784 : && shdr->sh_type != SHT_NOTE
4304 [ + + ]: 9182 : && (shdr->sh_flags & SHF_ALLOC) != 0)
4305 : : {
4306 : 20058 : bits_alloc_p = true;
4307 : : }
4308 : 20058 : }
4309 : :
4310 : : // For more expansive elf/split-debuginfo classification, we
4311 : : // want to identify as debuginfo "strip -s"-produced files
4312 : : // without .debug_info* (like libicudata), but we don't want to
4313 : : // identify "strip -g" executables (with .symtab left there).
4314 [ - + ]: 762 : if (symtab_p && !bits_alloc_p)
4315 : 0 : debuginfo_p = true;
4316 : : }
4317 [ # # ]: 0 : catch (const reportable_exception& e)
4318 : : {
4319 [ # # ]: 0 : e.report(clog);
4320 : 0 : }
4321 : 762 : elf_end (elf);
4322 : : }
4323 : :
4324 : :
4325 : : // Intern the given file name in two parts (dirname & basename) and
4326 : : // return the resulting file's id.
4327 : : static int64_t
4328 : 32726 : register_file_name(sqlite_ps& ps_upsert_fileparts,
4329 : : sqlite_ps& ps_upsert_file,
4330 : : sqlite_ps& ps_lookup_file,
4331 : : const string& name)
4332 : : {
4333 : 32726 : std::size_t slash = name.rfind('/');
4334 [ + + ]: 32724 : string dirname, filename;
4335 [ + + ]: 32724 : if (slash == std::string::npos)
4336 : : {
4337 [ + - ]: 90 : dirname = "";
4338 [ + - ]: 90 : filename = name;
4339 : : }
4340 : : else
4341 : : {
4342 [ + - - + ]: 32634 : dirname = name.substr(0, slash);
4343 [ + - - + : 32634 : filename = name.substr(slash+1);
- - ]
4344 : : }
4345 : : // NB: see also handle_metadata()
4346 : :
4347 : : // intern the two substrings
4348 : 32726 : ps_upsert_fileparts
4349 [ + - ]: 32726 : .reset()
4350 [ + - ]: 32726 : .bind(1, dirname)
4351 [ + - ]: 32726 : .step_ok_done();
4352 : 32726 : ps_upsert_fileparts
4353 [ + - ]: 32726 : .reset()
4354 [ + - ]: 32726 : .bind(1, filename)
4355 [ + - ]: 32724 : .step_ok_done();
4356 : :
4357 : : // intern the tuple
4358 : 32726 : ps_upsert_file
4359 [ + - ]: 32726 : .reset()
4360 [ + - ]: 32726 : .bind(1, dirname)
4361 [ + - ]: 32725 : .bind(2, filename)
4362 [ + - ]: 32724 : .step_ok_done();
4363 : :
4364 : : // look up the tuple's id
4365 : 32726 : ps_lookup_file
4366 [ + - ]: 32726 : .reset()
4367 [ + - ]: 32726 : .bind(1, dirname)
4368 [ + - ]: 32726 : .bind(2, filename);
4369 [ + - ]: 32726 : int rc = ps_lookup_file.step();
4370 [ - + - - : 32726 : if (rc != SQLITE_ROW) throw sqlite_exception(rc, "step");
- - ]
4371 : :
4372 [ + - ]: 32726 : int64_t id = sqlite3_column_int64 (ps_lookup_file, 0);
4373 [ + - ]: 32724 : ps_lookup_file.reset();
4374 [ + + ]: 32726 : return id;
4375 [ + + ]: 63128 : }
4376 : :
4377 : :
4378 : :
4379 : : static void
4380 : 1098 : scan_source_file (const string& rps, const stat_t& st,
4381 : : sqlite_ps& ps_upsert_buildids,
4382 : : sqlite_ps& ps_upsert_fileparts,
4383 : : sqlite_ps& ps_upsert_file,
4384 : : sqlite_ps& ps_lookup_file,
4385 : : sqlite_ps& ps_upsert_de,
4386 : : sqlite_ps& ps_upsert_s,
4387 : : sqlite_ps& ps_query,
4388 : : sqlite_ps& ps_scan_done,
4389 : : unsigned& fts_cached,
4390 : : unsigned& fts_executable,
4391 : : unsigned& fts_debuginfo,
4392 : : unsigned& fts_sourcefiles)
4393 : : {
4394 : 1098 : int64_t fileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
4395 : :
4396 : : /* See if we know of it already. */
4397 : 1098 : int rc = ps_query
4398 : 1098 : .reset()
4399 : 1098 : .bind(1, fileid)
4400 : 1098 : .bind(2, st.st_mtime)
4401 : 1098 : .step();
4402 : 1098 : ps_query.reset();
4403 [ + + ]: 1098 : if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
4404 : : // no need to recheck a file/version we already know
4405 : : // specifically, no need to elf-begin a file we already determined is non-elf
4406 : : // (so is stored with buildid=NULL)
4407 : : {
4408 : 438 : fts_cached++;
4409 : 438 : return;
4410 : : }
4411 : :
4412 : 660 : bool executable_p = false, debuginfo_p = false; // E and/or D
4413 [ + - ]: 660 : string buildid;
4414 [ + - ]: 660 : set<string> sourcefiles;
4415 : :
4416 [ + - ]: 660 : int fd = open (rps.c_str(), O_RDONLY);
4417 : 660 : try
4418 : : {
4419 [ + - ]: 660 : if (fd >= 0)
4420 [ + - ]: 660 : elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
4421 : : else
4422 [ # # # # : 0 : throw libc_exception(errno, string("open ") + rps);
# # # # ]
4423 [ + - + - : 1320 : add_metric ("scanned_bytes_total","source","file",
+ - - + -
+ - - -
- ]
4424 [ + - ]: 660 : st.st_size);
4425 [ + - + - : 1320 : inc_metric ("scanned_files_total","source","file");
+ - + - -
+ - + - -
- - ]
4426 : : }
4427 : : // NB: we catch exceptions here too, so that we can
4428 : : // cache the corrupt-elf case (!executable_p &&
4429 : : // !debuginfo_p) just below, just as if we had an
4430 : : // EPERM error from open(2).
4431 [ - - ]: 0 : catch (const reportable_exception& e)
4432 : : {
4433 [ - - ]: 0 : e.report(clog);
4434 : 0 : }
4435 : :
4436 [ + - ]: 660 : if (fd >= 0)
4437 [ + - ]: 660 : close (fd);
4438 : :
4439 [ + + ]: 660 : if (buildid == "")
4440 : : {
4441 : : // no point storing an elf file without buildid
4442 : 564 : executable_p = false;
4443 : 564 : debuginfo_p = false;
4444 : : }
4445 : : else
4446 : : {
4447 : : // register this build-id in the interning table
4448 : 96 : ps_upsert_buildids
4449 [ + - ]: 96 : .reset()
4450 [ + - ]: 96 : .bind(1, buildid)
4451 [ + - ]: 96 : .step_ok_done();
4452 : : }
4453 : :
4454 [ + + ]: 660 : if (executable_p)
4455 : 72 : fts_executable ++;
4456 [ + + ]: 660 : if (debuginfo_p)
4457 : 72 : fts_debuginfo ++;
4458 [ + + + + ]: 660 : if (executable_p || debuginfo_p)
4459 : : {
4460 : 96 : ps_upsert_de
4461 [ + - ]: 96 : .reset()
4462 [ + - ]: 96 : .bind(1, buildid)
4463 [ + + + - ]: 120 : .bind(2, debuginfo_p ? 1 : 0)
4464 [ + + + - ]: 120 : .bind(3, executable_p ? 1 : 0)
4465 [ + - ]: 96 : .bind(4, fileid)
4466 [ + - ]: 96 : .bind(5, st.st_mtime)
4467 [ + - ]: 96 : .step_ok_done();
4468 : : }
4469 [ + + ]: 660 : if (executable_p)
4470 [ + - + - : 144 : inc_metric("found_executable_total","source","files");
+ - + - -
+ - + - -
- - ]
4471 [ + + ]: 660 : if (debuginfo_p)
4472 [ + - + - : 144 : inc_metric("found_debuginfo_total","source","files");
+ - + - -
+ - + - -
- - ]
4473 : :
4474 [ + + + - ]: 732 : if (sourcefiles.size() && buildid != "")
4475 : : {
4476 : 72 : fts_sourcefiles += sourcefiles.size();
4477 : :
4478 [ + + ]: 14746 : for (auto&& dwarfsrc : sourcefiles)
4479 : : {
4480 [ + - ]: 14674 : char *srp = realpath(dwarfsrc.c_str(), NULL);
4481 [ - + ]: 14674 : if (srp == NULL) // also if DWZ unresolved dwarfsrc=""
4482 : 0 : continue; // unresolvable files are not a serious problem
4483 : : // throw libc_exception(errno, "fts/file realpath " + srcpath);
4484 [ + - ]: 14674 : string srps = string(srp);
4485 : 14674 : free (srp);
4486 : :
4487 : 14674 : struct stat sfs;
4488 : 14674 : rc = stat(srps.c_str(), &sfs);
4489 [ - + ]: 14674 : if (rc != 0)
4490 [ # # ]: 0 : continue;
4491 : :
4492 [ + - ]: 14674 : if (verbose > 2)
4493 [ + - + - : 44022 : obatched(clog) << "recorded buildid=" << buildid << " file=" << srps
- - ]
4494 [ + - + - : 14674 : << " mtime=" << sfs.st_mtime
+ - + - ]
4495 [ + - + - : 14674 : << " as source " << dwarfsrc << endl;
+ - ]
4496 : :
4497 : : // PR25548: store canonicalized dwarfsrc path
4498 [ + - ]: 14674 : string dwarfsrc_canon = canon_pathname (dwarfsrc);
4499 [ + + ]: 14674 : if (dwarfsrc_canon != dwarfsrc)
4500 : : {
4501 [ + + ]: 2636 : if (verbose > 3)
4502 [ + - + - : 4168 : obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
+ - + - +
- ]
4503 : : }
4504 : :
4505 [ + - ]: 14674 : int64_t fileid1 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, dwarfsrc_canon);
4506 [ + - ]: 14674 : int64_t fileid2 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, srps);
4507 : :
4508 : 14674 : ps_upsert_s
4509 [ + - ]: 14674 : .reset()
4510 [ + - ]: 14674 : .bind(1, buildid)
4511 [ + - ]: 14673 : .bind(2, fileid1)
4512 [ + - ]: 14674 : .bind(3, fileid2)
4513 [ + - ]: 14674 : .bind(4, sfs.st_mtime)
4514 [ + - ]: 14674 : .step_ok_done();
4515 : :
4516 [ + - + - : 29348 : inc_metric("found_sourcerefs_total","source","files");
+ - + - -
+ - + + -
- - - - -
- ]
4517 [ + - ]: 29348 : }
4518 : : }
4519 : :
4520 : 660 : ps_scan_done
4521 [ + - ]: 660 : .reset()
4522 [ + - ]: 660 : .bind(1, fileid)
4523 [ + - ]: 660 : .bind(2, st.st_mtime)
4524 [ + - ]: 660 : .bind(3, st.st_size)
4525 [ + - ]: 660 : .step_ok_done();
4526 : :
4527 [ + - ]: 660 : if (verbose > 2)
4528 [ + - + - ]: 1980 : obatched(clog) << "recorded buildid=" << buildid << " file=" << rps
4529 [ + - + - : 660 : << " mtime=" << st.st_mtime << " atype="
+ - + - ]
4530 : : << (executable_p ? "E" : "")
4531 [ + - + + : 1836 : << (debuginfo_p ? "D" : "") << endl;
+ - + + +
- + - ]
4532 [ + + ]: 756 : }
4533 : :
4534 : :
4535 : :
4536 : :
4537 : :
4538 : : // Analyze given archive file of given age; record buildids / exec/debuginfo-ness of its
4539 : : // constituent files with given upsert statements.
4540 : : static void
4541 : 396 : archive_classify (const string& rps, string& archive_extension, int64_t archiveid,
4542 : : sqlite_ps& ps_upsert_buildids, sqlite_ps& ps_upsert_fileparts, sqlite_ps& ps_upsert_file,
4543 : : sqlite_ps& ps_lookup_file,
4544 : : sqlite_ps& ps_upsert_de, sqlite_ps& ps_upsert_sref, sqlite_ps& ps_upsert_sdef,
4545 : : sqlite_ps& ps_upsert_seekable,
4546 : : time_t mtime,
4547 : : unsigned& fts_executable, unsigned& fts_debuginfo, unsigned& fts_sref, unsigned& fts_sdef,
4548 : : bool& fts_sref_complete_p)
4549 : : {
4550 : 396 : string archive_decoder = "/dev/null";
4551 [ + + ]: 1024 : for (auto&& arch : scan_archives)
4552 [ + + ]: 628 : if (string_endswith(rps, arch.first))
4553 : : {
4554 [ + - ]: 396 : archive_extension = arch.first;
4555 [ + - ]: 1024 : archive_decoder = arch.second;
4556 : : }
4557 : :
4558 : 396 : FILE* fp;
4559 : 396 : defer_dtor<FILE*,int>::dtor_fn dfn;
4560 [ + + ]: 396 : if (archive_decoder != "cat")
4561 : : {
4562 [ + - + - : 80 : string popen_cmd = archive_decoder + " " + shell_escape(rps);
+ - - + -
- - - ]
4563 [ + - ]: 40 : fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
4564 : 40 : dfn = pclose;
4565 [ - + ]: 40 : if (fp == NULL)
4566 [ # # # # : 0 : throw libc_exception (errno, string("popen ") + popen_cmd);
# # # # ]
4567 : 40 : }
4568 : : else
4569 : : {
4570 [ + - ]: 356 : fp = fopen (rps.c_str(), "r");
4571 : 356 : dfn = fclose;
4572 [ - + ]: 356 : if (fp == NULL)
4573 [ # # # # : 0 : throw libc_exception (errno, string("fopen ") + rps);
# # # # ]
4574 : : }
4575 : 396 : defer_dtor<FILE*,int> fp_closer (fp, dfn);
4576 : :
4577 : 396 : struct archive *a;
4578 [ + - ]: 396 : a = archive_read_new();
4579 [ - + ]: 396 : if (a == NULL)
4580 [ # # # # ]: 0 : throw archive_exception("cannot create archive reader");
4581 : 396 : defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
4582 : :
4583 [ + - ]: 396 : int rc = archive_read_support_format_all(a);
4584 [ - + ]: 396 : if (rc != ARCHIVE_OK)
4585 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all formats");
4586 [ + - ]: 396 : rc = archive_read_support_filter_all(a);
4587 [ - + ]: 396 : if (rc != ARCHIVE_OK)
4588 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all filters");
4589 : :
4590 [ + - ]: 396 : rc = archive_read_open_FILE (a, fp);
4591 [ - + ]: 396 : if (rc != ARCHIVE_OK)
4592 : : {
4593 [ # # # # : 0 : obatched(clog) << "cannot open archive from pipe " << rps << endl;
# # ]
4594 [ # # # # ]: 0 : throw archive_exception(a, "cannot open archive from pipe");
4595 : : }
4596 : :
4597 [ + + ]: 396 : if (verbose > 3)
4598 [ + - + - : 712 : obatched(clog) << "libarchive scanning " << rps << " id " << archiveid << endl;
+ - + - +
- ]
4599 : :
4600 [ + - ]: 396 : bool seekable = is_seekable_archive (rps, a);
4601 [ + - + + ]: 396 : if (verbose> 2 && seekable)
4602 [ + - + - : 64 : obatched(clog) << rps << " is seekable" << endl;
+ - ]
4603 : :
4604 : : bool any_exceptions = false;
4605 : 3774 : while(1) // parse archive entries
4606 : : {
4607 [ + - ]: 3774 : if (interrupted)
4608 : : break;
4609 : :
4610 : 3774 : try
4611 : : {
4612 : 3774 : struct archive_entry *e;
4613 [ + - ]: 3774 : rc = archive_read_next_header (a, &e);
4614 [ + + ]: 3774 : if (rc != ARCHIVE_OK)
4615 : : break;
4616 : :
4617 [ + - + + ]: 3378 : if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
4618 : 2338 : continue;
4619 : :
4620 [ + - ]: 1040 : string fn = canonicalized_archive_entry_pathname (e);
4621 : :
4622 [ + + ]: 1039 : if (verbose > 3)
4623 [ + - + - : 1755 : obatched(clog) << "libarchive checking " << fn << endl;
+ - - - ]
4624 : :
4625 [ + - ]: 1040 : int64_t seekable_size = archive_entry_size (e);
4626 [ + - ]: 1040 : int64_t seekable_offset = archive_filter_bytes (a, 0);
4627 [ + - ]: 1040 : time_t seekable_mtime = archive_entry_mtime (e);
4628 : :
4629 : : // extract this file to a temporary file
4630 : 1040 : char* tmppath = NULL;
4631 : 1040 : rc = asprintf (&tmppath, "%s/debuginfod-classify.XXXXXX", tmpdir.c_str());
4632 [ - + ]: 1040 : if (rc < 0)
4633 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
4634 : 1040 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
4635 [ + - ]: 1040 : int fd = mkstemp (tmppath);
4636 [ - + ]: 1040 : if (fd < 0)
4637 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
4638 : 1040 : unlink (tmppath); // unlink now so OS will release the file as soon as we close the fd
4639 : 1040 : defer_dtor<int,int> minifd_closer (fd, close);
4640 : :
4641 [ + - ]: 1040 : rc = archive_read_data_into_fd (a, fd);
4642 [ - + ]: 1040 : if (rc != ARCHIVE_OK) {
4643 [ # # ]: 0 : close (fd);
4644 [ # # # # ]: 0 : throw archive_exception(a, "cannot extract file");
4645 : : }
4646 : :
4647 : : // finally ... time to run elf_classify on this bad boy and update the database
4648 : 1040 : bool executable_p = false, debuginfo_p = false;
4649 [ + - ]: 1040 : string buildid;
4650 [ + - ]: 1040 : set<string> sourcefiles;
4651 [ + - ]: 1040 : elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
4652 : : // NB: might throw
4653 : :
4654 [ + + ]: 1040 : if (buildid != "") // intern buildid
4655 : : {
4656 : 666 : ps_upsert_buildids
4657 [ + - ]: 666 : .reset()
4658 [ + - ]: 666 : .bind(1, buildid)
4659 [ + - ]: 666 : .step_ok_done();
4660 : : }
4661 : :
4662 [ + - ]: 1040 : int64_t fileid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, fn);
4663 : :
4664 [ + + ]: 1040 : if (sourcefiles.size() > 0) // sref records needed
4665 : : {
4666 : : // NB: we intern each source file once. Once raw, as it
4667 : : // appears in the DWARF file list coming back from
4668 : : // elf_classify() - because it'll end up in the
4669 : : // _norm.artifactsrc column. We don't also put another
4670 : : // version with a '.' at the front, even though that's
4671 : : // how rpm/cpio packs names, because we hide that from
4672 : : // the database for storage efficiency.
4673 : :
4674 [ + + ]: 802 : for (auto&& s : sourcefiles)
4675 : : {
4676 [ + + ]: 498 : if (s == "")
4677 : : {
4678 : 20 : fts_sref_complete_p = false;
4679 : 20 : continue;
4680 : : }
4681 : :
4682 : : // PR25548: store canonicalized source path
4683 : 478 : const string& dwarfsrc = s;
4684 [ + - ]: 478 : string dwarfsrc_canon = canon_pathname (dwarfsrc);
4685 [ + + ]: 478 : if (dwarfsrc_canon != dwarfsrc)
4686 : : {
4687 [ + - ]: 28 : if (verbose > 3)
4688 [ + - + - : 56 : obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
+ - + - +
- - - ]
4689 : : }
4690 : :
4691 [ + - ]: 478 : int64_t srcfileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
4692 : : dwarfsrc_canon);
4693 : :
4694 : 478 : ps_upsert_sref
4695 [ + - ]: 478 : .reset()
4696 [ + - ]: 478 : .bind(1, buildid)
4697 [ + - ]: 478 : .bind(2, srcfileid)
4698 [ + - ]: 478 : .step_ok_done();
4699 : :
4700 [ + - ]: 478 : fts_sref ++;
4701 : 478 : }
4702 : : }
4703 : :
4704 [ + + ]: 1040 : if (executable_p)
4705 : 302 : fts_executable ++;
4706 [ + + ]: 1040 : if (debuginfo_p)
4707 : 366 : fts_debuginfo ++;
4708 : :
4709 [ + + + + ]: 1040 : if (executable_p || debuginfo_p)
4710 : : {
4711 : 666 : ps_upsert_de
4712 [ + - ]: 666 : .reset()
4713 [ + - ]: 666 : .bind(1, buildid)
4714 [ + + + - ]: 966 : .bind(2, debuginfo_p ? 1 : 0)
4715 [ + + + - ]: 1030 : .bind(3, executable_p ? 1 : 0)
4716 [ + - ]: 666 : .bind(4, archiveid)
4717 [ + - ]: 666 : .bind(5, mtime)
4718 [ + - ]: 666 : .bind(6, fileid)
4719 [ + - ]: 666 : .step_ok_done();
4720 [ + + ]: 666 : if (seekable)
4721 : 336 : ps_upsert_seekable
4722 [ + - ]: 336 : .reset()
4723 [ + - ]: 336 : .bind(1, archiveid)
4724 [ + - ]: 336 : .bind(2, fileid)
4725 [ + - ]: 336 : .bind(3, seekable_size)
4726 [ + - ]: 336 : .bind(4, seekable_offset)
4727 [ + - ]: 336 : .bind(5, seekable_mtime)
4728 [ + - ]: 336 : .step_ok_done();
4729 : : }
4730 : : else // potential source - sdef record
4731 : : {
4732 : 374 : fts_sdef ++;
4733 : 374 : ps_upsert_sdef
4734 [ + - ]: 374 : .reset()
4735 [ + - ]: 374 : .bind(1, archiveid)
4736 [ + - ]: 374 : .bind(2, mtime)
4737 [ + - ]: 374 : .bind(3, fileid)
4738 [ + - ]: 374 : .step_ok_done();
4739 : : }
4740 : :
4741 [ + - + + : 1040 : if ((verbose > 2) && (executable_p || debuginfo_p))
+ + ]
4742 : : {
4743 [ + - ]: 666 : obatched ob(clog);
4744 [ + - + - ]: 666 : auto& o = ob << "recorded buildid=" << buildid << " rpm=" << rps << " file=" << fn
4745 [ + - + - : 666 : << " mtime=" << mtime << " atype="
+ - + - +
- + - ]
4746 : : << (executable_p ? "E" : "")
4747 : : << (debuginfo_p ? "D" : "")
4748 [ + - + + : 1330 : << " sourcefiles=" << sourcefiles.size();
+ - + + +
- + - +
- ]
4749 [ + + ]: 666 : if (seekable)
4750 [ + - + - ]: 336 : o << " seekable size=" << seekable_size
4751 [ + - + - ]: 336 : << " offset=" << seekable_offset
4752 [ + - + - ]: 336 : << " mtime=" << seekable_mtime;
4753 [ + - ]: 666 : o << endl;
4754 : 666 : }
4755 : :
4756 [ + + + + ]: 2584 : }
4757 [ - - ]: 0 : catch (const reportable_exception& e)
4758 : : {
4759 [ - - ]: 0 : e.report(clog);
4760 : 0 : any_exceptions = true;
4761 : : // NB: but we allow the libarchive iteration to continue, in
4762 : : // case we can still gather some useful information. That
4763 : : // would allow some webapi queries to work, until later when
4764 : : // this archive is rescanned. (Its vitals won't go into the
4765 : : // _file_mtime_scanned table until after a successful scan.)
4766 : 0 : }
4767 : : }
4768 : :
4769 [ - + ]: 396 : if (any_exceptions)
4770 [ # # # # ]: 0 : throw reportable_exception("exceptions encountered during archive scan");
4771 [ + + ]: 420 : }
4772 : :
4773 : :
4774 : :
4775 : : // scan for archive files such as .rpm
4776 : : static void
4777 : 762 : scan_archive_file (const string& rps, const stat_t& st,
4778 : : sqlite_ps& ps_upsert_buildids,
4779 : : sqlite_ps& ps_upsert_fileparts,
4780 : : sqlite_ps& ps_upsert_file,
4781 : : sqlite_ps& ps_lookup_file,
4782 : : sqlite_ps& ps_upsert_de,
4783 : : sqlite_ps& ps_upsert_sref,
4784 : : sqlite_ps& ps_upsert_sdef,
4785 : : sqlite_ps& ps_upsert_seekable,
4786 : : sqlite_ps& ps_query,
4787 : : sqlite_ps& ps_scan_done,
4788 : : unsigned& fts_cached,
4789 : : unsigned& fts_executable,
4790 : : unsigned& fts_debuginfo,
4791 : : unsigned& fts_sref,
4792 : : unsigned& fts_sdef)
4793 : : {
4794 : : // intern the archive file name
4795 : 762 : int64_t archiveid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
4796 : :
4797 : : /* See if we know of it already. */
4798 : 762 : int rc = ps_query
4799 : 762 : .reset()
4800 : 762 : .bind(1, archiveid)
4801 : 762 : .bind(2, st.st_mtime)
4802 : 762 : .step();
4803 : 762 : ps_query.reset();
4804 [ + + ]: 762 : if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
4805 : : // no need to recheck a file/version we already know
4806 : : // specifically, no need to parse this archive again, since we already have
4807 : : // it as a D or E or S record,
4808 : : // (so is stored with buildid=NULL)
4809 : : {
4810 : 366 : fts_cached ++;
4811 : 366 : return;
4812 : : }
4813 : :
4814 : : // extract the archive contents
4815 : 396 : unsigned my_fts_executable = 0, my_fts_debuginfo = 0, my_fts_sref = 0, my_fts_sdef = 0;
4816 : 396 : bool my_fts_sref_complete_p = true;
4817 : 396 : bool any_exceptions = false;
4818 : 396 : try
4819 : : {
4820 [ + - ]: 396 : string archive_extension;
4821 : 396 : archive_classify (rps, archive_extension, archiveid,
4822 : : ps_upsert_buildids, ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
4823 : : ps_upsert_de, ps_upsert_sref, ps_upsert_sdef, ps_upsert_seekable, // dalt
4824 [ + - ]: 396 : st.st_mtime,
4825 : : my_fts_executable, my_fts_debuginfo, my_fts_sref, my_fts_sdef,
4826 : : my_fts_sref_complete_p);
4827 [ + - + - : 792 : add_metric ("scanned_bytes_total","source",archive_extension + " archive",
+ - - + +
+ - - -
- ]
4828 [ + - ]: 396 : st.st_size);
4829 [ + - + - : 792 : inc_metric ("scanned_files_total","source",archive_extension + " archive");
+ - + - -
+ + + - -
- - ]
4830 [ + - + - : 792 : add_metric("found_debuginfo_total","source",archive_extension + " archive",
+ - + - -
+ + + - -
- - ]
4831 : : my_fts_debuginfo);
4832 [ + - + - : 792 : add_metric("found_executable_total","source",archive_extension + " archive",
+ - + - -
+ + + - -
- - ]
4833 : : my_fts_executable);
4834 [ + - + - : 808 : add_metric("found_sourcerefs_total","source",archive_extension + " archive",
+ - + - -
+ + + - +
- - - - -
- ]
4835 : : my_fts_sref);
4836 : 396 : }
4837 [ - - ]: 0 : catch (const reportable_exception& e)
4838 : : {
4839 [ - - ]: 0 : e.report(clog);
4840 : 0 : any_exceptions = true;
4841 : 0 : }
4842 : :
4843 [ + - ]: 396 : if (verbose > 2)
4844 [ + - ]: 1188 : obatched(clog) << "scanned archive=" << rps
4845 [ + - + - ]: 396 : << " mtime=" << st.st_mtime
4846 [ + - ]: 396 : << " executables=" << my_fts_executable
4847 [ + - + - ]: 396 : << " debuginfos=" << my_fts_debuginfo
4848 [ + - + - ]: 396 : << " srefs=" << my_fts_sref
4849 [ + - + - ]: 396 : << " sdefs=" << my_fts_sdef
4850 [ + - + - : 396 : << " exceptions=" << any_exceptions
+ - + - ]
4851 : 396 : << endl;
4852 : :
4853 : 396 : fts_executable += my_fts_executable;
4854 : 396 : fts_debuginfo += my_fts_debuginfo;
4855 : 396 : fts_sref += my_fts_sref;
4856 : 396 : fts_sdef += my_fts_sdef;
4857 : :
4858 [ - + ]: 396 : if (any_exceptions)
4859 [ # # # # ]: 0 : throw reportable_exception("exceptions encountered during archive scan");
4860 : :
4861 [ + + ]: 396 : if (my_fts_sref_complete_p) // leave incomplete?
4862 : 394 : ps_scan_done
4863 : 394 : .reset()
4864 : 394 : .bind(1, archiveid)
4865 : 394 : .bind(2, st.st_mtime)
4866 : 394 : .bind(3, st.st_size)
4867 : 394 : .step_ok_done();
4868 : : }
4869 : :
4870 : :
4871 : :
4872 : : ////////////////////////////////////////////////////////////////////////
4873 : :
4874 : :
4875 : :
4876 : : // The thread that consumes file names off of the scanq. We hold
4877 : : // the persistent sqlite_ps's at this level and delegate file/archive
4878 : : // scanning to other functions.
4879 : : static void
4880 : 288 : scan ()
4881 : : {
4882 : : // all the prepared statements fit to use, the _f_ set:
4883 [ + - + - : 576 : sqlite_ps ps_f_upsert_buildids (db, "file-buildids-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
+ - - - ]
4884 [ + - + - : 576 : sqlite_ps ps_f_upsert_fileparts (db, "file-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
+ - + - -
- ]
4885 [ + - ]: 288 : sqlite_ps ps_f_upsert_file (db, "file-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
4886 : : "(select id from " BUILDIDS "_fileparts where name = ?),\n"
4887 [ + - + - : 576 : "(select id from " BUILDIDS "_fileparts where name = ?));");
+ - + - -
- ]
4888 [ + - ]: 288 : sqlite_ps ps_f_lookup_file (db, "file-file-lookup",
4889 : : "select f.id\n"
4890 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
4891 [ + - + - : 576 : " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
+ - + - -
- ]
4892 [ + - ]: 288 : sqlite_ps ps_f_upsert_de (db, "file-de-upsert",
4893 : : "insert or ignore into " BUILDIDS "_f_de "
4894 : : "(buildid, debuginfo_p, executable_p, file, mtime) "
4895 : : "values ((select id from " BUILDIDS "_buildids where hex = ?),"
4896 [ + - + - : 576 : " ?,?,?,?);");
+ - + - -
- ]
4897 [ + - ]: 288 : sqlite_ps ps_f_upsert_s (db, "file-s-upsert",
4898 : : "insert or ignore into " BUILDIDS "_f_s "
4899 : : "(buildid, artifactsrc, file, mtime) "
4900 : : "values ((select id from " BUILDIDS "_buildids where hex = ?),"
4901 [ + - + - : 576 : " ?,?,?);");
+ - + - -
- ]
4902 [ + - ]: 288 : sqlite_ps ps_f_query (db, "file-negativehit-find",
4903 : : "select 1 from " BUILDIDS "_file_mtime_scanned where sourcetype = 'F' "
4904 [ + - + - : 576 : "and file = ? and mtime = ?;");
+ - + - -
- ]
4905 [ + - ]: 288 : sqlite_ps ps_f_scan_done (db, "file-scanned",
4906 : : "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
4907 [ + - + - : 576 : "values ('F', ?,?,?);");
+ - + - -
- ]
4908 : :
4909 : : // and now for the _r_ set
4910 [ + - + - : 576 : sqlite_ps ps_r_upsert_buildids (db, "rpm-buildid-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
+ - + - -
- ]
4911 [ + - + - : 576 : sqlite_ps ps_r_upsert_fileparts (db, "rpm-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
+ - + - -
- ]
4912 [ + - ]: 288 : sqlite_ps ps_r_upsert_file (db, "rpm-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
4913 : : "(select id from " BUILDIDS "_fileparts where name = ?),\n"
4914 [ + - + - : 576 : "(select id from " BUILDIDS "_fileparts where name = ?));");
+ - + - -
- ]
4915 [ + - ]: 288 : sqlite_ps ps_r_lookup_file (db, "rpm-file-lookup",
4916 : : "select f.id\n"
4917 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
4918 [ + - + - : 576 : " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
+ - + - -
- ]
4919 [ + - ]: 288 : sqlite_ps ps_r_upsert_de (db, "rpm-de-insert",
4920 : : "insert or ignore into " BUILDIDS "_r_de (buildid, debuginfo_p, executable_p, file, mtime, content) values ("
4921 [ + - + - : 576 : "(select id from " BUILDIDS "_buildids where hex = ?), ?, ?, ?, ?, ?);");
+ - + - -
- ]
4922 [ + - ]: 288 : sqlite_ps ps_r_upsert_sref (db, "rpm-sref-insert",
4923 : : "insert or ignore into " BUILDIDS "_r_sref (buildid, artifactsrc) values ("
4924 : : "(select id from " BUILDIDS "_buildids where hex = ?), "
4925 [ + - + - : 576 : "?);");
+ - + - -
- ]
4926 [ + - ]: 288 : sqlite_ps ps_r_upsert_sdef (db, "rpm-sdef-insert",
4927 : : "insert or ignore into " BUILDIDS "_r_sdef (file, mtime, content) values ("
4928 [ + - + - : 576 : "?, ?, ?);");
+ - + - -
- ]
4929 [ + - ]: 288 : sqlite_ps ps_r_upsert_seekable (db, "rpm-seekable-insert",
4930 : : "insert or ignore into " BUILDIDS "_r_seekable (file, content, type, size, offset, mtime) "
4931 [ + - + - : 576 : "values (?, ?, 'xz', ?, ?, ?);");
+ - + - -
- ]
4932 [ + - ]: 288 : sqlite_ps ps_r_query (db, "rpm-negativehit-query",
4933 : : "select 1 from " BUILDIDS "_file_mtime_scanned where "
4934 [ + - + - : 576 : "sourcetype = 'R' and file = ? and mtime = ?;");
+ - + - -
- ]
4935 [ + - ]: 288 : sqlite_ps ps_r_scan_done (db, "rpm-scanned",
4936 : : "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
4937 [ + - + - : 576 : "values ('R', ?, ?, ?);");
+ - + - -
- ]
4938 : :
4939 : :
4940 : 288 : unsigned fts_cached = 0, fts_executable = 0, fts_debuginfo = 0, fts_sourcefiles = 0;
4941 : 288 : unsigned fts_sref = 0, fts_sdef = 0;
4942 : :
4943 [ + - + - : 576 : add_metric("thread_count", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
4944 [ + - + - : 576 : add_metric("thread_busy", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
4945 [ + + ]: 1882 : while (! interrupted)
4946 : : {
4947 [ + - ]: 1594 : scan_payload p;
4948 : :
4949 [ + - + - : 3188 : add_metric("thread_busy", "role", "scan", -1);
+ - + - -
+ - + - -
- - ]
4950 : : // NB: threads may be blocked within either of these two waiting
4951 : : // states, if the work queue happens to run dry. That's OK.
4952 [ + - + - ]: 1594 : if (scan_barrier) scan_barrier->count();
4953 [ + - ]: 1593 : bool gotone = scanq.wait_front(p);
4954 [ + - + - : 3188 : add_metric("thread_busy", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
4955 : :
4956 [ + + - + ]: 1594 : if (! gotone) continue; // go back to waiting
4957 : :
4958 : 1306 : try
4959 : : {
4960 : 1306 : bool scan_archive = false;
4961 [ + + ]: 2878 : for (auto&& arch : scan_archives)
4962 [ + + ]: 1572 : if (string_endswith(p.first, arch.first))
4963 : 762 : scan_archive = true;
4964 : :
4965 [ + + ]: 1306 : if (scan_archive)
4966 [ + - ]: 762 : scan_archive_file (p.first, p.second,
4967 : : ps_r_upsert_buildids,
4968 : : ps_r_upsert_fileparts,
4969 : : ps_r_upsert_file,
4970 : : ps_r_lookup_file,
4971 : : ps_r_upsert_de,
4972 : : ps_r_upsert_sref,
4973 : : ps_r_upsert_sdef,
4974 : : ps_r_upsert_seekable,
4975 : : ps_r_query,
4976 : : ps_r_scan_done,
4977 : : fts_cached,
4978 : : fts_executable,
4979 : : fts_debuginfo,
4980 : : fts_sref,
4981 : : fts_sdef);
4982 : :
4983 [ + + ]: 1306 : if (scan_files) // NB: maybe "else if" ?
4984 [ + - ]: 1098 : scan_source_file (p.first, p.second,
4985 : : ps_f_upsert_buildids,
4986 : : ps_f_upsert_fileparts,
4987 : : ps_f_upsert_file,
4988 : : ps_f_lookup_file,
4989 : : ps_f_upsert_de,
4990 : : ps_f_upsert_s,
4991 : : ps_f_query,
4992 : : ps_f_scan_done,
4993 : : fts_cached, fts_executable, fts_debuginfo, fts_sourcefiles);
4994 : : }
4995 [ - - ]: 0 : catch (const reportable_exception& e)
4996 : : {
4997 [ - - ]: 0 : e.report(cerr);
4998 : 0 : }
4999 : :
5000 [ + - ]: 1306 : scanq.done_front(); // let idlers run
5001 : :
5002 : 1306 : if (fts_cached || fts_executable || fts_debuginfo || fts_sourcefiles || fts_sref || fts_sdef)
5003 : : {} // NB: not just if a successful scan - we might have encountered -ENOSPC & failed
5004 [ + - + - ]: 1306 : (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
5005 [ + - + - ]: 1306 : (void) statfs_free_enough_p(tmpdir, "tmpdir"); // this too, in case of fdcache/tmpfile usage
5006 : :
5007 : : // finished a scanning step -- not a "loop", because we just
5008 : : // consume the traversal loop's work, whenever
5009 [ + - + - : 2612 : inc_metric("thread_work_total","role","scan");
+ - + - -
+ - + + -
- - - - -
- ]
5010 : 1594 : }
5011 : :
5012 [ + - + - : 576 : add_metric("thread_busy", "role", "scan", -1);
+ - + - -
+ - + - -
- - ]
5013 : 288 : }
5014 : :
5015 : :
5016 : : // Use this function as the thread entry point, so it can catch our
5017 : : // fleet of exceptions (incl. the sqlite_ps ctors) and report.
5018 : : static void*
5019 : 288 : thread_main_scanner (void* arg)
5020 : : {
5021 : 288 : (void) arg;
5022 [ + + ]: 864 : while (! interrupted)
5023 : 288 : try
5024 : : {
5025 [ + - ]: 288 : scan();
5026 : : }
5027 [ - - ]: 0 : catch (const reportable_exception& e)
5028 : : {
5029 [ - - ]: 0 : e.report(cerr);
5030 : 0 : }
5031 : 288 : return 0;
5032 : : }
5033 : :
5034 : :
5035 : :
5036 : : // The thread that traverses all the source_paths and enqueues all the
5037 : : // matching files into the file/archive scan queue.
5038 : : static void
5039 : 126 : scan_source_paths()
5040 : : {
5041 : : // NB: fedora 31 glibc/fts(3) crashes inside fts_read() on empty
5042 : : // path list.
5043 [ + + ]: 126 : if (source_paths.empty())
5044 : 2 : return;
5045 : :
5046 : : // Turn the source_paths into an fts(3)-compatible char**. Since
5047 : : // source_paths[] does not change after argv processing, the
5048 : : // c_str()'s are safe to keep around awile.
5049 : 124 : vector<const char *> sps;
5050 [ + + ]: 332 : for (auto&& sp: source_paths)
5051 [ + - ]: 208 : sps.push_back(sp.c_str());
5052 [ + - - - ]: 124 : sps.push_back(NULL);
5053 : :
5054 [ + + + - ]: 234 : FTS *fts = fts_open ((char * const *)sps.data(),
5055 : : (traverse_logical ? FTS_LOGICAL : FTS_PHYSICAL|FTS_XDEV)
5056 : : | FTS_NOCHDIR /* multithreaded */,
5057 : : NULL);
5058 [ - + ]: 124 : if (fts == NULL)
5059 [ # # # # ]: 0 : throw libc_exception(errno, "cannot fts_open");
5060 : 124 : defer_dtor<FTS*,int> fts_cleanup (fts, fts_close);
5061 : :
5062 : 124 : struct timespec ts_start, ts_end;
5063 : 124 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
5064 : 124 : unsigned fts_scanned = 0, fts_regex = 0;
5065 : :
5066 : 124 : FTSENT *f;
5067 [ + - + + ]: 2636 : while ((f = fts_read (fts)) != NULL)
5068 : : {
5069 [ + - ]: 2388 : if (interrupted) break;
5070 : :
5071 [ - + ]: 2388 : if (sigusr2 != forced_groom_count) // stop early if groom triggered
5072 : : {
5073 [ # # ]: 0 : scanq.clear(); // clear previously issued work for scanner threads
5074 : : break;
5075 : : }
5076 : :
5077 : 2388 : fts_scanned ++;
5078 : :
5079 [ + - ]: 2388 : if (verbose > 2)
5080 [ + - + - : 4776 : obatched(clog) << "fts traversing " << f->fts_path << endl;
+ - ]
5081 : :
5082 [ + + + + : 2388 : switch (f->fts_info)
+ ]
5083 : : {
5084 : 1416 : case FTS_F:
5085 : 1416 : {
5086 : : /* Found a file. Convert it to an absolute path, so
5087 : : the buildid database does not have relative path
5088 : : names that are unresolvable from a subsequent run
5089 : : in a different cwd. */
5090 [ + - ]: 1416 : char *rp = realpath(f->fts_path, NULL);
5091 [ - + ]: 1416 : if (rp == NULL)
5092 : 0 : continue; // ignore dangling symlink or such
5093 [ + - ]: 1416 : string rps = string(rp);
5094 : 1416 : free (rp);
5095 : :
5096 [ + - ]: 1416 : bool ri = !regexec (&file_include_regex, rps.c_str(), 0, 0, 0);
5097 [ + - ]: 1416 : bool rx = !regexec (&file_exclude_regex, rps.c_str(), 0, 0, 0);
5098 [ + + ]: 1416 : if (!ri || rx)
5099 : : {
5100 [ + - ]: 110 : if (verbose > 3)
5101 [ + - ]: 220 : obatched(clog) << "fts skipped by regex "
5102 [ + + + - : 134 : << (!ri ? "I" : "") << (rx ? "X" : "") << endl;
+ + + - +
- ]
5103 : 110 : fts_regex ++;
5104 [ + + ]: 110 : if (!ri)
5105 [ + - + - : 24 : inc_metric("traversed_total","type","file-skipped-I");
+ - + - -
+ - + - -
- - ]
5106 [ + + ]: 110 : if (rx)
5107 [ + - + - : 196 : inc_metric("traversed_total","type","file-skipped-X");
+ - + - -
+ - + - -
- - ]
5108 : : }
5109 : : else
5110 : : {
5111 [ + - + - ]: 1306 : scanq.push_back (make_pair(rps, *f->fts_statp));
5112 [ + - + - : 2612 : inc_metric("traversed_total","type","file");
+ - + - -
+ - + - -
- - - - ]
5113 : : }
5114 : 0 : }
5115 : 1416 : break;
5116 : :
5117 : 4 : case FTS_ERR:
5118 : 4 : case FTS_NS:
5119 : : // report on some types of errors because they may reflect fixable misconfiguration
5120 : 4 : {
5121 [ + - + - : 8 : auto x = libc_exception(f->fts_errno, string("fts traversal ") + string(f->fts_path));
+ - + - -
+ - + -
- ]
5122 [ + - ]: 4 : x.report(cerr);
5123 : 0 : }
5124 [ + - + - : 8 : inc_metric("traversed_total","type","error");
+ - + - -
+ - + - -
- - ]
5125 : 4 : break;
5126 : :
5127 : 32 : case FTS_SL: // ignore, but count because debuginfod -L would traverse these
5128 [ + - + - : 64 : inc_metric("traversed_total","type","symlink");
+ - + - -
+ - + - -
- - ]
5129 : 32 : break;
5130 : :
5131 : 468 : case FTS_D: // ignore
5132 [ + - + - : 936 : inc_metric("traversed_total","type","directory");
+ - + - -
+ - + - -
- - ]
5133 : 468 : break;
5134 : :
5135 : 468 : default: // ignore
5136 [ + - + - : 936 : inc_metric("traversed_total","type","other");
+ - + - -
+ - + - -
- - ]
5137 : 468 : break;
5138 : : }
5139 : : }
5140 : 124 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
5141 : 124 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
5142 : :
5143 [ + - + - : 372 : obatched(clog) << "fts traversed source paths in " << deltas << "s, scanned=" << fts_scanned
+ - + - ]
5144 [ + - + - : 124 : << ", regex-skipped=" << fts_regex << endl;
+ - ]
5145 [ + - ]: 248 : }
5146 : :
5147 : :
5148 : : static void*
5149 : 72 : thread_main_fts_source_paths (void* arg)
5150 : : {
5151 : 72 : (void) arg; // ignore; we operate on global data
5152 : :
5153 [ + - + - : 144 : set_metric("thread_tid", "role","traverse", tid());
+ - - + -
+ - - -
- ]
5154 [ + - + - : 144 : add_metric("thread_count", "role", "traverse", 1);
+ - - + -
+ - - -
- ]
5155 : :
5156 : 72 : time_t last_rescan = 0;
5157 : :
5158 [ + - ]: 299 : while (! interrupted)
5159 : : {
5160 : 299 : sleep (1);
5161 : 299 : scanq.wait_idle(); // don't start a new traversal while scanners haven't finished the job
5162 : 299 : scanq.done_idle(); // release the hounds
5163 [ + + ]: 299 : if (interrupted) break;
5164 : :
5165 : 227 : time_t now = time(NULL);
5166 : 227 : bool rescan_now = false;
5167 [ + + ]: 227 : if (last_rescan == 0) // at least one initial rescan is documented even for -t0
5168 : 70 : rescan_now = true;
5169 [ + + + + ]: 227 : if (rescan_s > 0 && (long)now > (long)(last_rescan + rescan_s))
5170 : 227 : rescan_now = true;
5171 [ + + ]: 227 : if (sigusr1 != forced_rescan_count)
5172 : : {
5173 : 58 : forced_rescan_count = sigusr1;
5174 : 58 : rescan_now = true;
5175 : : }
5176 [ + + ]: 227 : if (rescan_now)
5177 : : {
5178 [ + - + - : 252 : set_metric("thread_busy", "role","traverse", 1);
+ - - + -
+ - - -
- ]
5179 : 126 : try
5180 : : {
5181 [ + - ]: 126 : scan_source_paths();
5182 : : }
5183 [ - - ]: 0 : catch (const reportable_exception& e)
5184 : : {
5185 [ - - ]: 0 : e.report(cerr);
5186 : 0 : }
5187 : 126 : last_rescan = time(NULL); // NB: now was before scanning
5188 : : // finished a traversal loop
5189 [ + - + - : 252 : inc_metric("thread_work_total", "role","traverse");
+ - - + -
+ - - -
- ]
5190 [ + - + - : 252 : set_metric("thread_busy", "role","traverse", 0);
+ - - + -
+ - - -
- ]
5191 : : }
5192 : : }
5193 : :
5194 : 72 : return 0;
5195 : : }
5196 : :
5197 : :
5198 : :
5199 : : ////////////////////////////////////////////////////////////////////////
5200 : :
5201 : : static void
5202 : 78 : database_stats_report()
5203 : : {
5204 : 78 : sqlite_ps ps_query (db, "database-overview",
5205 [ + - + - : 156 : "select label,quantity from " BUILDIDS "_stats");
+ - - - ]
5206 : :
5207 [ + - + - ]: 156 : obatched(clog) << "database record counts:" << endl;
5208 : 1794 : while (1)
5209 : : {
5210 [ + - ]: 936 : if (interrupted) break;
5211 [ + - ]: 936 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
5212 : : break;
5213 : :
5214 [ + - ]: 936 : int rc = ps_query.step();
5215 [ + + ]: 936 : if (rc == SQLITE_DONE) break;
5216 [ - + ]: 858 : if (rc != SQLITE_ROW)
5217 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
5218 : :
5219 [ + - ]: 858 : obatched(clog)
5220 [ + - - + : 858 : << ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL")
+ - ]
5221 : : << " "
5222 [ + - + - : 1716 : << (sqlite3_column_text(ps_query, 1) ?: (const unsigned char*) "NULL")
- + + - ]
5223 : 858 : << endl;
5224 : :
5225 [ + - + - : 1716 : set_metric("groom", "statistic",
- + + - +
- + - + -
- + + + -
- - - ]
5226 [ + - ]: 858 : ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL"),
5227 : : (sqlite3_column_double(ps_query, 1)));
5228 : 858 : }
5229 : 78 : }
5230 : :
5231 : :
5232 : : // Do a round of database grooming that might take many minutes to run.
5233 : 78 : void groom()
5234 : : {
5235 [ + - ]: 156 : obatched(clog) << "grooming database" << endl;
5236 : :
5237 : 78 : struct timespec ts_start, ts_end;
5238 : 78 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
5239 : :
5240 : : // scan for files that have disappeared
5241 : 78 : sqlite_ps files (db, "check old files",
5242 : : "select distinct s.mtime, s.file, f.name from "
5243 : : BUILDIDS "_file_mtime_scanned s, " BUILDIDS "_files_v f "
5244 [ + - + - : 156 : "where f.id = s.file");
+ - - - ]
5245 : : // NB: Because _ftime_mtime_scanned can contain both F and
5246 : : // R records for the same file, this query would return duplicates if the
5247 : : // DISTINCT qualifier were not there.
5248 [ + - ]: 78 : files.reset();
5249 : :
5250 : : // DECISION TIME - we enumerate stale fileids/mtimes
5251 [ + - ]: 78 : deque<pair<int64_t,int64_t> > stale_fileid_mtime;
5252 : :
5253 : 78 : time_t time_start = time(NULL);
5254 : 346 : while(1)
5255 : : {
5256 : : // PR28514: limit grooming iteration to O(rescan time), to avoid
5257 : : // slow filesystem tests over many files locking out rescans for
5258 : : // too long.
5259 [ + + - + ]: 212 : if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
5260 : : {
5261 [ # # # # : 0 : inc_metric("groomed_total", "decision", "aborted");
# # # # #
# # # # #
# # ]
5262 : 0 : break;
5263 : : }
5264 : :
5265 [ + - ]: 212 : if (interrupted) break;
5266 : :
5267 [ + - ]: 212 : int rc = files.step();
5268 [ + + ]: 212 : if (rc != SQLITE_ROW)
5269 : : break;
5270 : :
5271 [ + - ]: 134 : int64_t mtime = sqlite3_column_int64 (files, 0);
5272 [ + - ]: 134 : int64_t fileid = sqlite3_column_int64 (files, 1);
5273 [ + - - + ]: 134 : const char* filename = ((const char*) sqlite3_column_text (files, 2) ?: "");
5274 : 134 : struct stat s;
5275 : 134 : bool regex_file_drop = 0;
5276 : :
5277 [ + + ]: 134 : if (regex_groom)
5278 : : {
5279 [ + - ]: 16 : bool reg_include = !regexec (&file_include_regex, filename, 0, 0, 0);
5280 [ + - ]: 16 : bool reg_exclude = !regexec (&file_exclude_regex, filename, 0, 0, 0);
5281 : 16 : regex_file_drop = !reg_include || reg_exclude; // match logic of scan_source_paths
5282 : : }
5283 : :
5284 : 134 : rc = stat(filename, &s);
5285 [ + + - + ]: 134 : if ( regex_file_drop || rc < 0 || (mtime != (int64_t) s.st_mtime) )
5286 : : {
5287 [ + - ]: 24 : if (verbose > 2)
5288 [ + - + - : 48 : obatched(clog) << "groom: stale file=" << filename << " mtime=" << mtime << endl;
+ - + - +
- ]
5289 [ + - ]: 24 : stale_fileid_mtime.push_back(make_pair(fileid,mtime));
5290 [ + - + - : 48 : inc_metric("groomed_total", "decision", "stale");
+ - + - -
+ - + - -
- - ]
5291 [ + - + - : 48 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
5292 : : }
5293 : : else
5294 [ + - + - : 220 : inc_metric("groomed_total", "decision", "fresh");
+ - + - -
+ - + - -
- - ]
5295 : :
5296 [ + - ]: 134 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
5297 : : break;
5298 : 134 : }
5299 [ + - ]: 78 : files.reset();
5300 : :
5301 : : // ACTION TIME
5302 : :
5303 : : // Now that we know which file/mtime tuples are stale, actually do
5304 : : // the deletion from the database. Doing this during the SELECT
5305 : : // iteration above results in undefined behaviour in sqlite, as per
5306 : : // https://www.sqlite.org/isolation.html
5307 : :
5308 : : // We could shuffle stale_fileid_mtime[] here. It'd let aborted
5309 : : // sequences of nuke operations resume at random locations, instead
5310 : : // of just starting over. But it doesn't matter much either way,
5311 : : // as long as we make progress.
5312 : :
5313 [ + - + - : 156 : sqlite_ps files_del_f_de (db, "nuke f_de", "delete from " BUILDIDS "_f_de where file = ? and mtime = ?");
+ - + - -
- ]
5314 [ + - + - : 156 : sqlite_ps files_del_r_de (db, "nuke r_de", "delete from " BUILDIDS "_r_de where file = ? and mtime = ?");
+ - + - -
- ]
5315 [ + - ]: 78 : sqlite_ps files_del_scan (db, "nuke f_m_s", "delete from " BUILDIDS "_file_mtime_scanned "
5316 [ + - + - : 156 : "where file = ? and mtime = ?");
+ - + - -
- ]
5317 : :
5318 [ + + ]: 102 : while (! stale_fileid_mtime.empty())
5319 : : {
5320 : 24 : auto stale = stale_fileid_mtime.front();
5321 : 24 : stale_fileid_mtime.pop_front();
5322 [ + - + - : 48 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
5323 : :
5324 : : // PR28514: limit grooming iteration to O(rescan time), to avoid
5325 : : // slow nuke_* queries over many files locking out rescans for too
5326 : : // long. We iterate over the files in random() sequence to avoid
5327 : : // partial checks going over the same set.
5328 [ - + - - ]: 24 : if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
5329 : : {
5330 [ # # # # : 0 : inc_metric("groomed_total", "action", "aborted");
# # # # #
# # # # #
# # ]
5331 : 0 : break;
5332 : : }
5333 : :
5334 [ + - ]: 24 : if (interrupted) break;
5335 : :
5336 : 24 : int64_t fileid = stale.first;
5337 : 24 : int64_t mtime = stale.second;
5338 [ + - + - : 24 : files_del_f_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
5339 [ + - + - : 24 : files_del_r_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
5340 [ + - + - : 24 : files_del_scan.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
5341 [ + - + - : 48 : inc_metric("groomed_total", "action", "cleaned");
+ - + - -
+ - + - -
- - ]
5342 : :
5343 [ + - ]: 24 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
5344 : : break;
5345 : : }
5346 : 78 : stale_fileid_mtime.clear(); // no need for this any longer
5347 [ + - + - : 156 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
5348 : :
5349 : : // delete buildids with no references in _r_de or _f_de tables;
5350 : : // cascades to _r_sref & _f_s records
5351 [ + - ]: 78 : sqlite_ps buildids_del (db, "nuke orphan buildids",
5352 : : "delete from " BUILDIDS "_buildids "
5353 : : "where not exists (select 1 from " BUILDIDS "_f_de d where " BUILDIDS "_buildids.id = d.buildid) "
5354 [ + - + - : 156 : "and not exists (select 1 from " BUILDIDS "_r_de d where " BUILDIDS "_buildids.id = d.buildid)");
+ - + - -
- ]
5355 [ + - + - ]: 78 : buildids_del.reset().step_ok_done();
5356 : :
5357 [ - + ]: 78 : if (interrupted) return;
5358 : :
5359 : : // NB: "vacuum" is too heavy for even daily runs: it rewrites the entire db, so is done as maxigroom -G
5360 [ + - + - : 234 : { sqlite_ps g (db, "incremental vacuum", "pragma incremental_vacuum"); g.reset().step_ok_done(); }
+ - + - +
- + - -
- ]
5361 : : // https://www.sqlite.org/lang_analyze.html#approx
5362 [ + - + - : 234 : { sqlite_ps g (db, "analyze setup", "pragma analysis_limit = 1000;\n"); g.reset().step_ok_done(); }
+ - + - +
- + - -
- ]
5363 [ + - + - : 156 : { sqlite_ps g (db, "analyze", "analyze"); g.reset().step_ok_done(); }
+ - - + +
- + - -
- ]
5364 [ + - + - : 234 : { sqlite_ps g (db, "analyze reload", "analyze sqlite_schema"); g.reset().step_ok_done(); }
+ - + - +
- + - -
- ]
5365 [ + - + - : 156 : { sqlite_ps g (db, "optimize", "pragma optimize"); g.reset().step_ok_done(); }
+ - - + +
- + - -
- ]
5366 [ + - + - : 234 : { sqlite_ps g (db, "wal checkpoint", "pragma wal_checkpoint=truncate"); g.reset().step_ok_done(); }
+ - + - +
- + - -
- ]
5367 : :
5368 [ + - ]: 78 : database_stats_report();
5369 : :
5370 [ + - + - ]: 78 : (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
5371 : :
5372 [ + - ]: 78 : sqlite3_db_release_memory(db); // shrink the process if possible
5373 [ + - ]: 78 : sqlite3_db_release_memory(dbq); // ... for both connections
5374 [ + - ]: 78 : debuginfod_pool_groom(); // and release any debuginfod_client objects we've been holding onto
5375 : : #if HAVE_MALLOC_TRIM
5376 : 78 : malloc_trim(0); // PR31103: release memory allocated for temporary purposes
5377 : : #endif
5378 : :
5379 : : #if 0 /* PR31265: don't jettison cache unnecessarily */
5380 : : fdcache.limit(0); // release the fdcache contents
5381 : : fdcache.limit(fdcache_mbs); // restore status quo parameters
5382 : : #endif
5383 : :
5384 : 78 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
5385 : 78 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
5386 : :
5387 [ + - + - : 156 : obatched(clog) << "groomed database in " << deltas << "s" << endl;
+ - + - ]
5388 : 78 : }
5389 : :
5390 : :
5391 : : static void*
5392 : 78 : thread_main_groom (void* /*arg*/)
5393 : : {
5394 [ + - + - : 156 : set_metric("thread_tid", "role", "groom", tid());
+ - - + -
+ - - -
- ]
5395 [ + - + - : 156 : add_metric("thread_count", "role", "groom", 1);
+ - - + -
+ - - -
- ]
5396 : :
5397 : 78 : time_t last_groom = 0;
5398 : :
5399 : 536 : while (1)
5400 : : {
5401 : 307 : sleep (1);
5402 : 307 : scanq.wait_idle(); // PR25394: block scanners during grooming!
5403 [ + + ]: 307 : if (interrupted) break;
5404 : :
5405 : 229 : time_t now = time(NULL);
5406 : 229 : bool groom_now = false;
5407 [ + + ]: 229 : if (last_groom == 0) // at least one initial groom is documented even for -g0
5408 : 72 : groom_now = true;
5409 [ + + + + ]: 229 : if (groom_s > 0 && (long)now > (long)(last_groom + groom_s))
5410 : 229 : groom_now = true;
5411 [ + + ]: 229 : if (sigusr2 != forced_groom_count)
5412 : : {
5413 : 6 : forced_groom_count = sigusr2;
5414 : 6 : groom_now = true;
5415 : : }
5416 [ + + ]: 229 : if (groom_now)
5417 : : {
5418 [ + - + - : 156 : set_metric("thread_busy", "role", "groom", 1);
+ - - + -
+ - - -
- ]
5419 : 78 : try
5420 : : {
5421 [ + - ]: 78 : groom ();
5422 : : }
5423 [ - - ]: 0 : catch (const sqlite_exception& e)
5424 : : {
5425 [ - - - - : 0 : obatched(cerr) << e.message << endl;
- - ]
5426 : 0 : }
5427 : 78 : last_groom = time(NULL); // NB: now was before grooming
5428 : : // finished a grooming loop
5429 [ + - + - : 156 : inc_metric("thread_work_total", "role", "groom");
+ - - + -
+ - - -
- ]
5430 [ + - + - : 156 : set_metric("thread_busy", "role", "groom", 0);
+ - - + -
+ - - -
- ]
5431 : : }
5432 : :
5433 : 229 : scanq.done_idle();
5434 : 229 : }
5435 : :
5436 : 78 : return 0;
5437 : : }
5438 : :
5439 : :
5440 : : ////////////////////////////////////////////////////////////////////////
5441 : :
5442 : :
5443 : : static void
5444 : 80 : signal_handler (int /* sig */)
5445 : : {
5446 : 80 : interrupted ++;
5447 : :
5448 [ + + ]: 80 : if (db)
5449 : 78 : sqlite3_interrupt (db);
5450 [ + - ]: 80 : if (dbq)
5451 : 80 : sqlite3_interrupt (dbq);
5452 : :
5453 : : // NB: don't do anything else in here
5454 : 80 : }
5455 : :
5456 : : static void
5457 : 58 : sigusr1_handler (int /* sig */)
5458 : : {
5459 : 58 : sigusr1 ++;
5460 : : // NB: don't do anything else in here
5461 : 58 : }
5462 : :
5463 : : static void
5464 : 6 : sigusr2_handler (int /* sig */)
5465 : : {
5466 : 6 : sigusr2 ++;
5467 : : // NB: don't do anything else in here
5468 : 6 : }
5469 : :
5470 : :
5471 : : static void // error logging callback from libmicrohttpd internals
5472 : 0 : error_cb (void *arg, const char *fmt, va_list ap)
5473 : : {
5474 : 0 : (void) arg;
5475 [ # # # # : 0 : inc_metric("error_count","libmicrohttpd",fmt);
# # # # #
# # # #
# ]
5476 : 0 : char errmsg[512];
5477 : 0 : (void) vsnprintf (errmsg, sizeof(errmsg), fmt, ap); // ok if slightly truncated
5478 [ # # ]: 0 : obatched(cerr) << "libmicrohttpd error: " << errmsg; // MHD_DLOG calls already include \n
5479 : 0 : }
5480 : :
5481 : :
5482 : : // A user-defined sqlite function, to score the sharedness of the
5483 : : // prefix of two strings. This is used to compare candidate debuginfo
5484 : : // / source-rpm names, so that the closest match
5485 : : // (directory-topology-wise closest) is found. This is important in
5486 : : // case the same sref (source file name) is in many -debuginfo or
5487 : : // -debugsource RPMs, such as when multiple versions/releases of the
5488 : : // same package are in the database.
5489 : :
5490 : 1320 : static void sqlite3_sharedprefix_fn (sqlite3_context* c, int argc, sqlite3_value** argv)
5491 : : {
5492 [ - + ]: 1320 : if (argc != 2)
5493 : 0 : sqlite3_result_error(c, "expect 2 string arguments", -1);
5494 [ + - + + ]: 2640 : else if ((sqlite3_value_type(argv[0]) != SQLITE_TEXT) ||
5495 : 1320 : (sqlite3_value_type(argv[1]) != SQLITE_TEXT))
5496 : 1058 : sqlite3_result_null(c);
5497 : : else
5498 : : {
5499 : 262 : const unsigned char* a = sqlite3_value_text (argv[0]);
5500 : 262 : const unsigned char* b = sqlite3_value_text (argv[1]);
5501 : 262 : int i = 0;
5502 [ + + + - : 16570 : while (*a != '\0' && *b != '\0' && *a++ == *b++)
+ + + + ]
5503 : 15822 : i++;
5504 : 262 : sqlite3_result_int (c, i);
5505 : : }
5506 : 1320 : }
5507 : :
5508 : :
5509 : : static unsigned
5510 : 156 : default_concurrency() // guaranteed >= 1
5511 : : {
5512 : : // Prior to PR29975 & PR29976, we'd just use this:
5513 : 156 : unsigned sth = std::thread::hardware_concurrency();
5514 : : // ... but on many-CPU boxes, admins or distros may throttle
5515 : : // resources in such a way that debuginfod would mysteriously fail.
5516 : : // So we reduce the defaults:
5517 : :
5518 : 156 : unsigned aff = 0;
5519 : : #ifdef HAVE_SCHED_GETAFFINITY
5520 : 156 : {
5521 : 156 : int ret;
5522 : 156 : cpu_set_t mask;
5523 : 156 : CPU_ZERO(&mask);
5524 : 156 : ret = sched_getaffinity(0, sizeof(mask), &mask);
5525 [ + - ]: 156 : if (ret == 0)
5526 : 156 : aff = CPU_COUNT(&mask);
5527 : : }
5528 : : #endif
5529 : :
5530 : 156 : unsigned fn = 0;
5531 : : #ifdef HAVE_GETRLIMIT
5532 : 156 : {
5533 : 156 : struct rlimit rlim;
5534 : 156 : int rc = getrlimit(RLIMIT_NOFILE, &rlim);
5535 [ + - ]: 156 : if (rc == 0)
5536 [ + - ]: 312 : fn = max((rlim_t)1, (rlim.rlim_cur - 100) / 4);
5537 : : // at least 2 fds are used by each listener thread etc.
5538 : : // plus a bunch to account for shared libraries and such
5539 : : }
5540 : : #endif
5541 : :
5542 [ - + - + : 156 : unsigned d = min(max(sth, 1U),
- + ]
5543 [ - + ]: 156 : min(max(aff, 1U),
5544 [ - + ]: 156 : max(fn, 1U)));
5545 : 156 : return d;
5546 : : }
5547 : :
5548 : :
5549 : : // 30879: Something to help out in case of an uncaught exception.
5550 : 0 : void my_terminate_handler()
5551 : : {
5552 : : #if defined(__GLIBC__)
5553 : 0 : void *array[40];
5554 : 0 : int size = backtrace (array, 40);
5555 : 0 : backtrace_symbols_fd (array, size, STDERR_FILENO);
5556 : : #endif
5557 : : #if defined(__GLIBCXX__) || defined(__GLIBCPP__)
5558 : 0 : __gnu_cxx::__verbose_terminate_handler();
5559 : : #endif
5560 : 0 : abort();
5561 : : }
5562 : :
5563 : :
5564 : : int
5565 : 80 : main (int argc, char *argv[])
5566 : : {
5567 : 80 : (void) setlocale (LC_ALL, "");
5568 : 80 : (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
5569 : 80 : (void) textdomain (PACKAGE_TARNAME);
5570 : :
5571 : 80 : std::set_terminate(& my_terminate_handler);
5572 : :
5573 : : /* Tell the library which version we are expecting. */
5574 : 80 : elf_version (EV_CURRENT);
5575 : :
5576 [ + - - + ]: 160 : tmpdir = string(getenv("TMPDIR") ?: "/tmp");
5577 : :
5578 : : /* Set computed default values. */
5579 [ - + + - : 80 : db_path = string(getenv("HOME") ?: "/") + string("/.debuginfod.sqlite"); /* XDG? */
+ - - + -
+ + - -
- ]
5580 : 80 : int rc = regcomp (& file_include_regex, ".*", REG_EXTENDED|REG_NOSUB); // match everything
5581 [ - + ]: 80 : if (rc != 0)
5582 : 0 : error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
5583 : 80 : rc = regcomp (& file_exclude_regex, "^$", REG_EXTENDED|REG_NOSUB); // match nothing
5584 [ - + ]: 80 : if (rc != 0)
5585 : 0 : error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
5586 : :
5587 : : // default parameters for fdcache are computed from system stats
5588 : 80 : struct statfs sfs;
5589 : 80 : rc = statfs(tmpdir.c_str(), &sfs);
5590 [ - + ]: 80 : if (rc < 0)
5591 : 0 : fdcache_mbs = 1024; // 1 gigabyte
5592 : : else
5593 : 80 : fdcache_mbs = sfs.f_bavail * sfs.f_bsize / 1024 / 1024 / 4; // 25% of free space
5594 : 80 : fdcache_mintmp = 25; // emergency flush at 25% remaining (75% full)
5595 : 80 : fdcache_prefetch = 64; // guesstimate storage is this much less costly than re-decompression
5596 : :
5597 : : /* Parse and process arguments. */
5598 : 80 : int remaining;
5599 : 80 : (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
5600 [ - + ]: 80 : if (remaining != argc)
5601 : 0 : error (EXIT_FAILURE, 0,
5602 : 0 : "unexpected argument: %s", argv[remaining]);
5603 : :
5604 [ + + + + : 80 : if (scan_archives.size()==0 && !scan_files && source_paths.size()>0)
- + ]
5605 [ # # ]: 0 : obatched(clog) << "warning: without -F -R -U -Z, ignoring PATHs" << endl;
5606 : :
5607 : 80 : fdcache.limit(fdcache_mbs);
5608 : :
5609 : 80 : (void) signal (SIGPIPE, SIG_IGN); // microhttpd can generate it incidentally, ignore
5610 : 80 : (void) signal (SIGINT, signal_handler); // ^C
5611 : 80 : (void) signal (SIGHUP, signal_handler); // EOF
5612 : 80 : (void) signal (SIGTERM, signal_handler); // systemd
5613 : 80 : (void) signal (SIGUSR1, sigusr1_handler); // end-user
5614 : 80 : (void) signal (SIGUSR2, sigusr2_handler); // end-user
5615 : :
5616 : : /* Get database ready. */
5617 [ + + ]: 80 : if (! passive_p)
5618 : : {
5619 : 78 : rc = sqlite3_open_v2 (db_path.c_str(), &db, (SQLITE_OPEN_READWRITE
5620 : : |SQLITE_OPEN_URI
5621 : : |SQLITE_OPEN_PRIVATECACHE
5622 : : |SQLITE_OPEN_CREATE
5623 : : |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
5624 : : NULL);
5625 [ - + ]: 78 : if (rc == SQLITE_CORRUPT)
5626 : : {
5627 : 0 : (void) unlink (db_path.c_str());
5628 : 0 : error (EXIT_FAILURE, 0,
5629 : : "cannot open %s, deleted database: %s", db_path.c_str(), sqlite3_errmsg(db));
5630 : : }
5631 [ - + ]: 78 : else if (rc)
5632 : : {
5633 : 0 : error (EXIT_FAILURE, 0,
5634 : : "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(db));
5635 : : }
5636 : : }
5637 : :
5638 : : // open the readonly query variant
5639 : : // NB: PRIVATECACHE allows web queries to operate in parallel with
5640 : : // much other grooming/scanning operation.
5641 : 80 : rc = sqlite3_open_v2 (db_path.c_str(), &dbq, (SQLITE_OPEN_READONLY
5642 : : |SQLITE_OPEN_URI
5643 : : |SQLITE_OPEN_PRIVATECACHE
5644 : : |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
5645 : : NULL);
5646 [ - + ]: 80 : if (rc)
5647 : : {
5648 : 0 : error (EXIT_FAILURE, 0,
5649 : : "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(dbq));
5650 : : }
5651 : :
5652 : :
5653 [ + - ]: 160 : obatched(clog) << "opened database " << db_path
5654 [ + + + - : 82 : << (db?" rw":"") << (dbq?" ro":"") << endl;
- + + - +
- ]
5655 [ + - + - ]: 160 : obatched(clog) << "sqlite version " << sqlite3_version << endl;
5656 [ + + + - : 238 : obatched(clog) << "service mode " << (passive_p ? "passive":"active") << endl;
+ - ]
5657 : :
5658 : : // add special string-prefix-similarity function used in rpm sref/sdef resolution
5659 : 80 : rc = sqlite3_create_function(dbq, "sharedprefix", 2, SQLITE_UTF8, NULL,
5660 : : & sqlite3_sharedprefix_fn, NULL, NULL);
5661 [ - + ]: 80 : if (rc != SQLITE_OK)
5662 : 0 : error (EXIT_FAILURE, 0,
5663 : : "cannot create sharedprefix function: %s", sqlite3_errmsg(dbq));
5664 : :
5665 [ + + ]: 80 : if (! passive_p)
5666 : : {
5667 [ + + ]: 78 : if (verbose > 3)
5668 [ + - + - ]: 92 : obatched(clog) << "ddl: " << DEBUGINFOD_SQLITE_DDL << endl;
5669 : 78 : rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_DDL, NULL, NULL, NULL);
5670 [ - + ]: 78 : if (rc != SQLITE_OK)
5671 : : {
5672 : 0 : error (EXIT_FAILURE, 0,
5673 : : "cannot run database schema ddl: %s", sqlite3_errmsg(db));
5674 : : }
5675 : : }
5676 : :
5677 [ + - + - : 160 : obatched(clog) << "libmicrohttpd version " << MHD_get_version() << endl;
+ - ]
5678 : :
5679 : : /* If '-C' wasn't given or was given with no arg, pick a reasonable default
5680 : : for the number of worker threads. */
5681 [ + + ]: 80 : if (connection_pool == 0)
5682 : 76 : connection_pool = default_concurrency();
5683 : :
5684 : : /* Note that MHD_USE_EPOLL and MHD_USE_THREAD_PER_CONNECTION don't
5685 : : work together. */
5686 : 80 : unsigned int use_epoll = 0;
5687 : : #if MHD_VERSION >= 0x00095100
5688 : 80 : use_epoll = MHD_USE_EPOLL;
5689 : : #endif
5690 : :
5691 : 80 : unsigned int mhd_flags = (
5692 : : #if MHD_VERSION >= 0x00095300
5693 : : MHD_USE_INTERNAL_POLLING_THREAD
5694 : : #else
5695 : : MHD_USE_SELECT_INTERNALLY
5696 : : #endif
5697 : : | MHD_USE_DUAL_STACK
5698 : : | use_epoll
5699 : : #if MHD_VERSION >= 0x00095200
5700 : : | MHD_USE_ITC
5701 : : #endif
5702 : : | MHD_USE_DEBUG); /* report errors to stderr */
5703 : :
5704 : : // Start httpd server threads. Use a single dual-homed pool.
5705 : 80 : MHD_Daemon *d46 = MHD_start_daemon (mhd_flags, http_port,
5706 : : NULL, NULL, /* default accept policy */
5707 : : handler_cb, NULL, /* handler callback */
5708 : : MHD_OPTION_EXTERNAL_LOGGER,
5709 : : error_cb, NULL,
5710 : : MHD_OPTION_THREAD_POOL_SIZE,
5711 : : (int)connection_pool,
5712 : : MHD_OPTION_END);
5713 : :
5714 : 80 : MHD_Daemon *d4 = NULL;
5715 [ - + ]: 80 : if (d46 == NULL)
5716 : : {
5717 : : // Cannot use dual_stack, use ipv4 only
5718 : 0 : mhd_flags &= ~(MHD_USE_DUAL_STACK);
5719 [ # # ]: 0 : d4 = MHD_start_daemon (mhd_flags, http_port,
5720 : : NULL, NULL, /* default accept policy */
5721 : : handler_cb, NULL, /* handler callback */
5722 : : MHD_OPTION_EXTERNAL_LOGGER,
5723 : : error_cb, NULL,
5724 : : (connection_pool
5725 : : ? MHD_OPTION_THREAD_POOL_SIZE
5726 : : : MHD_OPTION_END),
5727 : : (connection_pool
5728 : : ? (int)connection_pool
5729 : : : MHD_OPTION_END),
5730 : : MHD_OPTION_END);
5731 [ # # ]: 0 : if (d4 == NULL)
5732 : : {
5733 : 0 : sqlite3 *database = db;
5734 : 0 : sqlite3 *databaseq = dbq;
5735 : 0 : db = dbq = 0; // for signal_handler not to freak
5736 : 0 : sqlite3_close (databaseq);
5737 : 0 : sqlite3_close (database);
5738 : 0 : error (EXIT_FAILURE, 0, "cannot start http server at port %d",
5739 : : http_port);
5740 : : }
5741 : :
5742 : : }
5743 : 80 : obatched(clog) << "started http server on"
5744 : : << (d4 != NULL ? " IPv4 " : " IPv4 IPv6 ")
5745 [ + - + - : 160 : << "port=" << http_port
+ - ]
5746 [ + - + + : 154 : << (webapi_cors ? " with cors" : "")
+ - + - ]
5747 : 80 : << endl;
5748 : :
5749 : : // add maxigroom sql if -G given
5750 [ - + ]: 80 : if (maxigroom)
5751 : : {
5752 [ # # ]: 0 : obatched(clog) << "maxigrooming database, please wait." << endl;
5753 : : // NB: this index alone can nearly double the database size!
5754 : : // NB: this index would be necessary to run source-file metadata searches fast
5755 [ # # ]: 0 : extra_ddl.push_back("create index if not exists " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);");
5756 [ # # ]: 0 : extra_ddl.push_back("delete from " BUILDIDS "_r_sdef where not exists (select 1 from " BUILDIDS "_r_sref b where " BUILDIDS "_r_sdef.content = b.artifactsrc);");
5757 [ # # ]: 0 : extra_ddl.push_back("drop index if exists " BUILDIDS "_r_sref_arc;");
5758 : :
5759 : : // NB: we don't maxigroom the _files interning table. It'd require a temp index on all the
5760 : : // tables that have file foreign-keys, which is a lot.
5761 : :
5762 : : // NB: with =delete, may take up 3x disk space total during vacuum process
5763 : : // vs. =off (only 2x but may corrupt database if program dies mid-vacuum)
5764 : : // vs. =wal (>3x observed, but safe)
5765 [ # # ]: 0 : extra_ddl.push_back("pragma journal_mode=delete;");
5766 [ # # ]: 0 : extra_ddl.push_back("vacuum;");
5767 [ # # ]: 0 : extra_ddl.push_back("pragma journal_mode=wal;");
5768 : : }
5769 : :
5770 : : // run extra -D sql if given
5771 [ + + ]: 80 : if (! passive_p)
5772 [ - + ]: 78 : for (auto&& i: extra_ddl)
5773 : : {
5774 [ # # ]: 0 : if (verbose > 1)
5775 [ # # # # ]: 0 : obatched(clog) << "extra ddl:\n" << i << endl;
5776 : 0 : rc = sqlite3_exec (db, i.c_str(), NULL, NULL, NULL);
5777 [ # # # # ]: 0 : if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
5778 : 0 : error (0, 0,
5779 : : "warning: cannot run database extra ddl %s: %s", i.c_str(), sqlite3_errmsg(db));
5780 : :
5781 [ # # ]: 0 : if (maxigroom)
5782 [ # # ]: 0 : obatched(clog) << "maxigroomed database" << endl;
5783 : : }
5784 : :
5785 [ + + ]: 80 : if (! passive_p)
5786 [ + - + - ]: 156 : obatched(clog) << "search concurrency " << concurrency << endl;
5787 : 80 : obatched(clog) << "webapi connection pool " << connection_pool
5788 [ + - - + : 80 : << (connection_pool ? "" : " (unlimited)") << endl;
+ - + - ]
5789 [ + + ]: 80 : if (! passive_p) {
5790 [ + - + - ]: 156 : obatched(clog) << "rescan time " << rescan_s << endl;
5791 [ + - + - ]: 156 : obatched(clog) << "scan checkpoint " << scan_checkpoint << endl;
5792 : : }
5793 [ + - + - ]: 160 : obatched(clog) << "fdcache mbs " << fdcache_mbs << endl;
5794 [ + - + - ]: 160 : obatched(clog) << "fdcache prefetch " << fdcache_prefetch << endl;
5795 [ + - + - ]: 160 : obatched(clog) << "fdcache tmpdir " << tmpdir << endl;
5796 [ + - + - ]: 160 : obatched(clog) << "fdcache tmpdir min% " << fdcache_mintmp << endl;
5797 [ + + ]: 80 : if (! passive_p)
5798 [ + - + - ]: 156 : obatched(clog) << "groom time " << groom_s << endl;
5799 [ + - + - ]: 160 : obatched(clog) << "forwarded ttl limit " << forwarded_ttl_limit << endl;
5800 : :
5801 [ + + ]: 80 : if (scan_archives.size()>0)
5802 : : {
5803 : 56 : obatched ob(clog);
5804 [ + - ]: 56 : auto& o = ob << "accepting archive types ";
5805 [ + + ]: 174 : for (auto&& arch : scan_archives)
5806 [ + - + - : 118 : o << arch.first << "(" << arch.second << ") ";
+ - + - ]
5807 [ + - ]: 56 : o << endl;
5808 : 56 : }
5809 : 80 : const char* du = getenv(DEBUGINFOD_URLS_ENV_VAR);
5810 [ + + + + ]: 80 : if (du && du[0] != '\0') // set to non-empty string?
5811 [ + - + - ]: 32 : obatched(clog) << "upstream debuginfod servers: " << du << endl;
5812 : :
5813 [ + + ]: 80 : vector<pthread_t> all_threads;
5814 : :
5815 [ + + ]: 80 : if (! passive_p)
5816 : : {
5817 : 78 : pthread_t pt;
5818 : 78 : rc = pthread_create (& pt, NULL, thread_main_groom, NULL);
5819 [ - + ]: 78 : if (rc)
5820 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to groom database\n");
5821 : : else
5822 : : {
5823 : : #ifdef HAVE_PTHREAD_SETNAME_NP
5824 : 78 : (void) pthread_setname_np (pt, "groom");
5825 : : #endif
5826 [ + - ]: 78 : all_threads.push_back(pt);
5827 : : }
5828 : :
5829 [ + + + + ]: 78 : if (scan_files || scan_archives.size() > 0)
5830 : : {
5831 [ + - ]: 72 : if (scan_checkpoint > 0)
5832 [ + - ]: 72 : scan_barrier = new sqlite_checkpoint_pb(concurrency, (unsigned) scan_checkpoint);
5833 : :
5834 : 72 : rc = pthread_create (& pt, NULL, thread_main_fts_source_paths, NULL);
5835 [ - + ]: 72 : if (rc)
5836 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to traverse source paths\n");
5837 : : #ifdef HAVE_PTHREAD_SETNAME_NP
5838 : 72 : (void) pthread_setname_np (pt, "traverse");
5839 : : #endif
5840 [ + - ]: 72 : all_threads.push_back(pt);
5841 : :
5842 [ + + ]: 360 : for (unsigned i=0; i<concurrency; i++)
5843 : : {
5844 : 288 : rc = pthread_create (& pt, NULL, thread_main_scanner, NULL);
5845 [ - + ]: 288 : if (rc)
5846 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to scan source files / archives\n");
5847 : : #ifdef HAVE_PTHREAD_SETNAME_NP
5848 : 288 : (void) pthread_setname_np (pt, "scan");
5849 : : #endif
5850 [ + - ]: 288 : all_threads.push_back(pt);
5851 : : }
5852 : : }
5853 : : }
5854 : :
5855 : : /* Trivial main loop! */
5856 [ + - + - ]: 80 : set_metric("ready", 1);
5857 [ + + ]: 224 : while (! interrupted)
5858 [ + - ]: 144 : pause ();
5859 [ + - ]: 80 : scanq.nuke(); // wake up any remaining scanq-related threads, let them die
5860 [ + + + - ]: 80 : if (scan_barrier) scan_barrier->nuke(); // ... in case they're stuck in a barrier
5861 [ + - + - ]: 80 : set_metric("ready", 0);
5862 : :
5863 [ + - ]: 80 : if (verbose)
5864 [ + - + - : 160 : obatched(clog) << "stopping" << endl;
- - ]
5865 : :
5866 : : /* Join all our threads. */
5867 [ + + ]: 518 : for (auto&& it : all_threads)
5868 [ + - ]: 438 : pthread_join (it, NULL);
5869 : :
5870 : : /* Stop all the web service threads. */
5871 [ + - + - ]: 80 : if (d46) MHD_stop_daemon (d46);
5872 [ - + - - ]: 80 : if (d4) MHD_stop_daemon (d4);
5873 : :
5874 [ + + ]: 80 : if (! passive_p)
5875 : : {
5876 : : /* With all threads known dead, we can clean up the global resources. */
5877 [ + - ]: 78 : rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_CLEANUP_DDL, NULL, NULL, NULL);
5878 [ - + ]: 78 : if (rc != SQLITE_OK)
5879 : : {
5880 [ # # # # ]: 0 : error (0, 0,
5881 : : "warning: cannot run database cleanup ddl: %s", sqlite3_errmsg(db));
5882 : : }
5883 : : }
5884 : :
5885 [ + - ]: 80 : debuginfod_pool_groom ();
5886 [ + + ]: 80 : delete scan_barrier;
5887 : :
5888 : : // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
5889 [ + - ]: 80 : (void) regfree (& file_include_regex);
5890 [ + - ]: 80 : (void) regfree (& file_exclude_regex);
5891 : :
5892 : 80 : sqlite3 *database = db;
5893 : 80 : sqlite3 *databaseq = dbq;
5894 : 80 : db = dbq = 0; // for signal_handler not to freak
5895 [ + - ]: 80 : (void) sqlite3_close (databaseq);
5896 [ + + ]: 80 : if (! passive_p)
5897 [ + - ]: 78 : (void) sqlite3_close (database);
5898 : :
5899 [ + + ]: 80 : return 0;
5900 : 80 : }
|