LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Hit Total Coverage
Test: elfutils-0.189 Lines: 1889 2234 84.6 %
Date: 2023-08-29 13:46:25 Functions: 88 96 91.7 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 2498 5804 43.0 %

           Branch data     Line data    Source code
       1                 :            : /* Debuginfo-over-http server.
       2                 :            :    Copyright (C) 2019-2021 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                 :            : extern "C" {
      48                 :            : #include "printversion.h"
      49                 :            : #include "system.h"
      50                 :            : }
      51                 :            : 
      52                 :            : #include "debuginfod.h"
      53                 :            : #include <dwarf.h>
      54                 :            : 
      55                 :            : #include <argp.h>
      56                 :            : #ifdef __GNUC__
      57                 :            : #undef __attribute__ /* glibc bug - rhbz 1763325 */
      58                 :            : #endif
      59                 :            : 
      60                 :            : #include <unistd.h>
      61                 :            : #include <stdlib.h>
      62                 :            : #include <locale.h>
      63                 :            : #include <pthread.h>
      64                 :            : #include <signal.h>
      65                 :            : #include <sys/stat.h>
      66                 :            : #include <sys/time.h>
      67                 :            : #include <sys/vfs.h>
      68                 :            : #include <unistd.h>
      69                 :            : #include <fcntl.h>
      70                 :            : #include <netdb.h>
      71                 :            : 
      72                 :            : 
      73                 :            : /* If fts.h is included before config.h, its indirect inclusions may not
      74                 :            :    give us the right LFS aliases of these functions, so map them manually.  */
      75                 :            : #ifdef BAD_FTS
      76                 :            :   #ifdef _FILE_OFFSET_BITS
      77                 :            :     #define open open64
      78                 :            :     #define fopen fopen64
      79                 :            :   #endif
      80                 :            : #else
      81                 :            :   #include <sys/types.h>
      82                 :            :   #include <fts.h>
      83                 :            : #endif
      84                 :            : 
      85                 :            : #include <cstring>
      86                 :            : #include <vector>
      87                 :            : #include <set>
      88                 :            : #include <unordered_set>
      89                 :            : #include <map>
      90                 :            : #include <string>
      91                 :            : #include <iostream>
      92                 :            : #include <iomanip>
      93                 :            : #include <ostream>
      94                 :            : #include <sstream>
      95                 :            : #include <mutex>
      96                 :            : #include <deque>
      97                 :            : #include <condition_variable>
      98                 :            : #include <thread>
      99                 :            : // #include <regex> // on rhel7 gcc 4.8, not competent
     100                 :            : #include <regex.h>
     101                 :            : // #include <algorithm>
     102                 :            : using namespace std;
     103                 :            : 
     104                 :            : #include <gelf.h>
     105                 :            : #include <libdwelf.h>
     106                 :            : 
     107                 :            : #include <microhttpd.h>
     108                 :            : 
     109                 :            : #if MHD_VERSION >= 0x00097002
     110                 :            : // libmicrohttpd 0.9.71 broke API
     111                 :            : #define MHD_RESULT enum MHD_Result
     112                 :            : #else
     113                 :            : #define MHD_RESULT int
     114                 :            : #endif
     115                 :            : 
     116                 :            : #include <curl/curl.h>
     117                 :            : #include <archive.h>
     118                 :            : #include <archive_entry.h>
     119                 :            : #include <sqlite3.h>
     120                 :            : 
     121                 :            : #ifdef __linux__
     122                 :            : #include <sys/syscall.h>
     123                 :            : #endif
     124                 :            : 
     125                 :            : #ifdef __linux__
     126                 :            : #define tid() syscall(SYS_gettid)
     127                 :            : #else
     128                 :            : #define tid() pthread_self()
     129                 :            : #endif
     130                 :            : 
     131                 :            : 
     132                 :            : inline bool
     133                 :       1517 : string_endswith(const string& haystack, const string& needle)
     134                 :            : {
     135         [ +  - ]:       1517 :   return (haystack.size() >= needle.size() &&
     136                 :       1517 :           equal(haystack.end()-needle.size(), haystack.end(),
     137                 :       1517 :                 needle.begin()));
     138                 :            : }
     139                 :            : 
     140                 :            : 
     141                 :            : // Roll this identifier for every sqlite schema incompatibility.
     142                 :            : #define BUILDIDS "buildids10"
     143                 :            : 
     144                 :            : #if SQLITE_VERSION_NUMBER >= 3008000
     145                 :            : #define WITHOUT_ROWID "without rowid"
     146                 :            : #else
     147                 :            : #define WITHOUT_ROWID ""
     148                 :            : #endif
     149                 :            : 
     150                 :            : static const char DEBUGINFOD_SQLITE_DDL[] =
     151                 :            :   "pragma foreign_keys = on;\n"
     152                 :            :   "pragma synchronous = 0;\n" // disable fsync()s - this cache is disposable across a machine crash
     153                 :            :   "pragma journal_mode = wal;\n" // https://sqlite.org/wal.html
     154                 :            :   "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
     155                 :            :   "pragma journal_size_limit = 0;\n" // limit steady state file (between grooming, which also =truncate's)
     156                 :            :   "pragma auto_vacuum = incremental;\n" // https://sqlite.org/pragma.html
     157                 :            :   "pragma busy_timeout = 1000;\n" // https://sqlite.org/pragma.html
     158                 :            :   // NB: all these are overridable with -D option
     159                 :            : 
     160                 :            :   // Normalization table for interning file names
     161                 :            :   "create table if not exists " BUILDIDS "_fileparts (\n"
     162                 :            :   "        id integer primary key not null,\n"
     163                 :            :   "        name text unique not null\n"
     164                 :            :   "        );\n"
     165                 :            :   "create table if not exists " BUILDIDS "_files (\n"
     166                 :            :   "        id integer primary key not null,\n"
     167                 :            :   "        dirname integer not null,\n"
     168                 :            :   "        basename integer not null,\n"
     169                 :            :   "        unique (dirname, basename),\n"
     170                 :            :   "        foreign key (dirname) references " BUILDIDS "_fileparts(id) on delete cascade,\n"
     171                 :            :   "        foreign key (basename) references " BUILDIDS "_fileparts(id) on delete cascade\n"
     172                 :            :   "        );\n"
     173                 :            :   "create view if not exists " BUILDIDS "_files_v as\n" // a 
     174                 :            :   "        select f.id, n1.name || '/' || n2.name as name\n"
     175                 :            :   "        from " BUILDIDS "_files f, " BUILDIDS "_fileparts n1, " BUILDIDS "_fileparts n2\n"
     176                 :            :   "        where f.dirname = n1.id and f.basename = n2.id;\n"
     177                 :            :   
     178                 :            :   // Normalization table for interning buildids
     179                 :            :   "create table if not exists " BUILDIDS "_buildids (\n"
     180                 :            :   "        id integer primary key not null,\n"
     181                 :            :   "        hex text unique not null);\n"
     182                 :            :   // Track the completion of scanning of a given file & sourcetype at given time
     183                 :            :   "create table if not exists " BUILDIDS "_file_mtime_scanned (\n"
     184                 :            :   "        mtime integer not null,\n"
     185                 :            :   "        file integer not null,\n"
     186                 :            :   "        size integer not null,\n" // in bytes
     187                 :            :   "        sourcetype text(1) not null\n"
     188                 :            :   "            check (sourcetype IN ('F', 'R')),\n"
     189                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     190                 :            :   "        primary key (file, mtime, sourcetype)\n"
     191                 :            :   "        ) " WITHOUT_ROWID ";\n"
     192                 :            :   "create table if not exists " BUILDIDS "_f_de (\n"
     193                 :            :   "        buildid integer not null,\n"
     194                 :            :   "        debuginfo_p integer not null,\n"
     195                 :            :   "        executable_p integer not null,\n"
     196                 :            :   "        file integer not null,\n"
     197                 :            :   "        mtime integer not null,\n"
     198                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     199                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     200                 :            :   "        primary key (buildid, file, mtime)\n"
     201                 :            :   "        ) " WITHOUT_ROWID ";\n"
     202                 :            :   // Index for faster delete by file identifier
     203                 :            :   "create index if not exists " BUILDIDS "_f_de_idx on " BUILDIDS "_f_de (file, mtime);\n"
     204                 :            :   "create table if not exists " BUILDIDS "_f_s (\n"
     205                 :            :   "        buildid integer not null,\n"
     206                 :            :   "        artifactsrc integer not null,\n"
     207                 :            :   "        file integer not null,\n" // NB: not necessarily entered into _mtime_scanned
     208                 :            :   "        mtime integer not null,\n"
     209                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     210                 :            :   "        foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     211                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     212                 :            :   "        primary key (buildid, artifactsrc, file, mtime)\n"
     213                 :            :   "        ) " WITHOUT_ROWID ";\n"
     214                 :            :   "create table if not exists " BUILDIDS "_r_de (\n"
     215                 :            :   "        buildid integer not null,\n"
     216                 :            :   "        debuginfo_p integer not null,\n"
     217                 :            :   "        executable_p integer not null,\n"
     218                 :            :   "        file integer not null,\n"
     219                 :            :   "        mtime integer not null,\n"
     220                 :            :   "        content integer not null,\n"
     221                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     222                 :            :   "        foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     223                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     224                 :            :   "        primary key (buildid, debuginfo_p, executable_p, file, content, mtime)\n"
     225                 :            :   "        ) " WITHOUT_ROWID ";\n"
     226                 :            :   // Index for faster delete by archive file identifier
     227                 :            :   "create index if not exists " BUILDIDS "_r_de_idx on " BUILDIDS "_r_de (file, mtime);\n"
     228                 :            :   "create table if not exists " BUILDIDS "_r_sref (\n" // outgoing dwarf sourcefile references from rpm
     229                 :            :   "        buildid integer not null,\n"
     230                 :            :   "        artifactsrc integer not null,\n"
     231                 :            :   "        foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     232                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     233                 :            :   "        primary key (buildid, artifactsrc)\n"
     234                 :            :   "        ) " WITHOUT_ROWID ";\n"
     235                 :            :   "create table if not exists " BUILDIDS "_r_sdef (\n" // rpm contents that may satisfy sref
     236                 :            :   "        file integer not null,\n"
     237                 :            :   "        mtime integer not null,\n"
     238                 :            :   "        content integer not null,\n"
     239                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     240                 :            :   "        foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     241                 :            :   "        primary key (content, file, mtime)\n"
     242                 :            :   "        ) " WITHOUT_ROWID ";\n"
     243                 :            :   // create views to glue together some of the above tables, for webapi D queries
     244                 :            :   "create view if not exists " BUILDIDS "_query_d as \n"
     245                 :            :   "select\n"
     246                 :            :   "        b.hex as buildid, n.mtime, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1\n"
     247                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
     248                 :            :   "        where b.id = n.buildid and f0.id = n.file and n.debuginfo_p = 1\n"
     249                 :            :   "union all select\n"
     250                 :            :   "        b.hex as buildid, n.mtime, 'R' as sourcetype, f0.name as source0, n.mtime as mtime, f1.name as source1\n"
     251                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
     252                 :            :   "        where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.debuginfo_p = 1\n"
     253                 :            :   ";"
     254                 :            :   // ... and for E queries
     255                 :            :   "create view if not exists " BUILDIDS "_query_e as \n"
     256                 :            :   "select\n"
     257                 :            :   "        b.hex as buildid, n.mtime, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1\n"
     258                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
     259                 :            :   "        where b.id = n.buildid and f0.id = n.file and n.executable_p = 1\n"
     260                 :            :   "union all select\n"
     261                 :            :   "        b.hex as buildid, n.mtime, 'R' as sourcetype, f0.name as source0, n.mtime as mtime, f1.name as source1\n"
     262                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
     263                 :            :   "        where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.executable_p = 1\n"
     264                 :            :   ";"
     265                 :            :   // ... and for S queries
     266                 :            :   "create view if not exists " BUILDIDS "_query_s as \n"
     267                 :            :   "select\n"
     268                 :            :   "        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"
     269                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v fs, " BUILDIDS "_f_s n\n"
     270                 :            :   "        where b.id = n.buildid and f0.id = n.file and fs.id = n.artifactsrc\n"
     271                 :            :   "union all select\n"
     272                 :            :   "        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"
     273                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_files_v fsref, "
     274                 :            :   "        " BUILDIDS "_r_sdef sd, " BUILDIDS "_r_sref sr, " BUILDIDS "_r_de sde\n"
     275                 :            :   "        where b.id = sr.buildid and f0.id = sd.file and fsref.id = sde.file and f1.id = sd.content\n"
     276                 :            :   "        and sr.artifactsrc = sd.content and sde.buildid = sr.buildid\n"
     277                 :            :   ";"
     278                 :            :   // and for startup overview counts
     279                 :            :   "drop view if exists " BUILDIDS "_stats;\n"
     280                 :            :   "create view if not exists " BUILDIDS "_stats as\n"
     281                 :            :   "          select 'file d/e' as label,count(*) as quantity from " BUILDIDS "_f_de\n"
     282                 :            :   "union all select 'file s',count(*) from " BUILDIDS "_f_s\n"
     283                 :            :   "union all select 'archive d/e',count(*) from " BUILDIDS "_r_de\n"
     284                 :            :   "union all select 'archive sref',count(*) from " BUILDIDS "_r_sref\n"
     285                 :            :   "union all select 'archive sdef',count(*) from " BUILDIDS "_r_sdef\n"
     286                 :            :   "union all select 'buildids',count(*) from " BUILDIDS "_buildids\n"
     287                 :            :   "union all select 'filenames',count(*) from " BUILDIDS "_files\n"
     288                 :            :   "union all select 'fileparts',count(*) from " BUILDIDS "_fileparts\n"  
     289                 :            :   "union all select 'files scanned (#)',count(*) from " BUILDIDS "_file_mtime_scanned\n"
     290                 :            :   "union all select 'files scanned (mb)',coalesce(sum(size)/1024/1024,0) from " BUILDIDS "_file_mtime_scanned\n"
     291                 :            : #if SQLITE_VERSION_NUMBER >= 3016000
     292                 :            :   "union all select 'index db size (mb)',page_count*page_size/1024/1024 as size FROM pragma_page_count(), pragma_page_size()\n"
     293                 :            : #endif
     294                 :            :   ";\n"
     295                 :            : 
     296                 :            : // schema change history & garbage collection
     297                 :            : //
     298                 :            : // XXX: we could have migration queries here to bring prior-schema
     299                 :            : // data over instead of just dropping it.  But that could incur
     300                 :            : // doubled storage costs.
     301                 :            : //
     302                 :            : // buildids10: split the _files table into _parts
     303                 :            :   "" // <<< we are here
     304                 :            : // buildids9: widen the mtime_scanned table
     305                 :            :   "DROP VIEW IF EXISTS buildids9_stats;\n"
     306                 :            :   "DROP INDEX IF EXISTS buildids9_r_de_idx;\n"
     307                 :            :   "DROP INDEX IF EXISTS buildids9_f_de_idx;\n"
     308                 :            :   "DROP VIEW IF EXISTS buildids9_query_s;\n"
     309                 :            :   "DROP VIEW IF EXISTS buildids9_query_e;\n"
     310                 :            :   "DROP VIEW IF EXISTS buildids9_query_d;\n"
     311                 :            :   "DROP TABLE IF EXISTS buildids9_r_sdef;\n"
     312                 :            :   "DROP TABLE IF EXISTS buildids9_r_sref;\n"
     313                 :            :   "DROP TABLE IF EXISTS buildids9_r_de;\n"
     314                 :            :   "DROP TABLE IF EXISTS buildids9_f_s;\n"
     315                 :            :   "DROP TABLE IF EXISTS buildids9_f_de;\n"
     316                 :            :   "DROP TABLE IF EXISTS buildids9_file_mtime_scanned;\n"
     317                 :            :   "DROP TABLE IF EXISTS buildids9_buildids;\n"
     318                 :            :   "DROP TABLE IF EXISTS buildids9_files;\n"
     319                 :            : // buildids8: slim the sref table
     320                 :            :   "drop table if exists buildids8_f_de;\n"
     321                 :            :   "drop table if exists buildids8_f_s;\n"
     322                 :            :   "drop table if exists buildids8_r_de;\n"
     323                 :            :   "drop table if exists buildids8_r_sref;\n"
     324                 :            :   "drop table if exists buildids8_r_sdef;\n"
     325                 :            :   "drop table if exists buildids8_file_mtime_scanned;\n"
     326                 :            :   "drop table if exists buildids8_files;\n"
     327                 :            :   "drop table if exists buildids8_buildids;\n"
     328                 :            : // buildids7: separate _norm table into dense subtype tables
     329                 :            :   "drop table if exists buildids7_f_de;\n"
     330                 :            :   "drop table if exists buildids7_f_s;\n"
     331                 :            :   "drop table if exists buildids7_r_de;\n"
     332                 :            :   "drop table if exists buildids7_r_sref;\n"
     333                 :            :   "drop table if exists buildids7_r_sdef;\n"
     334                 :            :   "drop table if exists buildids7_file_mtime_scanned;\n"
     335                 :            :   "drop table if exists buildids7_files;\n"
     336                 :            :   "drop table if exists buildids7_buildids;\n"
     337                 :            : // buildids6: drop bolo/rfolo again, represent sources / rpmcontents in main table
     338                 :            :   "drop table if exists buildids6_norm;\n"
     339                 :            :   "drop table if exists buildids6_files;\n"
     340                 :            :   "drop table if exists buildids6_buildids;\n"
     341                 :            :   "drop view if exists buildids6;\n"
     342                 :            : // buildids5: redefine srcfile1 column to be '.'-less (for rpms)
     343                 :            :   "drop table if exists buildids5_norm;\n"
     344                 :            :   "drop table if exists buildids5_files;\n"
     345                 :            :   "drop table if exists buildids5_buildids;\n"
     346                 :            :   "drop table if exists buildids5_bolo;\n"
     347                 :            :   "drop table if exists buildids5_rfolo;\n"
     348                 :            :   "drop view if exists buildids5;\n"
     349                 :            : // buildids4: introduce rpmfile RFOLO
     350                 :            :   "drop table if exists buildids4_norm;\n"
     351                 :            :   "drop table if exists buildids4_files;\n"
     352                 :            :   "drop table if exists buildids4_buildids;\n"
     353                 :            :   "drop table if exists buildids4_bolo;\n"
     354                 :            :   "drop table if exists buildids4_rfolo;\n"
     355                 :            :   "drop view if exists buildids4;\n"
     356                 :            : // buildids3*: split out srcfile BOLO
     357                 :            :   "drop table if exists buildids3_norm;\n"
     358                 :            :   "drop table if exists buildids3_files;\n"
     359                 :            :   "drop table if exists buildids3_buildids;\n"
     360                 :            :   "drop table if exists buildids3_bolo;\n"
     361                 :            :   "drop view if exists buildids3;\n"
     362                 :            : // buildids2: normalized buildid and filenames into interning tables;
     363                 :            :   "drop table if exists buildids2_norm;\n"
     364                 :            :   "drop table if exists buildids2_files;\n"
     365                 :            :   "drop table if exists buildids2_buildids;\n"
     366                 :            :   "drop view if exists buildids2;\n"
     367                 :            :   // buildids1: made buildid and artifacttype NULLable, to represent cached-negative
     368                 :            : //           lookups from sources, e.g. files or rpms that contain no buildid-indexable content
     369                 :            :   "drop table if exists buildids1;\n"
     370                 :            : // buildids: original
     371                 :            :   "drop table if exists buildids;\n"
     372                 :            :   ;
     373                 :            : 
     374                 :            : static const char DEBUGINFOD_SQLITE_CLEANUP_DDL[] =
     375                 :            :   "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
     376                 :            :   ;
     377                 :            : 
     378                 :            : 
     379                 :            : 
     380                 :            : 
     381                 :            : /* Name and version of program.  */
     382                 :            : ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
     383                 :            : 
     384                 :            : /* Bug report address.  */
     385                 :            : ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
     386                 :            : 
     387                 :            : /* Definitions of arguments for argp functions.  */
     388                 :            : static const struct argp_option options[] =
     389                 :            :   {
     390                 :            :    { NULL, 0, NULL, 0, "Scanners:", 1 },
     391                 :            :    { "scan-file-dir", 'F', NULL, 0, "Enable ELF/DWARF file scanning.", 0 },
     392                 :            :    { "scan-rpm-dir", 'R', NULL, 0, "Enable RPM scanning.", 0 },
     393                 :            :    { "scan-deb-dir", 'U', NULL, 0, "Enable DEB scanning.", 0 },
     394                 :            :    { "scan-archive", 'Z', "EXT=CMD", 0, "Enable arbitrary archive scanning.", 0 },
     395                 :            :    // "source-oci-imageregistry"  ...
     396                 :            : 
     397                 :            :    { NULL, 0, NULL, 0, "Options:", 2 },
     398                 :            :    { "logical", 'L', NULL, 0, "Follow symlinks, default=ignore.", 0 },
     399                 :            :    { "rescan-time", 't', "SECONDS", 0, "Number of seconds to wait between rescans, 0=disable.", 0 },
     400                 :            :    { "groom-time", 'g', "SECONDS", 0, "Number of seconds to wait between database grooming, 0=disable.", 0 },
     401                 :            :    { "maxigroom", 'G', NULL, 0, "Run a complete database groom/shrink pass at startup.", 0 },
     402                 :            :    { "concurrency", 'c', "NUM", 0, "Limit scanning thread concurrency to NUM, default=#CPUs.", 0 },
     403                 :            :    { "connection-pool", 'C', "NUM", OPTION_ARG_OPTIONAL,
     404                 :            :      "Use webapi connection pool with NUM threads, default=unlim.", 0 },
     405                 :            :    { "include", 'I', "REGEX", 0, "Include files matching REGEX, default=all.", 0 },
     406                 :            :    { "exclude", 'X', "REGEX", 0, "Exclude files matching REGEX, default=none.", 0 },
     407                 :            :    { "port", 'p', "NUM", 0, "HTTP port to listen on, default 8002.", 0 },
     408                 :            :    { "database", 'd', "FILE", 0, "Path to sqlite database.", 0 },
     409                 :            :    { "ddl", 'D', "SQL", 0, "Apply extra sqlite ddl/pragma to connection.", 0 },
     410                 :            :    { "verbose", 'v', NULL, 0, "Increase verbosity.", 0 },
     411                 :            :    { "regex-groom", 'r', NULL, 0,"Uses regexes from -I and -X arguments to groom the database.",0},
     412                 :            : #define ARGP_KEY_FDCACHE_FDS 0x1001
     413                 :            :    { "fdcache-fds", ARGP_KEY_FDCACHE_FDS, "NUM", 0, "Maximum number of archive files to keep in fdcache.", 0 },
     414                 :            : #define ARGP_KEY_FDCACHE_MBS 0x1002
     415                 :            :    { "fdcache-mbs", ARGP_KEY_FDCACHE_MBS, "MB", 0, "Maximum total size of archive file fdcache.", 0 },
     416                 :            : #define ARGP_KEY_FDCACHE_PREFETCH 0x1003
     417                 :            :    { "fdcache-prefetch", ARGP_KEY_FDCACHE_PREFETCH, "NUM", 0, "Number of archive files to prefetch into fdcache.", 0 },
     418                 :            : #define ARGP_KEY_FDCACHE_MINTMP 0x1004
     419                 :            :    { "fdcache-mintmp", ARGP_KEY_FDCACHE_MINTMP, "NUM", 0, "Minimum free space% on tmpdir.", 0 },
     420                 :            : #define ARGP_KEY_FDCACHE_PREFETCH_MBS 0x1005
     421                 :            :    { "fdcache-prefetch-mbs", ARGP_KEY_FDCACHE_PREFETCH_MBS, "MB", 0,"Megabytes allocated to the \
     422                 :            :       prefetch cache.", 0},
     423                 :            : #define ARGP_KEY_FDCACHE_PREFETCH_FDS 0x1006
     424                 :            :    { "fdcache-prefetch-fds", ARGP_KEY_FDCACHE_PREFETCH_FDS, "NUM", 0,"Number of files allocated to the \
     425                 :            :       prefetch cache.", 0},
     426                 :            : #define ARGP_KEY_FORWARDED_TTL_LIMIT 0x1007
     427                 :            :    {"forwarded-ttl-limit", ARGP_KEY_FORWARDED_TTL_LIMIT, "NUM", 0, "Limit of X-Forwarded-For hops, default 8.", 0},
     428                 :            : #define ARGP_KEY_PASSIVE 0x1008
     429                 :            :    { "passive", ARGP_KEY_PASSIVE, NULL, 0, "Do not scan or groom, read-only database.", 0 },
     430                 :            : #define ARGP_KEY_DISABLE_SOURCE_SCAN 0x1009
     431                 :            :    { "disable-source-scan", ARGP_KEY_DISABLE_SOURCE_SCAN, NULL, 0, "Do not scan dwarf source info.", 0 },
     432                 :            : #define ARGP_SCAN_CHECKPOINT 0x100A
     433                 :            :    { "scan-checkpoint", ARGP_SCAN_CHECKPOINT, "NUM", 0, "Number of files scanned before a WAL checkpoint.", 0 },
     434                 :            :    { NULL, 0, NULL, 0, NULL, 0 },
     435                 :            :   };
     436                 :            : 
     437                 :            : /* Short description of program.  */
     438                 :            : static const char doc[] = "Serve debuginfo-related content across HTTP from files under PATHs.";
     439                 :            : 
     440                 :            : /* Strings for arguments in help texts.  */
     441                 :            : static const char args_doc[] = "[PATH ...]";
     442                 :            : 
     443                 :            : /* Prototype for option handler.  */
     444                 :            : static error_t parse_opt (int key, char *arg, struct argp_state *state);
     445                 :            : 
     446                 :            : static unsigned default_concurrency();
     447                 :            : 
     448                 :            : /* Data structure to communicate with argp functions.  */
     449                 :            : static struct argp argp =
     450                 :            :   {
     451                 :            :    options, parse_opt, args_doc, doc, NULL, NULL, NULL
     452                 :            :   };
     453                 :            : 
     454                 :            : 
     455                 :            : static string db_path;
     456                 :            : static sqlite3 *db;  // single connection, serialized across all our threads!
     457                 :            : static sqlite3 *dbq; // webapi query-servicing readonly connection, serialized ditto!
     458                 :            : static unsigned verbose;
     459                 :            : static volatile sig_atomic_t interrupted = 0;
     460                 :            : static volatile sig_atomic_t forced_rescan_count = 0;
     461                 :            : static volatile sig_atomic_t sigusr1 = 0;
     462                 :            : static volatile sig_atomic_t forced_groom_count = 0;
     463                 :            : static volatile sig_atomic_t sigusr2 = 0;
     464                 :            : static unsigned http_port = 8002;
     465                 :            : static unsigned rescan_s = 300;
     466                 :            : static unsigned groom_s = 86400;
     467                 :            : static bool maxigroom = false;
     468                 :            : static unsigned concurrency = default_concurrency();
     469                 :            : static int connection_pool = 0;
     470                 :            : static set<string> source_paths;
     471                 :            : static bool scan_files = false;
     472                 :            : static map<string,string> scan_archives;
     473                 :            : static vector<string> extra_ddl;
     474                 :            : static regex_t file_include_regex;
     475                 :            : static regex_t file_exclude_regex;
     476                 :            : static bool regex_groom = false;
     477                 :            : static bool traverse_logical;
     478                 :            : static long fdcache_fds;
     479                 :            : static long fdcache_mbs;
     480                 :            : static long fdcache_prefetch;
     481                 :            : static long fdcache_mintmp;
     482                 :            : static long fdcache_prefetch_mbs;
     483                 :            : static long fdcache_prefetch_fds;
     484                 :            : static unsigned forwarded_ttl_limit = 8;
     485                 :            : static bool scan_source_info = true;
     486                 :            : static string tmpdir;
     487                 :            : static bool passive_p = false;
     488                 :            : static long scan_checkpoint = 256;
     489                 :            : 
     490                 :            : static void set_metric(const string& key, double value);
     491                 :            : // static void inc_metric(const string& key);
     492                 :            : static void set_metric(const string& metric,
     493                 :            :                        const string& lname, const string& lvalue,
     494                 :            :                        double value);
     495                 :            : static void inc_metric(const string& metric,
     496                 :            :                        const string& lname, const string& lvalue);
     497                 :            : static void add_metric(const string& metric,
     498                 :            :                        const string& lname, const string& lvalue,
     499                 :            :                        double value);
     500                 :            : static void inc_metric(const string& metric,
     501                 :            :                        const string& lname, const string& lvalue,
     502                 :            :                        const string& rname, const string& rvalue);
     503                 :            : static void add_metric(const string& metric,
     504                 :            :                        const string& lname, const string& lvalue,
     505                 :            :                        const string& rname, const string& rvalue,                       
     506                 :            :                        double value);
     507                 :            : 
     508                 :            : 
     509                 :            : class tmp_inc_metric { // a RAII style wrapper for exception-safe scoped increment & decrement
     510                 :            :   string m, n, v;
     511                 :            : public:
     512                 :       1034 :   tmp_inc_metric(const string& mname, const string& lname, const string& lvalue):
     513   [ +  -  +  - ]:       1034 :     m(mname), n(lname), v(lvalue)
     514                 :            :   {
     515         [ +  - ]:       1034 :     add_metric (m, n, v, 1);
     516   [ -  -  -  -  :       1034 :   }
                   -  - ]
     517                 :       1034 :   ~tmp_inc_metric()
     518                 :            :   {
     519                 :       1034 :     add_metric (m, n, v, -1);
     520   [ -  +  -  +  :       1034 :   }
                   -  + ]
     521                 :            : };
     522                 :            : 
     523                 :            : class tmp_ms_metric { // a RAII style wrapper for exception-safe scoped timing
     524                 :            :   string m, n, v;
     525                 :            :   struct timespec ts_start;
     526                 :            : public:
     527                 :      49091 :   tmp_ms_metric(const string& mname, const string& lname, const string& lvalue):
     528   [ +  -  +  - ]:      49091 :     m(mname), n(lname), v(lvalue)
     529                 :            :   {
     530                 :      49093 :     clock_gettime (CLOCK_MONOTONIC, & ts_start);
     531   [ -  -  -  - ]:      49096 :   }
     532                 :      49098 :   ~tmp_ms_metric()
     533                 :            :   {
     534                 :      49098 :     struct timespec ts_end;
     535                 :      49098 :     clock_gettime (CLOCK_MONOTONIC, & ts_end);
     536                 :      49100 :     double deltas = (ts_end.tv_sec - ts_start.tv_sec)
     537                 :      49100 :       + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
     538                 :            : 
     539         [ +  - ]:      49100 :     add_metric (m + "_milliseconds_sum", n, v, (deltas*1000.0));
     540         [ +  - ]:      49101 :     inc_metric (m + "_milliseconds_count", n, v);
     541   [ +  +  -  +  :      86494 :   }
                   -  + ]
     542                 :            : };
     543                 :            : 
     544                 :            : 
     545                 :            : /* Handle program arguments.  */
     546                 :            : static error_t
     547                 :        562 : parse_opt (int key, char *arg,
     548                 :            :            struct argp_state *state __attribute__ ((unused)))
     549                 :            : {
     550                 :        562 :   int rc;
     551   [ +  +  +  +  :        562 :   switch (key)
          +  +  +  +  -  
          +  +  -  -  +  
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  -  +  
                      + ]
     552                 :            :     {
     553                 :        139 :     case 'v': verbose ++; break;
     554                 :         36 :     case 'd':
     555                 :            :       /* When using the in-memory database make sure it is shareable,
     556                 :            :          so we can open it twice as read/write and read-only.  */
     557         [ +  + ]:         36 :       if (strcmp (arg, ":memory:") == 0)
     558                 :        569 :         db_path = "file::memory:?cache=shared";
     559                 :            :       else
     560         [ +  - ]:         58 :         db_path = string(arg);
     561                 :            :       break;
     562                 :         36 :     case 'p': http_port = (unsigned) atoi(arg);
     563         [ +  - ]:         36 :       if (http_port == 0 || http_port > 65535)
     564                 :          0 :         argp_failure(state, 1, EINVAL, "port number");
     565                 :            :       break;
     566                 :         24 :     case 'F': scan_files = true; break;
     567                 :         11 :     case 'R':
     568   [ +  -  +  -  :         11 :       scan_archives[".rpm"]="cat"; // libarchive groks rpm natively
                   -  + ]
     569                 :         11 :       break;
     570                 :          7 :     case 'U':
     571   [ +  -  +  -  :          7 :       scan_archives[".deb"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     572   [ +  -  +  -  :          7 :       scan_archives[".ddeb"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     573   [ +  -  +  -  :          7 :       scan_archives[".ipk"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     574                 :            :       // .udeb too?
     575                 :          7 :       break;
     576                 :         19 :     case 'Z':
     577                 :         19 :       {
     578         [ -  + ]:         19 :         char* extension = strchr(arg, '=');
     579         [ -  + ]:         19 :         if (arg[0] == '\0')
     580                 :          0 :           argp_failure(state, 1, EINVAL, "missing EXT");
     581         [ +  + ]:         19 :         else if (extension)
     582   [ +  -  +  -  :         10 :           scan_archives[string(arg, (extension-arg))]=string(extension+1);
          -  +  -  +  -  
                      - ]
     583                 :            :         else
     584   [ +  -  +  -  :          9 :           scan_archives[string(arg)]=string("cat");
          -  +  -  +  -  
                      - ]
     585                 :            :       }
     586                 :            :       break;
     587                 :          4 :     case 'L':
     588         [ -  + ]:          4 :       if (passive_p)
     589                 :          0 :         argp_failure(state, 1, EINVAL, "-L option inconsistent with passive mode");
     590                 :          4 :       traverse_logical = true;
     591                 :          4 :       break;
     592                 :          0 :     case 'D':
     593         [ #  # ]:          0 :       if (passive_p)
     594                 :          0 :         argp_failure(state, 1, EINVAL, "-D option inconsistent with passive mode");
     595         [ #  # ]:          0 :       extra_ddl.push_back(string(arg));
     596                 :          0 :       break;
     597                 :         29 :     case 't':
     598         [ -  + ]:         29 :       if (passive_p)
     599                 :          0 :         argp_failure(state, 1, EINVAL, "-t option inconsistent with passive mode");
     600                 :         29 :       rescan_s = (unsigned) atoi(arg);
     601                 :         29 :       break;
     602                 :         29 :     case 'g':
     603         [ -  + ]:         29 :       if (passive_p)
     604                 :          0 :         argp_failure(state, 1, EINVAL, "-g option inconsistent with passive mode");
     605                 :         29 :       groom_s = (unsigned) atoi(arg);
     606                 :         29 :       break;
     607                 :          0 :     case 'G':
     608         [ #  # ]:          0 :       if (passive_p)
     609                 :          0 :         argp_failure(state, 1, EINVAL, "-G option inconsistent with passive mode");
     610                 :          0 :       maxigroom = true;
     611                 :          0 :       break;
     612                 :          0 :     case 'c':
     613         [ #  # ]:          0 :       if (passive_p)
     614                 :          0 :         argp_failure(state, 1, EINVAL, "-c option inconsistent with passive mode");
     615                 :          0 :       concurrency = (unsigned) atoi(arg);
     616         [ #  # ]:          0 :       if (concurrency < 1) concurrency = 1;
     617                 :            :       break;
     618                 :          3 :     case 'C':
     619         [ +  + ]:          3 :       if (arg)
     620                 :            :         {
     621                 :          2 :           connection_pool = atoi(arg);
     622         [ +  - ]:          2 :           if (connection_pool < 2)
     623                 :          0 :             argp_failure(state, 1, EINVAL, "-C NUM minimum 2");
     624                 :            :         }
     625                 :            :       break;
     626                 :          2 :     case 'I':
     627                 :            :       // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
     628         [ -  + ]:          2 :       if (passive_p)
     629                 :          0 :         argp_failure(state, 1, EINVAL, "-I option inconsistent with passive mode");
     630                 :          2 :       regfree (&file_include_regex);
     631                 :          2 :       rc = regcomp (&file_include_regex, arg, REG_EXTENDED|REG_NOSUB);
     632         [ +  - ]:          2 :       if (rc != 0)
     633                 :          0 :         argp_failure(state, 1, EINVAL, "regular expression");
     634                 :            :       break;
     635                 :          3 :     case 'X':
     636         [ -  + ]:          3 :       if (passive_p)
     637                 :          0 :         argp_failure(state, 1, EINVAL, "-X option inconsistent with passive mode");
     638                 :          3 :       regfree (&file_exclude_regex);
     639                 :          3 :       rc = regcomp (&file_exclude_regex, arg, REG_EXTENDED|REG_NOSUB);
     640         [ +  - ]:          3 :       if (rc != 0)
     641                 :          0 :         argp_failure(state, 1, EINVAL, "regular expression");
     642                 :            :       break;
     643                 :          2 :     case 'r':
     644         [ -  + ]:          2 :       if (passive_p)
     645                 :          0 :         argp_failure(state, 1, EINVAL, "-r option inconsistent with passive mode");
     646                 :          2 :       regex_groom = true;
     647                 :          2 :       break;
     648                 :          5 :     case ARGP_KEY_FDCACHE_FDS:
     649                 :          5 :       fdcache_fds = atol (arg);
     650                 :          5 :       break;
     651                 :          2 :     case ARGP_KEY_FDCACHE_MBS:
     652                 :          2 :       fdcache_mbs = atol (arg);
     653                 :          2 :       break;
     654                 :          1 :     case ARGP_KEY_FDCACHE_PREFETCH:
     655                 :          1 :       fdcache_prefetch = atol (arg);
     656                 :          1 :       break;
     657                 :          1 :     case ARGP_KEY_FDCACHE_MINTMP:
     658                 :          1 :       fdcache_mintmp = atol (arg);
     659         [ +  - ]:          1 :       if( fdcache_mintmp > 100 || fdcache_mintmp < 0 )
     660                 :          0 :         argp_failure(state, 1, EINVAL, "fdcache mintmp percent");
     661                 :            :       break;
     662                 :          2 :     case ARGP_KEY_FORWARDED_TTL_LIMIT:
     663                 :          2 :       forwarded_ttl_limit = (unsigned) atoi(arg);
     664                 :          2 :       break;
     665                 :         50 :     case ARGP_KEY_ARG:
     666         [ +  - ]:         50 :       source_paths.insert(string(arg));
     667                 :         50 :       break;
     668                 :          5 :     case ARGP_KEY_FDCACHE_PREFETCH_FDS:
     669                 :          5 :       fdcache_prefetch_fds = atol(arg);
     670         [ +  - ]:          5 :       if ( fdcache_prefetch_fds < 0)
     671                 :          0 :         argp_failure(state, 1, EINVAL, "fdcache prefetch fds");
     672                 :            :       break;
     673                 :          1 :     case ARGP_KEY_FDCACHE_PREFETCH_MBS:
     674                 :          1 :       fdcache_prefetch_mbs = atol(arg);
     675         [ +  - ]:          1 :       if ( fdcache_prefetch_mbs < 0)
     676                 :          0 :         argp_failure(state, 1, EINVAL, "fdcache prefetch mbs");
     677                 :            :       break;
     678                 :          1 :     case ARGP_KEY_PASSIVE:
     679                 :          1 :       passive_p = true;
     680         [ +  - ]:          1 :       if (source_paths.size() > 0
     681         [ +  - ]:          1 :           || maxigroom
     682         [ +  - ]:          1 :           || extra_ddl.size() > 0
     683   [ +  -  +  - ]:          2 :           || traverse_logical)
     684                 :            :         // other conflicting options tricky to check
     685                 :          0 :         argp_failure(state, 1, EINVAL, "inconsistent options with passive mode");
     686                 :            :       break;
     687                 :          0 :     case ARGP_KEY_DISABLE_SOURCE_SCAN:
     688                 :          0 :       scan_source_info = false;
     689                 :          0 :       break;
     690                 :          1 :     case ARGP_SCAN_CHECKPOINT:
     691                 :          1 :       scan_checkpoint = atol (arg);
     692         [ +  - ]:          1 :       if (scan_checkpoint < 0)
     693                 :          0 :         argp_failure(state, 1, EINVAL, "scan checkpoint");        
     694                 :            :       break;
     695                 :            :       // case 'h': argp_state_help (state, stderr, ARGP_HELP_LONG|ARGP_HELP_EXIT_OK);
     696                 :            :     default: return ARGP_ERR_UNKNOWN;
     697                 :            :     }
     698                 :            : 
     699                 :            :   return 0;
     700                 :            : }
     701                 :            : 
     702                 :            : 
     703                 :            : ////////////////////////////////////////////////////////////////////////
     704                 :            : 
     705                 :            : 
     706                 :            : static void add_mhd_response_header (struct MHD_Response *r,
     707                 :            :                                      const char *h, const char *v);
     708                 :            : 
     709                 :            : // represent errors that may get reported to an ostream and/or a libmicrohttpd connection
     710                 :            : 
     711                 :          4 : struct reportable_exception
     712                 :            : {
     713                 :            :   int code;
     714                 :            :   string message;
     715                 :            : 
     716   [ -  -  +  -  :         43 :   reportable_exception(int c, const string& m): code(c), message(m) {}
          -  -  +  -  +  
                      - ]
     717   [ -  -  -  -  :        300 :   reportable_exception(const string& m): code(503), message(m) {}
          -  -  -  -  +  
          -  -  -  -  -  
          +  -  -  -  -  
          -  -  -  +  -  
                   -  - ]
     718                 :            :   reportable_exception(): code(503), message() {}
     719                 :            : 
     720                 :            :   void report(ostream& o) const; // defined under obatched() class below
     721                 :            : 
     722                 :        315 :   MHD_RESULT mhd_send_response(MHD_Connection* c) const {
     723                 :        630 :     MHD_Response* r = MHD_create_response_from_buffer (message.size(),
     724                 :        315 :                                                        (void*) message.c_str(),
     725                 :            :                                                        MHD_RESPMEM_MUST_COPY);
     726                 :        315 :     add_mhd_response_header (r, "Content-Type", "text/plain");
     727                 :        315 :     MHD_RESULT rc = MHD_queue_response (c, code, r);
     728                 :        315 :     MHD_destroy_response (r);
     729                 :        315 :     return rc;
     730                 :            :   }
     731                 :            : };
     732                 :            : 
     733                 :            : 
     734                 :            : struct sqlite_exception: public reportable_exception
     735                 :            : {
     736                 :          0 :   sqlite_exception(int rc, const string& msg):
     737   [ #  #  #  #  :          0 :     reportable_exception(string("sqlite3 error: ") + msg + ": " + string(sqlite3_errstr(rc) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     738   [ #  #  #  #  :          0 :     inc_metric("error_count","sqlite3",sqlite3_errstr(rc));
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
     739         [ #  # ]:          0 :   }
     740                 :            : };
     741                 :            : 
     742   [ +  -  -  - ]:          2 : struct libc_exception: public reportable_exception
     743                 :            : {
     744                 :        297 :   libc_exception(int rc, const string& msg):
     745   [ -  +  +  -  :       1188 :     reportable_exception(string("libc error: ") + msg + ": " + string(strerror(rc) ?: "?")) {
          +  -  +  -  +  
          -  -  +  -  +  
          -  +  +  -  -  
                      - ]
     746   [ +  -  +  -  :        594 :     inc_metric("error_count","libc",strerror(rc));
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
     747         [ -  - ]:        297 :   }
     748                 :            : };
     749                 :            : 
     750                 :            : 
     751                 :            : struct archive_exception: public reportable_exception
     752                 :            : {
     753                 :          0 :   archive_exception(const string& msg):
     754   [ #  #  #  #  :          0 :     reportable_exception(string("libarchive error: ") + msg) {
                   #  # ]
     755   [ #  #  #  #  :          0 :       inc_metric("error_count","libarchive",msg);
          #  #  #  #  #  
                      # ]
     756         [ #  # ]:          0 :   }
     757                 :          0 :   archive_exception(struct archive* a, const string& msg):
     758   [ #  #  #  #  :          0 :     reportable_exception(string("libarchive error: ") + msg + ": " + string(archive_error_string(a) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     759   [ #  #  #  #  :          0 :     inc_metric("error_count","libarchive",msg + ": " + string(archive_error_string(a) ?: "?"));
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     760         [ #  # ]:          0 :   }
     761                 :            : };
     762                 :            : 
     763                 :            : 
     764                 :            : struct elfutils_exception: public reportable_exception
     765                 :            : {
     766                 :          0 :   elfutils_exception(int rc, const string& msg):
     767   [ #  #  #  #  :          0 :     reportable_exception(string("elfutils error: ") + msg + ": " + string(elf_errmsg(rc) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     768   [ #  #  #  #  :          0 :     inc_metric("error_count","elfutils",elf_errmsg(rc));
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
     769         [ #  # ]:          0 :   }
     770                 :            : };
     771                 :            : 
     772                 :            : 
     773                 :            : ////////////////////////////////////////////////////////////////////////
     774                 :            : 
     775                 :            : template <typename Payload>
     776                 :            : class workq
     777                 :            : {
     778                 :            :   unordered_set<Payload> q; // eliminate duplicates
     779                 :            :   mutex mtx;
     780                 :            :   condition_variable cv;
     781                 :            :   bool dead;
     782                 :            :   unsigned idlers;   // number of threads busy with wait_idle / done_idle
     783                 :            :   unsigned fronters; // number of threads busy with wait_front / done_front
     784                 :            : 
     785                 :            : public:
     786                 :         36 :   workq() { dead = false; idlers = 0; fronters = 0; }
     787                 :         36 :   ~workq() {}
     788                 :            : 
     789                 :        470 :   void push_back(const Payload& p)
     790                 :            :   {
     791                 :        470 :     unique_lock<mutex> lock(mtx);
     792         [ +  - ]:        470 :     q.insert (p);
     793   [ +  -  +  -  :        940 :     set_metric("thread_work_pending","role","scan", q.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
     794                 :        470 :     cv.notify_all();
     795                 :        470 :   }
     796                 :            : 
     797                 :            :   // kill this workqueue, wake up all idlers / scanners
     798                 :         36 :   void nuke() {
     799                 :         36 :     unique_lock<mutex> lock(mtx);
     800                 :            :     // optional: q.clear();
     801                 :         36 :     dead = true;
     802                 :         36 :     cv.notify_all();
     803                 :         36 :   }
     804                 :            : 
     805                 :            :   // clear the workqueue, when scanning is interrupted with USR2
     806                 :          0 :   void clear() {
     807                 :          0 :     unique_lock<mutex> lock(mtx);
     808                 :          0 :     q.clear();
     809   [ #  #  #  #  :          0 :     set_metric("thread_work_pending","role","scan", q.size());
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     810                 :            :     // NB: there may still be some live fronters
     811                 :          0 :     cv.notify_all(); // maybe wake up waiting idlers
     812                 :          0 :   }
     813                 :            : 
     814                 :            :   // block this scanner thread until there is work to do and no active idler
     815                 :        598 :   bool wait_front (Payload& p)
     816                 :            :   {
     817                 :        598 :     unique_lock<mutex> lock(mtx);
     818   [ +  +  +  +  :       2412 :     while (!dead && (q.size() == 0 || idlers > 0))
                   +  + ]
     819         [ +  - ]:       1814 :       cv.wait(lock);
     820         [ +  + ]:        598 :     if (dead)
     821                 :            :       return false;
     822                 :            :     else
     823                 :            :       {
     824         [ +  - ]:        470 :         p = * q.begin();
     825                 :        470 :         q.erase (q.begin());
     826                 :        470 :         fronters ++; // prevent idlers from starting awhile, even if empty q
     827   [ +  -  +  -  :        940 :         set_metric("thread_work_pending","role","scan", q.size());
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
     828                 :            :         // NB: don't wake up idlers yet!  The consumer is busy
     829                 :            :         // processing this element until it calls done_front().
     830                 :        470 :         return true;
     831                 :            :       }
     832                 :        597 :   }
     833                 :            : 
     834                 :            :   // notify waitq that scanner thread is done with that last item
     835                 :        470 :   void done_front ()
     836                 :            :   {
     837                 :        470 :     unique_lock<mutex> lock(mtx);
     838                 :        470 :     fronters --;
     839   [ +  +  +  + ]:        470 :     if (q.size() == 0 && fronters == 0)
     840                 :         48 :       cv.notify_all(); // maybe wake up waiting idlers
     841                 :        470 :   }
     842                 :            :   
     843                 :            :   // block this idler thread until there is no work to do
     844                 :        325 :   void wait_idle ()
     845                 :            :   {
     846                 :        325 :     unique_lock<mutex> lock(mtx);
     847                 :        325 :     cv.notify_all(); // maybe wake up waiting scanners
     848   [ +  +  +  +  :        351 :     while (!dead && ((q.size() != 0) || fronters > 0))
                   +  + ]
     849         [ +  - ]:         26 :       cv.wait(lock);
     850         [ +  - ]:        325 :     idlers ++;
     851                 :        325 :   }
     852                 :            : 
     853                 :        290 :   void done_idle ()
     854                 :            :   {
     855                 :        290 :     unique_lock<mutex> lock(mtx);
     856                 :        290 :     idlers --;
     857                 :        290 :     cv.notify_all(); // maybe wake up waiting scanners, but probably not (shutting down)
     858                 :        290 :   }
     859                 :            : };
     860                 :            : 
     861                 :            : typedef struct stat stat_t;
     862                 :            : typedef pair<string,stat_t> scan_payload;
     863                 :            : inline bool operator< (const scan_payload& a, const scan_payload& b)
     864                 :            : {
     865                 :            :   return a.first < b.first; // don't bother compare the stat fields
     866                 :            : }
     867                 :            : 
     868                 :            : namespace std { // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480
     869                 :            :   template<> struct hash<::scan_payload>
     870                 :            :   {
     871                 :       1773 :     std::size_t operator() (const ::scan_payload& p) const noexcept
     872                 :            :     {
     873   [ +  +  +  + ]:       1773 :       return hash<string>()(p.first);
     874                 :            :     }
     875                 :            :   };
     876                 :            :   template<> struct equal_to<::scan_payload>
     877                 :            :   {
     878                 :        128 :     std::size_t operator() (const ::scan_payload& a, const ::scan_payload& b) const noexcept
     879                 :            :     {
     880   [ -  +  -  - ]:        128 :       return a.first == b.first;
     881                 :            :     }
     882                 :            :   };
     883                 :            : }
     884                 :            : 
     885                 :            : static workq<scan_payload> scanq; // just a single one
     886                 :            : // producer & idler: thread_main_fts_source_paths()
     887                 :            : // consumer: thread_main_scanner()
     888                 :            : // idler: thread_main_groom()
     889                 :            : 
     890                 :            : 
     891                 :            : ////////////////////////////////////////////////////////////////////////
     892                 :            : 
     893                 :            : // Unique set is a thread-safe structure that lends 'ownership' of a value
     894                 :            : // to a thread.  Other threads requesting the same thing are made to wait.
     895                 :            : // It's like a semaphore-on-demand.
     896                 :            : template <typename T>
     897                 :            : class unique_set
     898                 :            : {
     899                 :            : private:
     900                 :            :   set<T> values;
     901                 :            :   mutex mtx;
     902                 :            :   condition_variable cv;
     903                 :            : public:
     904                 :         28 :   unique_set() {}
     905                 :         28 :   ~unique_set() {}
     906                 :            : 
     907                 :        692 :   void acquire(const T& value)
     908                 :            :   {
     909                 :        692 :     unique_lock<mutex> lock(mtx);
     910         [ +  + ]:       2764 :     while (values.find(value) != values.end())
     911         [ +  - ]:       2072 :       cv.wait(lock);
     912         [ +  - ]:        692 :     values.insert(value);
     913                 :        692 :   }
     914                 :            : 
     915                 :        692 :   void release(const T& value)
     916                 :            :   {
     917                 :        692 :     unique_lock<mutex> lock(mtx);
     918                 :            :     // assert (values.find(value) != values.end());
     919                 :        692 :     values.erase(value);
     920                 :        692 :     cv.notify_all();
     921                 :        692 :   }
     922                 :            : };
     923                 :            : 
     924                 :            : 
     925                 :            : // This is the object that's instantiate to uniquely hold a value in a
     926                 :            : // RAII-pattern way.
     927                 :            : template <typename T>
     928                 :            : class unique_set_reserver
     929                 :            : {
     930                 :            : private:
     931                 :            :   unique_set<T>& please_hold;
     932                 :            :   T mine;
     933                 :            : public:
     934                 :        692 :   unique_set_reserver(unique_set<T>& t, const T& value):
     935   [ +  -  -  - ]:        692 :     please_hold(t), mine(value)  { please_hold.acquire(mine); }
     936         [ +  - ]:        692 :   ~unique_set_reserver() { please_hold.release(mine); }
     937                 :            : };
     938                 :            : 
     939                 :            : 
     940                 :            : ////////////////////////////////////////////////////////////////////////
     941                 :            : 
     942                 :            : // periodic_barrier is a concurrency control object that lets N threads
     943                 :            : // periodically (based on counter value) agree to wait at a barrier,
     944                 :            : // let one of them carry out some work, then be set free
     945                 :            : 
     946                 :            : class periodic_barrier
     947                 :            : {
     948                 :            : private:
     949                 :            :   unsigned period; // number of count() reports to trigger barrier activation
     950                 :            :   unsigned threads; // number of threads participating
     951                 :            :   mutex mtx; // protects all the following fields
     952                 :            :   unsigned counter; // count of count() reports in the current generation
     953                 :            :   unsigned generation; // barrier activation generation
     954                 :            :   unsigned waiting; // number of threads waiting for barrier
     955                 :            :   bool dead; // bring out your
     956                 :            :   condition_variable cv;
     957                 :            : public:
     958                 :         32 :   periodic_barrier(unsigned t, unsigned p):
     959                 :         32 :     period(p), threads(t), counter(0), generation(0), waiting(0), dead(false) { }
     960                 :          0 :   virtual ~periodic_barrier() {}
     961                 :            : 
     962                 :            :   virtual void periodic_barrier_work() noexcept = 0;
     963                 :         32 :   void nuke() {
     964                 :         32 :     unique_lock<mutex> lock(mtx);
     965                 :         32 :     dead = true;
     966                 :         32 :     cv.notify_all();
     967                 :         32 :   }
     968                 :            :   
     969                 :        598 :   void count()
     970                 :            :   {
     971                 :        598 :     unique_lock<mutex> lock(mtx);
     972                 :        598 :     unsigned prev_generation = this->generation;
     973         [ +  + ]:        598 :     if (counter < period-1) // normal case: counter just freely running
     974                 :            :       {
     975                 :        540 :         counter ++;
     976                 :        540 :         return;
     977                 :            :       }
     978         [ +  + ]:         58 :     else if (counter == period-1) // we're the doer
     979                 :            :       {
     980                 :         15 :         counter = period; // entering barrier holding phase
     981                 :         15 :         cv.notify_all();
     982   [ +  +  +  + ]:         73 :         while (waiting < threads-1 && !dead)
     983         [ +  - ]:         43 :           cv.wait(lock);
     984                 :            :         // all other threads are now stuck in the barrier
     985                 :         15 :         this->periodic_barrier_work(); // NB: we're holding the mutex the whole time
     986                 :            :         // reset for next barrier, releasing other waiters
     987                 :         15 :         counter = 0;
     988                 :         15 :         generation ++;
     989                 :         15 :         cv.notify_all();
     990                 :         15 :         return;
     991                 :            :       }
     992         [ +  - ]:         43 :     else if (counter == period) // we're a waiter, in holding phase
     993                 :            :       {
     994                 :         43 :         waiting ++;
     995                 :         43 :         cv.notify_all();
     996   [ +  +  +  +  :        154 :         while (counter == period && generation == prev_generation && !dead)
                   +  + ]
     997         [ +  - ]:         68 :           cv.wait(lock);
     998                 :         43 :         waiting --;
     999                 :         43 :         return;
    1000                 :            :       }
    1001                 :        598 :   }
    1002                 :            : };
    1003                 :            : 
    1004                 :            : 
    1005                 :            : 
    1006                 :            : ////////////////////////////////////////////////////////////////////////
    1007                 :            : 
    1008                 :            : 
    1009                 :            : // Print a standard timestamp.
    1010                 :            : static ostream&
    1011                 :      11040 : timestamp (ostream &o)
    1012                 :            : {
    1013                 :      11040 :   char datebuf[80];
    1014                 :      11040 :   char *now2 = NULL;
    1015                 :      11040 :   time_t now_t = time(NULL);
    1016                 :      11040 :   struct tm now;
    1017                 :      11040 :   struct tm *nowp = gmtime_r (&now_t, &now);
    1018         [ +  - ]:      11040 :   if (nowp)
    1019                 :            :     {
    1020                 :      11040 :       (void) strftime (datebuf, sizeof (datebuf), "%c", nowp);
    1021                 :      11040 :       now2 = datebuf;
    1022                 :            :     }
    1023                 :            : 
    1024                 :      11040 :   return o << "[" << (now2 ? now2 : "") << "] "
    1025         [ -  + ]:      11040 :            << "(" << getpid () << "/" << tid() << "): ";
    1026                 :            : }
    1027                 :            : 
    1028                 :            : 
    1029                 :            : // A little class that impersonates an ostream to the extent that it can
    1030                 :            : // take << streaming operations.  It batches up the bits into an internal
    1031                 :            : // stringstream until it is destroyed; then flushes to the original ostream.
    1032                 :            : // It adds a timestamp
    1033                 :            : class obatched
    1034                 :            : {
    1035                 :            : private:
    1036                 :            :   ostream& o;
    1037                 :            :   stringstream stro;
    1038                 :            :   static mutex lock;
    1039                 :            : public:
    1040                 :      11040 :   obatched(ostream& oo, bool timestamp_p = true): o(oo)
    1041                 :            :   {
    1042         [ +  - ]:      11040 :     if (timestamp_p)
    1043         [ +  - ]:      11040 :       timestamp(stro);
    1044                 :      11040 :   }
    1045                 :      11040 :   ~obatched()
    1046                 :            :   {
    1047                 :      11040 :     unique_lock<mutex> do_not_cross_the_streams(obatched::lock);
    1048         [ +  - ]:      11040 :     o << stro.str();
    1049                 :      11040 :     o.flush();
    1050                 :      11040 :   }
    1051                 :            :   operator ostream& () { return stro; }
    1052   [ -  -  +  -  :       8309 :   template <typename T> ostream& operator << (const T& t) { stro << t; return stro; }
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  +  -  -  -  
          +  -  -  -  -  
          -  -  -  +  -  
          -  -  +  -  -  
          -  +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  -  
                -  -  - ]
    1053                 :            : };
    1054                 :            : mutex obatched::lock; // just the one, since cout/cerr iostreams are not thread-safe
    1055                 :            : 
    1056                 :            : 
    1057                 :        346 : void reportable_exception::report(ostream& o) const {
    1058   [ +  -  +  - ]:        346 :   obatched(o) << message << endl;
    1059                 :        346 : }
    1060                 :            : 
    1061                 :            : 
    1062                 :            : ////////////////////////////////////////////////////////////////////////
    1063                 :            : 
    1064                 :            : 
    1065                 :            : // RAII style sqlite prepared-statement holder that matches { } block lifetime
    1066                 :            : 
    1067                 :            : struct sqlite_ps
    1068                 :            : {
    1069                 :            : private:
    1070                 :            :   sqlite3* db;
    1071                 :            :   const string nickname;
    1072                 :            :   const string sql;
    1073                 :            :   sqlite3_stmt *pp;
    1074                 :            : 
    1075                 :            :   sqlite_ps(const sqlite_ps&); // make uncopyable
    1076                 :            :   sqlite_ps& operator=(const sqlite_ps &); // make unassignable
    1077                 :            : 
    1078                 :            : public:
    1079   [ +  -  -  - ]:       3232 :   sqlite_ps (sqlite3* d, const string& n, const string& s): db(d), nickname(n), sql(s) {
    1080                 :            :     // tmp_ms_metric tick("sqlite3","prep",nickname);
    1081         [ +  + ]:       3232 :     if (verbose > 4)
    1082   [ +  -  +  -  :        176 :       obatched(clog) << nickname << " prep " << sql << endl;
          +  -  +  -  +  
                -  -  - ]
    1083         [ +  - ]:       3232 :     int rc = sqlite3_prepare_v2 (db, sql.c_str(), -1 /* to \0 */, & this->pp, NULL);
    1084         [ -  + ]:       3232 :     if (rc != SQLITE_OK)
    1085   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "prepare " + sql);
    1086                 :       3232 :   }
    1087                 :            : 
    1088                 :      26974 :   sqlite_ps& reset()
    1089                 :            :   {
    1090   [ +  -  +  -  :      53947 :     tmp_ms_metric tick("sqlite3","reset",nickname);
             -  +  -  - ]
    1091         [ +  - ]:      26973 :     sqlite3_reset(this->pp);
    1092                 :      26974 :     return *this;
    1093                 :      26972 :   }
    1094                 :            : 
    1095                 :      28826 :   sqlite_ps& bind(int parameter, const string& str)
    1096                 :            :   {
    1097         [ +  + ]:      28826 :     if (verbose > 4)
    1098   [ +  -  +  -  :        709 :       obatched(clog) << nickname << " bind " << parameter << "=" << str << endl;
          +  -  +  -  +  
                -  +  - ]
    1099                 :      28826 :     int rc = sqlite3_bind_text (this->pp, parameter, str.c_str(), -1, SQLITE_TRANSIENT);
    1100         [ -  + ]:      28826 :     if (rc != SQLITE_OK)
    1101   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 bind");
    1102                 :      28826 :     return *this;
    1103                 :            :   }
    1104                 :            : 
    1105                 :       8852 :   sqlite_ps& bind(int parameter, int64_t value)
    1106                 :            :   {
    1107         [ +  + ]:       8852 :     if (verbose > 4)
    1108   [ +  -  +  -  :        318 :       obatched(clog) << nickname << " bind " << parameter << "=" << value << endl;
          +  -  +  -  +  
                -  +  - ]
    1109                 :       8852 :     int rc = sqlite3_bind_int64 (this->pp, parameter, value);
    1110         [ -  + ]:       8852 :     if (rc != SQLITE_OK)
    1111   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 bind");
    1112                 :       8852 :     return *this;
    1113                 :            :   }
    1114                 :            : 
    1115                 :            :   sqlite_ps& bind(int parameter)
    1116                 :            :   {
    1117                 :            :     if (verbose > 4)
    1118                 :            :       obatched(clog) << nickname << " bind " << parameter << "=" << "NULL" << endl;
    1119                 :            :     int rc = sqlite3_bind_null (this->pp, parameter);
    1120                 :            :     if (rc != SQLITE_OK)
    1121                 :            :       throw sqlite_exception(rc, "sqlite3 bind");
    1122                 :            :     return *this;
    1123                 :            :   }
    1124                 :            : 
    1125                 :            : 
    1126                 :      15823 :   void step_ok_done() {
    1127   [ +  -  +  -  :      31646 :     tmp_ms_metric tick("sqlite3","step_done",nickname);
             -  +  -  - ]
    1128         [ +  - ]:      15823 :     int rc = sqlite3_step (this->pp);
    1129         [ +  + ]:      15823 :     if (verbose > 4)
    1130   [ +  -  +  -  :        416 :       obatched(clog) << nickname << " step-ok-done(" << sqlite3_errstr(rc) << ") " << sql << endl;
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1131   [ +  +  -  + ]:      15823 :     if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
    1132   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 step");
    1133         [ +  - ]:      15823 :     (void) sqlite3_reset (this->pp);
    1134                 :      15823 :   }
    1135                 :            : 
    1136                 :            : 
    1137                 :       6304 :   int step() {
    1138   [ +  -  +  -  :      12608 :     tmp_ms_metric tick("sqlite3","step",nickname);
             -  +  -  - ]
    1139         [ +  - ]:       6304 :     int rc = sqlite3_step (this->pp);
    1140         [ +  + ]:       6304 :     if (verbose > 4)
    1141   [ +  -  +  -  :        209 :       obatched(clog) << nickname << " step(" << sqlite3_errstr(rc) << ") " << sql << endl;
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1142                 :       6304 :     return rc;
    1143                 :       6304 :   }
    1144                 :            : 
    1145   [ +  +  +  + ]:       6426 :   ~sqlite_ps () { sqlite3_finalize (this->pp); }
    1146   [ +  -  +  -  :       1290 :   operator sqlite3_stmt* () { return this->pp; }
                   +  - ]
    1147                 :            : };
    1148                 :            : 
    1149                 :            : 
    1150                 :            : ////////////////////////////////////////////////////////////////////////
    1151                 :            : 
    1152                 :            : 
    1153                 :            : struct sqlite_checkpoint_pb: public periodic_barrier
    1154                 :            : {
    1155                 :            :   sqlite_ps ckpt;
    1156                 :            : 
    1157                 :         32 :   sqlite_checkpoint_pb(unsigned t, unsigned p):
    1158   [ +  -  +  -  :         64 :     periodic_barrier(t, p), ckpt(db, "periodic wal checkpoint",
             +  -  -  - ]
    1159         [ +  - ]:         64 :                                  "pragma wal_checkpoint(truncate);") {}
    1160                 :            :   
    1161                 :         15 :   void periodic_barrier_work() noexcept
    1162                 :            :   {
    1163                 :         15 :     try
    1164                 :            :       {
    1165   [ +  -  +  - ]:         15 :         ckpt.reset().step_ok_done();
    1166                 :            :       }
    1167         [ -  - ]:          0 :     catch (const reportable_exception& e)
    1168                 :            :       {
    1169                 :          0 :         e.report(clog);        
    1170                 :          0 :       }
    1171                 :         15 :   }
    1172                 :            : };
    1173                 :            :   
    1174                 :            : static periodic_barrier* scan_barrier = 0; // initialized in main()
    1175                 :            : 
    1176                 :            : 
    1177                 :            : ////////////////////////////////////////////////////////////////////////
    1178                 :            : 
    1179                 :            : // RAII style templated autocloser
    1180                 :            : 
    1181                 :            : template <class Payload, class Ignore>
    1182                 :            : struct defer_dtor
    1183                 :            : {
    1184                 :            : public:
    1185                 :            :   typedef Ignore (*dtor_fn) (Payload);
    1186                 :            : 
    1187                 :            : private:
    1188                 :            :   Payload p;
    1189                 :            :   dtor_fn fn;
    1190                 :            : 
    1191                 :            : public:
    1192                 :       2673 :   defer_dtor(Payload _p, dtor_fn _fn): p(_p), fn(_fn) {}
    1193                 :       1117 :   ~defer_dtor() { (void) (*fn)(p); }
    1194                 :            : 
    1195                 :            : private:
    1196                 :            :   defer_dtor(const defer_dtor<Payload,Ignore>&); // make uncopyable
    1197                 :            :   defer_dtor& operator=(const defer_dtor<Payload,Ignore> &); // make unassignable
    1198                 :            : };
    1199                 :            : 
    1200                 :            : 
    1201                 :            : 
    1202                 :            : ////////////////////////////////////////////////////////////////////////
    1203                 :            : 
    1204                 :            : 
    1205                 :            : static string
    1206                 :       2074 : header_censor(const string& str)
    1207                 :            : {
    1208                 :       2074 :   string y;
    1209         [ +  + ]:      17509 :   for (auto&& x : str)
    1210                 :            :     {
    1211         [ +  + ]:      15435 :       if (isalnum(x) || x == '/' || x == '.' || x == ',' || x == '_' || x == ':')
    1212         [ +  - ]:      30867 :         y += x;
    1213                 :            :     }
    1214                 :       2074 :   return y;
    1215                 :          0 : }
    1216                 :            : 
    1217                 :            : 
    1218                 :            : static string
    1219                 :       1037 : conninfo (struct MHD_Connection * conn)
    1220                 :            : {
    1221                 :       1037 :   char hostname[256]; // RFC1035
    1222                 :       1037 :   char servname[256];
    1223                 :       1037 :   int sts = -1;
    1224                 :            : 
    1225         [ -  + ]:       1037 :   if (conn == 0)
    1226                 :          0 :     return "internal";
    1227                 :            : 
    1228                 :            :   /* Look up client address data. */
    1229                 :       1037 :   const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
    1230                 :            :                                                                MHD_CONNECTION_INFO_CLIENT_ADDRESS);
    1231         [ +  - ]:       1037 :   struct sockaddr *so = u ? u->client_addr : 0;
    1232                 :            : 
    1233   [ +  -  -  + ]:       1037 :   if (so && so->sa_family == AF_INET) {
    1234                 :          0 :     sts = getnameinfo (so, sizeof (struct sockaddr_in),
    1235                 :            :                        hostname, sizeof (hostname),
    1236                 :            :                        servname, sizeof (servname),
    1237                 :            :                        NI_NUMERICHOST | NI_NUMERICSERV);
    1238         [ +  - ]:       1037 :   } else if (so && so->sa_family == AF_INET6) {
    1239                 :       1037 :     struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
    1240   [ +  -  +  -  :       1037 :     if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
                   -  + ]
    1241                 :       1037 :       struct sockaddr_in addr4;
    1242                 :       1037 :       memset (&addr4, 0, sizeof(addr4));
    1243                 :       1037 :       addr4.sin_family = AF_INET;
    1244                 :       1037 :       addr4.sin_port = addr6->sin6_port;
    1245                 :       1037 :       memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
    1246                 :       1037 :       sts = getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
    1247                 :            :                          hostname, sizeof (hostname),
    1248                 :            :                          servname, sizeof (servname),
    1249                 :            :                          NI_NUMERICHOST | NI_NUMERICSERV);
    1250                 :            :     } else {
    1251                 :          0 :       sts = getnameinfo (so, sizeof (struct sockaddr_in6),
    1252                 :            :                          hostname, sizeof (hostname),
    1253                 :            :                          servname, sizeof (servname),
    1254                 :            :                          NI_NUMERICHOST | NI_NUMERICSERV);
    1255                 :            :     }
    1256                 :            :   }
    1257                 :            :   
    1258         [ -  + ]:       1037 :   if (sts != 0) {
    1259                 :          0 :     hostname[0] = servname[0] = '\0';
    1260                 :            :   }
    1261                 :            : 
    1262                 :            :   // extract headers relevant to administration
    1263         [ -  + ]:       1037 :   const char* user_agent = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
    1264         [ +  + ]:       1037 :   const char* x_forwarded_for = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
    1265                 :            :   // NB: these are untrustworthy, beware if machine-processing log files
    1266                 :            : 
    1267   [ +  -  +  -  :       3111 :   return string(hostname) + string(":") + string(servname) +
          +  -  +  -  +  
          -  +  -  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  -  -  
                      - ]
    1268   [ +  -  +  -  :       4299 :     string(" UA:") + header_censor(string(user_agent)) +
          +  -  +  -  +  
          -  -  +  +  +  
          -  +  +  +  -  
             +  -  -  -  
                      - ]
    1269   [ +  -  +  -  :       3117 :     string(" XFF:") + header_censor(string(x_forwarded_for));
          +  -  +  +  +  
                +  -  - ]
    1270                 :            : }
    1271                 :            : 
    1272                 :            : 
    1273                 :            : 
    1274                 :            : ////////////////////////////////////////////////////////////////////////
    1275                 :            : 
    1276                 :            : /* Wrapper for MHD_add_response_header that logs an error if we
    1277                 :            :    couldn't add the specified header.  */
    1278                 :            : static void
    1279                 :       3025 : add_mhd_response_header (struct MHD_Response *r,
    1280                 :            :                          const char *h, const char *v)
    1281                 :            : {
    1282         [ -  + ]:       3025 :   if (MHD_add_response_header (r, h, v) == MHD_NO)
    1283   [ #  #  #  #  :          0 :     obatched(clog) << "Error: couldn't add '" << h << "' header" << endl;
                   #  # ]
    1284                 :       3025 : }
    1285                 :            : 
    1286                 :            : static void
    1287                 :        401 : add_mhd_last_modified (struct MHD_Response *resp, time_t mtime)
    1288                 :            : {
    1289                 :        401 :   struct tm now;
    1290                 :        401 :   struct tm *nowp = gmtime_r (&mtime, &now);
    1291         [ +  - ]:        401 :   if (nowp != NULL)
    1292                 :            :     {
    1293                 :        401 :       char datebuf[80];
    1294                 :        401 :       size_t rc = strftime (datebuf, sizeof (datebuf), "%a, %d %b %Y %T GMT",
    1295                 :            :                             nowp);
    1296         [ +  - ]:        401 :       if (rc > 0 && rc < sizeof (datebuf))
    1297                 :        401 :         add_mhd_response_header (resp, "Last-Modified", datebuf);
    1298                 :            :     }
    1299                 :            : 
    1300                 :        401 :   add_mhd_response_header (resp, "Cache-Control", "public");
    1301                 :        401 : }
    1302                 :            : 
    1303                 :            : // quote all questionable characters of str for safe passage through a sh -c expansion.
    1304                 :            : static string
    1305                 :        280 : shell_escape(const string& str)
    1306                 :            : {
    1307                 :        280 :   string y;
    1308         [ +  + ]:      39438 :   for (auto&& x : str)
    1309                 :            :     {
    1310   [ +  +  +  + ]:      39158 :       if (! isalnum(x) && x != '/')
    1311         [ +  - ]:       3311 :         y += "\\";
    1312         [ +  - ]:      78316 :       y += x;
    1313                 :            :     }
    1314                 :        280 :   return y;
    1315                 :          0 : }
    1316                 :            : 
    1317                 :            : 
    1318                 :            : // PR25548: Perform POSIX / RFC3986 style path canonicalization on the input string.
    1319                 :            : //
    1320                 :            : // Namely:
    1321                 :            : //    //         ->   /
    1322                 :            : //    /foo/../   ->   /
    1323                 :            : //    /./        ->   /
    1324                 :            : //
    1325                 :            : // This mapping is done on dwarf-side source path names, which may
    1326                 :            : // include these constructs, so we can deal with debuginfod clients
    1327                 :            : // that accidentally canonicalize the paths.
    1328                 :            : //
    1329                 :            : // realpath(3) is close but not quite right, because it also resolves
    1330                 :            : // symbolic links.  Symlinks at the debuginfod server have nothing to
    1331                 :            : // do with the build-time symlinks, thus they must not be considered.
    1332                 :            : //
    1333                 :            : // see also curl Curl_dedotdotify() aka RFC3986, which we mostly follow here
    1334                 :            : // see also libc __realpath()
    1335                 :            : // see also llvm llvm::sys::path::remove_dots()
    1336                 :            : static string
    1337                 :       1776 : canon_pathname (const string& input)
    1338                 :            : {
    1339                 :       1776 :   string i = input; // 5.2.4 (1)
    1340                 :       1776 :   string o;
    1341                 :            : 
    1342                 :      16594 :   while (i.size() != 0)
    1343                 :            :     {
    1344                 :            :       // 5.2.4 (2) A
    1345   [ +  -  -  +  :      29636 :       if (i.substr(0,3) == "../")
                   -  + ]
    1346   [ #  #  #  # ]:          0 :         i = i.substr(3);
    1347   [ +  -  -  +  :      29636 :       else if(i.substr(0,2) == "./")
                   -  + ]
    1348   [ #  #  #  # ]:          0 :         i = i.substr(2);
    1349                 :            : 
    1350                 :            :       // 5.2.4 (2) B
    1351   [ +  -  -  +  :      29636 :       else if (i.substr(0,3) == "/./")
                   +  + ]
    1352   [ +  -  +  + ]:        311 :         i = i.substr(2);
    1353         [ -  + ]:      14627 :       else if (i == "/.")
    1354         [ #  # ]:          0 :         i = ""; // no need to handle "/." complete-path-segment case; we're dealing with file names
    1355                 :            : 
    1356                 :            :       // 5.2.4 (2) C
    1357   [ +  -  -  +  :      29254 :       else if (i.substr(0,4) == "/../") {
                   +  + ]
    1358   [ +  -  +  + ]:        236 :         i = i.substr(3);
    1359                 :        236 :         string::size_type sl = o.rfind("/");
    1360         [ +  - ]:        236 :         if (sl != string::npos)
    1361   [ +  -  +  - ]:        472 :           o = o.substr(0, sl);
    1362                 :            :         else
    1363         [ #  # ]:          0 :           o = "";
    1364         [ -  + ]:      14391 :       } else if (i == "/..")
    1365         [ #  # ]:          0 :         i = ""; // no need to handle "/.." complete-path-segment case; we're dealing with file names
    1366                 :            : 
    1367                 :            :       // 5.2.4 (2) D
    1368                 :            :       // no need to handle these cases; we're dealing with file names
    1369         [ -  + ]:      14391 :       else if (i == ".")
    1370         [ #  # ]:          0 :         i = "";
    1371         [ -  + ]:      14391 :       else if (i == "..")
    1372         [ #  # ]:          0 :         i = "";
    1373                 :            : 
    1374                 :            :       // POSIX special: map // to /
    1375   [ +  -  -  +  :      28782 :       else if (i.substr(0,2) == "//")
                   +  + ]
    1376   [ +  -  +  + ]:         76 :         i = i.substr(1);
    1377                 :            : 
    1378                 :            :       // 5.2.4 (2) E
    1379                 :            :       else {
    1380         [ -  + ]:      14323 :         string::size_type next_slash = i.find("/", (i[0]=='/' ? 1 : 0)); // skip first slash
    1381   [ +  -  +  + ]:      28646 :         o += i.substr(0, next_slash);
    1382         [ +  + ]:      14323 :         if (next_slash == string::npos)
    1383   [ +  -  +  + ]:      18370 :           i = "";
    1384                 :            :         else
    1385   [ +  -  +  +  :      23648 :           i = i.substr(next_slash);
                   -  - ]
    1386                 :            :       }
    1387                 :            :     }
    1388                 :            : 
    1389         [ +  - ]:       1776 :   return o;
    1390                 :       1776 : }
    1391                 :            : 
    1392                 :            : 
    1393                 :            : // Estimate available free space for a given filesystem via statfs(2).
    1394                 :            : // Return true if the free fraction is known to be smaller than the
    1395                 :            : // given minimum percentage.  Also update a related metric.
    1396                 :       1956 : bool statfs_free_enough_p(const string& path, const string& label, long minfree = 0)
    1397                 :            : {
    1398                 :       1956 :   struct statfs sfs;
    1399                 :       1956 :   int rc = statfs(path.c_str(), &sfs);
    1400         [ +  + ]:       1956 :   if (rc == 0)
    1401                 :            :     {
    1402                 :       1931 :       double s = (double) sfs.f_bavail / (double) sfs.f_blocks;
    1403   [ +  -  +  -  :       3862 :       set_metric("filesys_free_ratio","purpose",label, s);
             -  +  -  - ]
    1404                 :       1931 :       return ((s * 100.0) < minfree);
    1405                 :            :     }
    1406                 :            :   return false;
    1407                 :            : }
    1408                 :            : 
    1409                 :            : 
    1410                 :            : 
    1411                 :            : // A map-like class that owns a cache of file descriptors (indexed by
    1412                 :            : // file / content names).
    1413                 :            : //
    1414                 :            : // If only it could use fd's instead of file names ... but we can't
    1415                 :            : // dup(2) to create independent descriptors for the same unlinked
    1416                 :            : // files, so would have to use some goofy linux /proc/self/fd/%d
    1417                 :            : // hack such as the following
    1418                 :            : 
    1419                 :            : #if 0
    1420                 :            : int superdup(int fd)
    1421                 :            : {
    1422                 :            : #ifdef __linux__
    1423                 :            :   char *fdpath = NULL;
    1424                 :            :   int rc = asprintf(& fdpath, "/proc/self/fd/%d", fd);
    1425                 :            :   int newfd;
    1426                 :            :   if (rc >= 0)
    1427                 :            :     newfd = open(fdpath, O_RDONLY);
    1428                 :            :   else
    1429                 :            :     newfd = -1;
    1430                 :            :   free (fdpath);
    1431                 :            :   return newfd;
    1432                 :            : #else
    1433                 :            :   return -1;
    1434                 :            : #endif
    1435                 :            : }
    1436                 :            : #endif
    1437                 :            : 
    1438                 :            : class libarchive_fdcache
    1439                 :            : {
    1440                 :            : private:
    1441                 :            :   mutex fdcache_lock;
    1442                 :            : 
    1443                 :            :   struct fdcache_entry
    1444                 :            :   {
    1445                 :            :     string archive;
    1446                 :            :     string entry;
    1447                 :            :     string fd;
    1448                 :            :     double fd_size_mb; // slightly rounded up megabytes
    1449                 :            :   };
    1450                 :            :   deque<fdcache_entry> lru; // @head: most recently used
    1451                 :            :   long max_fds;
    1452                 :            :   deque<fdcache_entry> prefetch; // prefetched
    1453                 :            :   long max_mbs;
    1454                 :            :   long max_prefetch_mbs;
    1455                 :            :   long max_prefetch_fds;
    1456                 :            : 
    1457                 :            : public:
    1458                 :       1085 :   void set_metrics()
    1459                 :            :   {
    1460                 :       1085 :     double fdcache_mb = 0.0;
    1461                 :       1085 :     double prefetch_mb = 0.0;
    1462   [ +  +  +  + ]:       3940 :     for (auto i = lru.begin(); i < lru.end(); i++)
    1463                 :       1770 :       fdcache_mb += i->fd_size_mb;
    1464   [ +  +  +  + ]:       2747 :     for (auto j = prefetch.begin(); j < prefetch.end(); j++)
    1465                 :        577 :       prefetch_mb += j->fd_size_mb;
    1466         [ +  - ]:       1085 :     set_metric("fdcache_bytes", fdcache_mb*1024.0*1024.0);
    1467         [ +  - ]:       1085 :     set_metric("fdcache_count", lru.size());
    1468         [ +  - ]:       1085 :     set_metric("fdcache_prefetch_bytes", prefetch_mb*1024.0*1024.0);
    1469         [ +  - ]:       1085 :     set_metric("fdcache_prefetch_count", prefetch.size());
    1470                 :       1085 :   }
    1471                 :            : 
    1472                 :        611 :   void intern(const string& a, const string& b, string fd, off_t sz, bool front_p)
    1473                 :            :   {
    1474                 :        611 :     {
    1475                 :        611 :       unique_lock<mutex> lock(fdcache_lock);
    1476                 :            :       // nuke preexisting copy
    1477   [ +  +  +  + ]:       2402 :       for (auto i = lru.begin(); i < lru.end(); i++)
    1478                 :            :         {
    1479   [ +  +  -  + ]:        590 :           if (i->archive == a && i->entry == b)
    1480                 :            :             {
    1481                 :          0 :               unlink (i->fd.c_str());
    1482                 :          0 :               lru.erase(i);
    1483   [ #  #  #  #  :          0 :               inc_metric("fdcache_op_count","op","dequeue");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1484                 :          0 :               break; // must not continue iterating
    1485                 :            :             }
    1486                 :            :         }
    1487                 :            :       // nuke preexisting copy in prefetch
    1488   [ +  +  +  + ]:       1776 :       for (auto i = prefetch.begin(); i < prefetch.end(); i++)
    1489                 :            :         {
    1490   [ +  +  +  - ]:        277 :           if (i->archive == a && i->entry == b)
    1491                 :            :             {
    1492                 :          0 :               unlink (i->fd.c_str());
    1493                 :          0 :               prefetch.erase(i);
    1494   [ #  #  #  #  :          0 :               inc_metric("fdcache_op_count","op","prefetch_dequeue");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1495                 :          0 :               break; // must not continue iterating
    1496                 :            :             }
    1497                 :            :         }
    1498                 :        611 :       double mb = (sz+65535)/1048576.0; // round up to 64K block
    1499   [ +  -  +  -  :        611 :       fdcache_entry n = { a, b, fd, mb };
                   +  - ]
    1500         [ +  + ]:        611 :       if (front_p)
    1501                 :            :         {
    1502   [ +  -  +  -  :        666 :           inc_metric("fdcache_op_count","op","enqueue");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1503         [ +  - ]:        333 :           lru.push_front(n);
    1504                 :            :         }
    1505                 :            :       else
    1506                 :            :         {
    1507   [ +  -  +  -  :        556 :           inc_metric("fdcache_op_count","op","prefetch_enqueue");
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    1508         [ +  - ]:        278 :           prefetch.push_front(n);
    1509                 :            :         }
    1510         [ +  + ]:        611 :       if (verbose > 3)
    1511   [ +  -  +  - ]:       1788 :         obatched(clog) << "fdcache interned a=" << a << " b=" << b
    1512   [ +  -  +  -  :        596 :                        << " fd=" << fd << " mb=" << mb << " front=" << front_p << endl;
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
    1513                 :            :       
    1514         [ +  - ]:        611 :       set_metrics();
    1515                 :        611 :     }
    1516                 :            : 
    1517                 :            :     // NB: we age the cache at lookup time too
    1518   [ +  -  -  +  :        611 :     if (statfs_free_enough_p(tmpdir, "tmpdir", fdcache_mintmp))
                   -  + ]
    1519                 :            :       {
    1520   [ #  #  #  #  :          0 :         inc_metric("fdcache_op_count","op","emerg-flush");
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1521         [ #  # ]:          0 :         obatched(clog) << "fdcache emergency flush for filling tmpdir" << endl;
    1522                 :          0 :         this->limit(0, 0, 0, 0); // emergency flush
    1523                 :            :       }
    1524         [ +  + ]:        611 :     else if (front_p)
    1525                 :        333 :       this->limit(max_fds, max_mbs, max_prefetch_fds, max_prefetch_mbs); // age cache if required
    1526                 :        611 :   }
    1527                 :            : 
    1528                 :        370 :   int lookup(const string& a, const string& b)
    1529                 :            :   {
    1530                 :        370 :     int fd = -1;
    1531                 :        370 :     {
    1532                 :        370 :       unique_lock<mutex> lock(fdcache_lock);
    1533   [ +  +  +  + ]:       2000 :       for (auto i = lru.begin(); i < lru.end(); i++)
    1534                 :            :         {
    1535   [ +  +  +  + ]:        657 :           if (i->archive == a && i->entry == b)
    1536                 :            :             { // found it; move it to head of lru
    1537         [ +  - ]:         27 :               fdcache_entry n = *i;
    1538                 :         27 :               lru.erase(i); // invalidates i, so no more iteration!
    1539         [ +  - ]:         27 :               lru.push_front(n);
    1540   [ +  -  +  -  :         54 :               inc_metric("fdcache_op_count","op","requeue_front");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1541         [ +  - ]:         27 :               fd = open(n.fd.c_str(), O_RDONLY); 
    1542                 :         27 :               break;
    1543                 :         27 :             }
    1544                 :            :         }
    1545                 :            :       // Iterate through prefetch while fd == -1 to ensure that no duplication between lru and 
    1546                 :            :       // prefetch occurs.
    1547   [ +  +  +  +  :       1249 :       for ( auto i = prefetch.begin(); fd == -1 && i < prefetch.end(); ++i)
                   +  + ]
    1548                 :            :         {
    1549   [ +  +  +  + ]:        276 :           if (i->archive == a && i->entry == b)
    1550                 :            :             { // found it; take the entry from the prefetch deque to the lru deque, since it has now been accessed.
    1551         [ +  - ]:          8 :               fdcache_entry n = *i;
    1552                 :          8 :               prefetch.erase(i);
    1553         [ +  - ]:          8 :               lru.push_front(n);
    1554   [ +  -  +  -  :         16 :               inc_metric("fdcache_op_count","op","prefetch_access");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1555         [ +  - ]:          8 :               fd = open(n.fd.c_str(), O_RDONLY); 
    1556                 :          8 :               break;
    1557                 :          8 :             }
    1558                 :            :         }
    1559                 :          0 :     }
    1560                 :            : 
    1561   [ +  -  -  +  :        370 :     if (statfs_free_enough_p(tmpdir, "tmpdir", fdcache_mintmp))
                   -  + ]
    1562                 :            :       {
    1563   [ #  #  #  #  :          0 :         inc_metric("fdcache_op_count","op","emerg-flush");
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1564         [ #  # ]:          0 :         obatched(clog) << "fdcache emergency flush for filling tmpdir" << endl;
    1565                 :          0 :         this->limit(0, 0, 0, 0); // emergency flush
    1566                 :            :       }
    1567         [ +  + ]:        370 :     else if (fd >= 0)
    1568                 :         35 :       this->limit(max_fds, max_mbs, max_prefetch_fds, max_prefetch_mbs); // age cache if required
    1569                 :            : 
    1570                 :        370 :     return fd;
    1571                 :            :   }
    1572                 :            : 
    1573                 :        621 :   int probe(const string& a, const string& b) // just a cache residency check - don't modify LRU state, don't open
    1574                 :            :   {
    1575                 :        621 :     unique_lock<mutex> lock(fdcache_lock);
    1576   [ +  +  +  + ]:       2486 :     for (auto i = lru.begin(); i < lru.end(); i++)
    1577                 :            :       {
    1578   [ +  +  +  + ]:        636 :         if (i->archive == a && i->entry == b)
    1579                 :            :           {
    1580   [ +  -  +  -  :         28 :             inc_metric("fdcache_op_count","op","probe_hit");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1581                 :         14 :             return true;
    1582                 :            :           }
    1583                 :            :       }
    1584   [ +  +  +  + ]:       1764 :     for (auto i = prefetch.begin(); i < prefetch.end(); i++)
    1585                 :            :       {
    1586   [ +  +  +  - ]:        275 :         if (i->archive == a && i->entry == b)
    1587                 :            :           {
    1588   [ #  #  #  #  :          0 :             inc_metric("fdcache_op_count","op","prefetch_probe_hit");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1589                 :          0 :             return true;
    1590                 :            :           }
    1591                 :            :       }
    1592   [ +  -  +  -  :       1214 :     inc_metric("fdcache_op_count","op","probe_miss");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1593                 :        607 :     return false;
    1594                 :        621 :   }
    1595                 :            : 
    1596                 :          0 :   void clear(const string& a, const string& b)
    1597                 :            :   {
    1598                 :          0 :     unique_lock<mutex> lock(fdcache_lock);
    1599   [ #  #  #  # ]:          0 :     for (auto i = lru.begin(); i < lru.end(); i++)
    1600                 :            :       {
    1601   [ #  #  #  # ]:          0 :         if (i->archive == a && i->entry == b)
    1602                 :            :           { // found it; erase it from lru
    1603         [ #  # ]:          0 :             fdcache_entry n = *i;
    1604                 :          0 :             lru.erase(i); // invalidates i, so no more iteration!
    1605   [ #  #  #  #  :          0 :             inc_metric("fdcache_op_count","op","clear");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1606                 :          0 :             unlink (n.fd.c_str());
    1607         [ #  # ]:          0 :             set_metrics();
    1608                 :          0 :             return;
    1609                 :          0 :           }
    1610                 :            :       }
    1611   [ #  #  #  # ]:          0 :     for (auto i = prefetch.begin(); i < prefetch.end(); i++)
    1612                 :            :       {
    1613   [ #  #  #  # ]:          0 :         if (i->archive == a && i->entry == b)
    1614                 :            :           { // found it; erase it from lru
    1615         [ #  # ]:          0 :             fdcache_entry n = *i;
    1616                 :          0 :             prefetch.erase(i); // invalidates i, so no more iteration!
    1617   [ #  #  #  #  :          0 :             inc_metric("fdcache_op_count","op","prefetch_clear");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1618                 :          0 :             unlink (n.fd.c_str());
    1619         [ #  # ]:          0 :             set_metrics();
    1620                 :          0 :             return;
    1621                 :          0 :           }
    1622                 :            :       }
    1623                 :          0 :   }
    1624                 :            : 
    1625                 :        510 :   void limit(long maxfds, long maxmbs, long maxprefetchfds, long maxprefetchmbs , bool metrics_p = true)
    1626                 :            :   {
    1627   [ +  +  +  +  :        510 :     if (verbose > 3 && (this->max_fds != maxfds || this->max_mbs != maxmbs))
                   +  + ]
    1628   [ +  -  +  -  :        188 :       obatched(clog) << "fdcache limited to maxfds=" << maxfds << " maxmbs=" << maxmbs << endl;
             +  -  +  - ]
    1629                 :            : 
    1630                 :        510 :     unique_lock<mutex> lock(fdcache_lock);
    1631                 :        510 :     this->max_fds = maxfds;
    1632                 :        510 :     this->max_mbs = maxmbs;
    1633                 :        510 :     this->max_prefetch_fds = maxprefetchfds;
    1634                 :        510 :     this->max_prefetch_mbs = maxprefetchmbs;
    1635                 :        510 :     long total_fd = 0;
    1636                 :        510 :     double total_mb = 0.0;
    1637   [ +  +  +  + ]:       2714 :     for (auto i = lru.begin(); i < lru.end(); i++)
    1638                 :            :       {
    1639                 :            :         // accumulate totals from most recently used one going backward
    1640                 :       1119 :         total_fd ++;
    1641         [ +  + ]:       1119 :         total_mb += i->fd_size_mb;
    1642   [ +  +  +  + ]:       1119 :         if (total_fd > this->max_fds || total_mb > this->max_mbs)
    1643                 :            :           {
    1644                 :            :             // found the cut here point!
    1645                 :            : 
    1646   [ +  +  +  + ]:       1226 :             for (auto j = i; j < lru.end(); j++) // close all the fds from here on in
    1647                 :            :               {
    1648         [ +  + ]:        341 :                 if (verbose > 3)
    1649   [ +  -  +  - ]:       1005 :                   obatched(clog) << "fdcache evicted a=" << j->archive << " b=" << j->entry
    1650   [ +  -  +  -  :        335 :                                  << " fd=" << j->fd << " mb=" << j->fd_size_mb << endl;
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    1651         [ +  + ]:        341 :                 if (metrics_p)
    1652   [ +  -  +  -  :        562 :                   inc_metric("fdcache_op_count","op","evict");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1653                 :        341 :                 unlink (j->fd.c_str());
    1654                 :            :               }
    1655                 :            : 
    1656                 :        272 :             lru.erase(i, lru.end()); // erase the nodes generally
    1657                 :        272 :             break;
    1658                 :            :           }
    1659                 :            :       }
    1660                 :        510 :     total_fd = 0;
    1661                 :        510 :     total_mb = 0.0;
    1662   [ +  +  +  + ]:       1064 :     for(auto i = prefetch.begin(); i < prefetch.end(); i++){
    1663                 :            :       // accumulate totals from most recently used one going backward
    1664                 :        285 :         total_fd ++;
    1665         [ +  + ]:        285 :         total_mb += i->fd_size_mb;
    1666   [ +  +  +  + ]:        285 :         if (total_fd > this->max_prefetch_fds || total_mb > this->max_prefetch_mbs)
    1667                 :            :           {
    1668                 :            :             // found the cut here point!
    1669   [ +  +  +  + ]:       1066 :             for (auto j = i; j < prefetch.end(); j++) // close all the fds from here on in
    1670                 :            :               {
    1671         [ +  + ]:        270 :                 if (verbose > 3)
    1672   [ +  -  +  - ]:        783 :                   obatched(clog) << "fdcache evicted from prefetch a=" << j->archive << " b=" << j->entry
    1673   [ +  -  +  -  :        261 :                                  << " fd=" << j->fd << " mb=" << j->fd_size_mb << endl;
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    1674         [ +  + ]:        270 :                 if (metrics_p)
    1675   [ +  -  +  -  :        508 :                   inc_metric("fdcache_op_count","op","prefetch_evict");
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
    1676                 :        270 :                 unlink (j->fd.c_str());
    1677                 :            :               }
    1678                 :            : 
    1679                 :        263 :             prefetch.erase(i, prefetch.end()); // erase the nodes generally
    1680                 :        263 :             break;
    1681                 :            :           }
    1682                 :            :     }
    1683   [ +  +  +  - ]:        510 :     if (metrics_p) set_metrics();
    1684                 :        510 :   }
    1685                 :            : 
    1686                 :            : 
    1687                 :         36 :   ~libarchive_fdcache()
    1688                 :            :   {
    1689                 :            :     // unlink any fdcache entries in $TMPDIR
    1690                 :            :     // don't update metrics; those globals may be already destroyed
    1691                 :         36 :     limit(0, 0, 0, 0, false);
    1692                 :         36 :   }
    1693                 :            : };
    1694                 :            : static libarchive_fdcache fdcache;
    1695                 :            : 
    1696                 :            : /* Search ELF_FD for an ELF/DWARF section with name SECTION.
    1697                 :            :    If found copy the section to a temporary file and return
    1698                 :            :    its file descriptor, otherwise return -1.
    1699                 :            : 
    1700                 :            :    The temporary file's mtime will be set to PARENT_MTIME.
    1701                 :            :    B_SOURCE should be a description of the parent file suitable
    1702                 :            :    for printing to the log.  */
    1703                 :            : 
    1704                 :            : static int
    1705                 :          6 : extract_section (int elf_fd, int64_t parent_mtime,
    1706                 :            :                  const string& b_source, const string& section)
    1707                 :            : {
    1708                 :            :   /* Search the fdcache.  */
    1709                 :          6 :   struct stat fs;
    1710                 :          6 :   int fd = fdcache.lookup (b_source, section);
    1711         [ -  + ]:          6 :   if (fd >= 0)
    1712                 :            :     {
    1713         [ #  # ]:          0 :       if (fstat (fd, &fs) != 0)
    1714                 :            :         {
    1715         [ #  # ]:          0 :           if (verbose)
    1716         [ #  # ]:          0 :             obatched (clog) << "cannot fstate fdcache "
    1717   [ #  #  #  #  :          0 :                             << b_source << " " << section << endl;
                   #  # ]
    1718                 :          0 :           close (fd);
    1719                 :          0 :           return -1;
    1720                 :            :         }
    1721         [ #  # ]:          0 :       if ((int64_t) fs.st_mtime != parent_mtime)
    1722                 :            :         {
    1723         [ #  # ]:          0 :           if (verbose)
    1724         [ #  # ]:          0 :             obatched(clog) << "mtime mismatch for "
    1725   [ #  #  #  #  :          0 :                            << b_source << " " << section << endl;
                   #  # ]
    1726                 :          0 :           close (fd);
    1727                 :          0 :           return -1;
    1728                 :            :         }
    1729                 :            :       /* Success.  */
    1730                 :            :       return fd;
    1731                 :            :     }
    1732                 :            : 
    1733                 :          6 :   Elf *elf = elf_begin (elf_fd, ELF_C_READ_MMAP_PRIVATE, NULL);
    1734         [ -  + ]:          6 :   if (elf == NULL)
    1735                 :            :     return -1;
    1736                 :            : 
    1737                 :            :   /* Try to find the section and copy the contents into a separate file.  */
    1738                 :          6 :   try
    1739                 :            :     {
    1740                 :          6 :       size_t shstrndx;
    1741         [ +  - ]:          6 :       int rc = elf_getshdrstrndx (elf, &shstrndx);
    1742         [ -  + ]:          6 :       if (rc < 0)
    1743   [ #  #  #  # ]:          0 :         throw elfutils_exception (rc, "getshdrstrndx");
    1744                 :            : 
    1745                 :            :       Elf_Scn *scn = NULL;
    1746                 :        216 :       while (true)
    1747                 :            :         {
    1748         [ +  - ]:        111 :           scn = elf_nextscn (elf, scn);
    1749         [ +  - ]:        111 :           if (scn == NULL)
    1750                 :            :             break;
    1751                 :        111 :           GElf_Shdr shdr_storage;
    1752         [ +  - ]:        111 :           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
    1753         [ +  - ]:        111 :           if (shdr == NULL)
    1754                 :            :             break;
    1755                 :            : 
    1756         [ +  - ]:        111 :           const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
    1757         [ +  - ]:        111 :           if (scn_name == NULL)
    1758                 :            :             break;
    1759         [ +  + ]:        111 :           if (scn_name == section)
    1760                 :            :             {
    1761                 :          6 :               Elf_Data *data = NULL;
    1762                 :            : 
    1763                 :            :               /* We found the desired section.  */
    1764         [ +  - ]:          6 :               data = elf_rawdata (scn, NULL);
    1765         [ -  + ]:          6 :               if (data == NULL)
    1766   [ #  #  #  #  :          0 :                 throw elfutils_exception (elf_errno (), "elfraw_data");
                   #  # ]
    1767         [ +  + ]:          6 :               if (data->d_buf == NULL)
    1768                 :            :                 {
    1769   [ +  -  +  - ]:          4 :                   obatched(clog) << "section " << section
    1770   [ +  -  +  - ]:          2 :                                  << " is empty" << endl;
    1771                 :          2 :                   break;
    1772                 :            :                 }
    1773                 :            : 
    1774                 :            :               /* Create temporary file containing the section.  */
    1775                 :          4 :               char *tmppath = NULL;
    1776                 :          4 :               rc = asprintf (&tmppath, "%s/debuginfod.XXXXXX", tmpdir.c_str());
    1777         [ -  + ]:          4 :               if (rc < 0)
    1778   [ #  #  #  # ]:          0 :                 throw libc_exception (ENOMEM, "cannot allocate tmppath");
    1779                 :          4 :               defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    1780         [ +  - ]:          4 :               fd = mkstemp (tmppath);
    1781         [ -  + ]:          4 :               if (fd < 0)
    1782   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot create temporary file");
    1783         [ +  - ]:          4 :               ssize_t res = write_retry (fd, data->d_buf, data->d_size);
    1784   [ +  -  -  + ]:          4 :               if (res < 0 || (size_t) res != data->d_size)
    1785   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot write to temporary file");
    1786                 :            : 
    1787                 :            :               /* Set mtime to be the same as the parent file's mtime.  */
    1788                 :          4 :               struct timespec tvs[2];
    1789         [ -  + ]:          4 :               if (fstat (elf_fd, &fs) != 0)
    1790   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot fstat file");
    1791                 :            : 
    1792                 :          4 :               tvs[0].tv_sec = 0;
    1793                 :          4 :               tvs[0].tv_nsec = UTIME_OMIT;
    1794                 :          4 :               tvs[1] = fs.st_mtim;
    1795                 :          4 :               (void) futimens (fd, tvs);
    1796                 :            : 
    1797                 :            :               /* Add to fdcache.  */
    1798   [ +  -  +  - ]:          4 :               fdcache.intern (b_source, section, tmppath, data->d_size, true);
    1799                 :          4 :               break;
    1800                 :          6 :             }
    1801                 :        105 :         }
    1802                 :            :     }
    1803         [ -  - ]:          0 :   catch (const reportable_exception &e)
    1804                 :            :     {
    1805         [ -  - ]:          0 :       e.report (clog);
    1806         [ -  - ]:          0 :       close (fd);
    1807                 :          0 :       fd = -1;
    1808                 :          0 :     }
    1809                 :            : 
    1810                 :          6 :   elf_end (elf);
    1811                 :            :   return fd;
    1812                 :            : }
    1813                 :            : 
    1814                 :            : static struct MHD_Response*
    1815                 :         37 : handle_buildid_f_match (bool internal_req_t,
    1816                 :            :                         int64_t b_mtime,
    1817                 :            :                         const string& b_source0,
    1818                 :            :                         const string& section,
    1819                 :            :                         int *result_fd)
    1820                 :            : {
    1821                 :         37 :   (void) internal_req_t; // ignored
    1822                 :         37 :   int fd = open(b_source0.c_str(), O_RDONLY);
    1823         [ -  + ]:         37 :   if (fd < 0)
    1824   [ #  #  #  #  :          0 :     throw libc_exception (errno, string("open ") + b_source0);
             #  #  #  # ]
    1825                 :            : 
    1826                 :            :   // NB: use manual close(2) in error case instead of defer_dtor, because
    1827                 :            :   // in the normal case, we want to hand the fd over to libmicrohttpd for
    1828                 :            :   // file transfer.
    1829                 :            : 
    1830                 :         37 :   struct stat s;
    1831                 :         37 :   int rc = fstat(fd, &s);
    1832         [ -  + ]:         37 :   if (rc < 0)
    1833                 :            :     {
    1834                 :          0 :       close(fd);
    1835   [ #  #  #  #  :          0 :       throw libc_exception (errno, string("fstat ") + b_source0);
             #  #  #  # ]
    1836                 :            :     }
    1837                 :            : 
    1838         [ -  + ]:         37 :   if ((int64_t) s.st_mtime != b_mtime)
    1839                 :            :     {
    1840         [ #  # ]:          0 :       if (verbose)
    1841   [ #  #  #  # ]:          0 :         obatched(clog) << "mtime mismatch for " << b_source0 << endl;
    1842                 :          0 :       close(fd);
    1843                 :          0 :       return 0;
    1844                 :            :     }
    1845                 :            : 
    1846         [ +  + ]:         37 :   if (!section.empty ())
    1847                 :            :     {
    1848                 :          3 :       int scn_fd = extract_section (fd, s.st_mtime, b_source0, section);
    1849                 :          3 :       close (fd);
    1850                 :            : 
    1851         [ +  + ]:          3 :       if (scn_fd >= 0)
    1852                 :          2 :         fd = scn_fd;
    1853                 :            :       else
    1854                 :            :         {
    1855         [ +  - ]:          1 :           if (verbose)
    1856         [ +  - ]:          3 :             obatched (clog) << "cannot find section " << section
    1857   [ +  -  +  -  :          1 :                             << " for " << b_source0 << endl;
                   +  - ]
    1858                 :          1 :           return 0;
    1859                 :            :         }
    1860                 :            : 
    1861                 :          2 :       rc = fstat(fd, &s);
    1862         [ -  + ]:          2 :       if (rc < 0)
    1863                 :            :         {
    1864                 :          0 :           close (fd);
    1865   [ #  #  #  #  :          0 :           throw libc_exception (errno, string ("fstat ") + b_source0
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1866   [ #  #  #  #  :          0 :                                        + string (" ") + section);
          #  #  #  #  #  
                      # ]
    1867                 :            :         }
    1868                 :            :     }
    1869                 :            : 
    1870                 :         36 :   struct MHD_Response* r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
    1871   [ +  -  +  -  :         72 :   inc_metric ("http_responses_total","result","file");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    1872         [ -  + ]:         36 :   if (r == 0)
    1873                 :            :     {
    1874         [ #  # ]:          0 :       if (verbose)
    1875         [ #  # ]:          0 :         obatched(clog) << "cannot create fd-response for " << b_source0
    1876   [ #  #  #  #  :          0 :                        << " section=" << section << endl;
                   #  # ]
    1877                 :          0 :       close(fd);
    1878                 :            :     }
    1879                 :            :   else
    1880                 :            :     {
    1881                 :         36 :       std::string file = b_source0.substr(b_source0.find_last_of("/")+1, b_source0.length());
    1882         [ +  - ]:         36 :       add_mhd_response_header (r, "Content-Type", "application/octet-stream");
    1883         [ +  - ]:         36 :       add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
    1884         [ +  - ]:         36 :                                to_string(s.st_size).c_str());
    1885         [ +  - ]:         36 :       add_mhd_response_header (r, "X-DEBUGINFOD-FILE", file.c_str());
    1886         [ +  - ]:         36 :       add_mhd_last_modified (r, s.st_mtime);
    1887         [ +  - ]:         36 :       if (verbose > 1)
    1888   [ +  -  +  -  :         72 :         obatched(clog) << "serving file " << b_source0 << " section=" << section << endl;
          +  -  +  -  +  
                -  -  - ]
    1889                 :            :       /* libmicrohttpd will close it. */
    1890         [ +  - ]:         36 :       if (result_fd)
    1891                 :         36 :         *result_fd = fd;
    1892                 :         36 :     }
    1893                 :            : 
    1894                 :            :   return r;
    1895                 :            : }
    1896                 :            : 
    1897                 :            : // For security/portability reasons, many distro-package archives have
    1898                 :            : // a "./" in front of path names; others have nothing, others have
    1899                 :            : // "/".  Canonicalize them all to a single leading "/", with the
    1900                 :            : // assumption that this matches the dwarf-derived file names too.
    1901                 :       1751 : string canonicalized_archive_entry_pathname(struct archive_entry *e)
    1902                 :            : {
    1903                 :       1751 :   string fn = archive_entry_pathname(e);
    1904         [ -  + ]:       1751 :   if (fn.size() == 0)
    1905                 :          0 :     return fn;
    1906         [ -  + ]:       1751 :   if (fn[0] == '/')
    1907                 :          0 :     return fn;
    1908         [ +  + ]:       1751 :   if (fn[0] == '.')
    1909         [ +  - ]:       1148 :     return fn.substr(1);
    1910                 :            :   else
    1911   [ +  -  +  -  :       1206 :     return string("/")+fn;
                   -  - ]
    1912                 :       1751 : }
    1913                 :            : 
    1914                 :            : 
    1915                 :            : 
    1916                 :            : static struct MHD_Response*
    1917                 :        393 : handle_buildid_r_match (bool internal_req_p,
    1918                 :            :                         int64_t b_mtime,
    1919                 :            :                         const string& b_source0,
    1920                 :            :                         const string& b_source1,
    1921                 :            :                         const string& section,
    1922                 :            :                         int *result_fd)
    1923                 :            : {
    1924                 :        393 :   struct stat fs;
    1925                 :        393 :   int rc = stat (b_source0.c_str(), &fs);
    1926         [ +  + ]:        393 :   if (rc != 0)
    1927   [ +  -  +  -  :         58 :     throw libc_exception (errno, string("stat ") + b_source0);
             +  -  -  + ]
    1928                 :            : 
    1929         [ -  + ]:        364 :   if ((int64_t) fs.st_mtime != b_mtime)
    1930                 :            :     {
    1931         [ #  # ]:          0 :       if (verbose)
    1932   [ #  #  #  # ]:          0 :         obatched(clog) << "mtime mismatch for " << b_source0 << endl;
    1933                 :          0 :       return 0;
    1934                 :            :     }
    1935                 :            : 
    1936                 :            :   // check for a match in the fdcache first
    1937                 :        364 :   int fd = fdcache.lookup(b_source0, b_source1);
    1938         [ +  + ]:        364 :   while (fd >= 0) // got one!; NB: this is really an if() with a possible branch out to the end
    1939                 :            :     {
    1940                 :         35 :       rc = fstat(fd, &fs);
    1941         [ -  + ]:         35 :       if (rc < 0) // disappeared?
    1942                 :            :         {
    1943         [ #  # ]:          0 :           if (verbose)
    1944   [ #  #  #  # ]:          0 :             obatched(clog) << "cannot fstat fdcache " << b_source0 << endl;
    1945                 :          0 :           close(fd);
    1946                 :          0 :           fdcache.clear(b_source0, b_source1);
    1947                 :            :           break; // branch out of if "loop", to try new libarchive fetch attempt
    1948                 :            :         }
    1949                 :            : 
    1950         [ +  + ]:         35 :       if (!section.empty ())
    1951                 :            :         {
    1952   [ +  -  +  - ]:          1 :           int scn_fd = extract_section (fd, fs.st_mtime,
    1953   [ +  -  -  + ]:          2 :                                         b_source0 + ":" + b_source1,
    1954                 :            :                                         section);
    1955                 :          1 :           close (fd);
    1956         [ -  + ]:          1 :           if (scn_fd >= 0)
    1957                 :          0 :             fd = scn_fd;
    1958                 :            :           else
    1959                 :            :             {
    1960         [ +  - ]:          1 :               if (verbose)
    1961         [ +  - ]:          3 :                 obatched (clog) << "cannot find section " << section
    1962                 :            :                                 << " for archive " << b_source0
    1963   [ +  -  +  -  :          1 :                                 << " file " << b_source1 << endl;
          +  -  +  -  +  
                      - ]
    1964                 :          1 :               return 0;
    1965                 :            :             }
    1966                 :            : 
    1967                 :          0 :           rc = fstat(fd, &fs);
    1968         [ #  # ]:          0 :           if (rc < 0)
    1969                 :            :             {
    1970                 :          0 :               close (fd);
    1971   [ #  #  #  # ]:          0 :               throw libc_exception (errno,
    1972   [ #  #  #  #  :          0 :                 string ("fstat archive ") + b_source0 + string (" file ") + b_source1
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1973   [ #  #  #  #  :          0 :                 + string (" section ") + section);
          #  #  #  #  #  
                      # ]
    1974                 :            :             }
    1975                 :            :         }
    1976                 :            : 
    1977                 :         34 :       struct MHD_Response* r = MHD_create_response_from_fd (fs.st_size, fd);
    1978         [ -  + ]:         34 :       if (r == 0)
    1979                 :            :         {
    1980         [ #  # ]:          0 :           if (verbose)
    1981   [ #  #  #  # ]:          0 :             obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
    1982                 :          0 :           close(fd);
    1983                 :            :           break; // branch out of if "loop", to try new libarchive fetch attempt
    1984                 :            :         }
    1985                 :            : 
    1986   [ +  -  +  -  :         68 :       inc_metric ("http_responses_total","result","archive fdcache");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    1987                 :            : 
    1988                 :         34 :       add_mhd_response_header (r, "Content-Type", "application/octet-stream");
    1989         [ +  - ]:         34 :       add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
    1990                 :         34 :                                to_string(fs.st_size).c_str());
    1991                 :         34 :       add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE", b_source0.c_str());
    1992                 :         34 :       add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source1.c_str());
    1993                 :         34 :       add_mhd_last_modified (r, fs.st_mtime);
    1994         [ +  - ]:         34 :       if (verbose > 1)
    1995         [ +  - ]:        102 :         obatched(clog) << "serving fdcache archive " << b_source0
    1996                 :            :                        << " file " << b_source1
    1997   [ +  -  +  -  :         34 :                        << " section=" << section << endl;
          +  -  +  -  +  
                      - ]
    1998                 :            :       /* libmicrohttpd will close it. */
    1999         [ +  - ]:         34 :       if (result_fd)
    2000                 :         34 :         *result_fd = fd;
    2001                 :            :       return r;
    2002                 :            :       // NB: see, we never go around the 'loop' more than once
    2003                 :            :     }
    2004                 :            : 
    2005                 :            :   // no match ... grumble, must process the archive
    2006                 :        329 :   string archive_decoder = "/dev/null";
    2007   [ +  -  -  - ]:        329 :   string archive_extension = "";
    2008         [ +  + ]:        929 :   for (auto&& arch : scan_archives)
    2009         [ +  + ]:        600 :     if (string_endswith(b_source0, arch.first))
    2010                 :            :       {
    2011         [ +  - ]:        329 :         archive_extension = arch.first;
    2012         [ +  - ]:        929 :         archive_decoder = arch.second;
    2013                 :            :       }
    2014                 :        329 :   FILE* fp;
    2015                 :        329 :   defer_dtor<FILE*,int>::dtor_fn dfn;
    2016         [ +  + ]:        329 :   if (archive_decoder != "cat")
    2017                 :            :     {
    2018   [ +  -  +  -  :        528 :       string popen_cmd = archive_decoder + " " + shell_escape(b_source0);
          +  -  -  +  -  
                -  -  - ]
    2019         [ +  - ]:        264 :       fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
    2020                 :        264 :       dfn = pclose;
    2021         [ -  + ]:        264 :       if (fp == NULL)
    2022   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("popen ") + popen_cmd);
             #  #  #  # ]
    2023                 :        264 :     }
    2024                 :            :   else
    2025                 :            :     {
    2026         [ +  - ]:         65 :       fp = fopen (b_source0.c_str(), "r");
    2027                 :         65 :       dfn = fclose;
    2028         [ -  + ]:         65 :       if (fp == NULL)
    2029   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("fopen ") + b_source0);
             #  #  #  # ]
    2030                 :            :     }
    2031                 :        329 :   defer_dtor<FILE*,int> fp_closer (fp, dfn);
    2032                 :            : 
    2033                 :        329 :   struct archive *a;
    2034         [ +  - ]:        329 :   a = archive_read_new();
    2035         [ -  + ]:        329 :   if (a == NULL)
    2036   [ #  #  #  # ]:          0 :     throw archive_exception("cannot create archive reader");
    2037                 :        329 :   defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
    2038                 :            : 
    2039         [ +  - ]:        329 :   rc = archive_read_support_format_all(a);
    2040         [ -  + ]:        329 :   if (rc != ARCHIVE_OK)
    2041   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all format");
    2042         [ +  - ]:        329 :   rc = archive_read_support_filter_all(a);
    2043         [ -  + ]:        329 :   if (rc != ARCHIVE_OK)
    2044   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all filters");
    2045                 :            : 
    2046         [ +  - ]:        329 :   rc = archive_read_open_FILE (a, fp);
    2047         [ -  + ]:        329 :   if (rc != ARCHIVE_OK)
    2048                 :            :     {
    2049   [ #  #  #  #  :          0 :       obatched(clog) << "cannot open archive from pipe " << b_source0 << endl;
                   #  # ]
    2050   [ #  #  #  # ]:          0 :       throw archive_exception(a, "cannot open archive from pipe");
    2051                 :            :     }
    2052                 :            : 
    2053                 :            :   // archive traversal is in three stages, no, four stages:
    2054                 :            :   // 1) skip entries whose names do not match the requested one
    2055                 :            :   // 2) extract the matching entry name (set r = result)
    2056                 :            :   // 3) extract some number of prefetched entries (just into fdcache)
    2057                 :            :   // 4) abort any further processing
    2058                 :        329 :   struct MHD_Response* r = 0;                 // will set in stage 2
    2059         [ +  + ]:        329 :   unsigned prefetch_count =
    2060                 :            :     internal_req_p ? 0 : fdcache_prefetch;    // will decrement in stage 3
    2061                 :            : 
    2062         [ +  + ]:       5072 :   while(r == 0 || prefetch_count > 0) // stage 1, 2, or 3
    2063                 :            :     {
    2064         [ +  - ]:       5062 :       if (interrupted)
    2065                 :            :         break;
    2066                 :            : 
    2067                 :       5062 :       struct archive_entry *e;
    2068         [ +  - ]:       5062 :       rc = archive_read_next_header (a, &e);
    2069         [ +  + ]:       5062 :       if (rc != ARCHIVE_OK)
    2070                 :            :         break;
    2071                 :            : 
    2072   [ +  -  +  + ]:       4743 :       if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
    2073                 :       3329 :         continue;
    2074                 :            : 
    2075         [ +  - ]:       1414 :       string fn = canonicalized_archive_entry_pathname (e);
    2076   [ +  +  +  + ]:       1414 :       if ((r == 0) && (fn != b_source1)) // stage 1
    2077                 :        794 :         continue;
    2078                 :            : 
    2079   [ +  -  +  + ]:        620 :       if (fdcache.probe (b_source0, fn) && // skip if already interned
    2080         [ -  + ]:         13 :           fn != b_source1) // but only if we'd just be prefetching, PR29474
    2081                 :         13 :         continue;
    2082                 :            : 
    2083                 :            :       // extract this file to a temporary file
    2084                 :        607 :       char* tmppath = NULL;
    2085                 :        607 :       rc = asprintf (&tmppath, "%s/debuginfod.XXXXXX", tmpdir.c_str());
    2086         [ -  + ]:        607 :       if (rc < 0)
    2087   [ #  #  #  # ]:          0 :         throw libc_exception (ENOMEM, "cannot allocate tmppath");
    2088                 :        607 :       defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    2089         [ +  - ]:        607 :       fd = mkstemp (tmppath);
    2090         [ -  + ]:        607 :       if (fd < 0)
    2091   [ #  #  #  # ]:          0 :         throw libc_exception (errno, "cannot create temporary file");
    2092                 :            :       // NB: don't unlink (tmppath), as fdcache will take charge of it.
    2093                 :            : 
    2094                 :            :       // NB: this can take many uninterruptible seconds for a huge file
    2095         [ +  - ]:        607 :       rc = archive_read_data_into_fd (a, fd);
    2096         [ -  + ]:        607 :       if (rc != ARCHIVE_OK) // e.g. ENOSPC!
    2097                 :            :         {
    2098         [ #  # ]:          0 :           close (fd);
    2099                 :          0 :           unlink (tmppath);
    2100   [ #  #  #  # ]:          0 :           throw archive_exception(a, "cannot extract file");
    2101                 :            :         }
    2102                 :            : 
    2103                 :            :       // Set the mtime so the fdcache file mtimes, even prefetched ones,
    2104                 :            :       // propagate to future webapi clients.
    2105                 :        607 :       struct timespec tvs[2];
    2106                 :        607 :       tvs[0].tv_sec = 0;
    2107                 :        607 :       tvs[0].tv_nsec = UTIME_OMIT;
    2108         [ +  - ]:        607 :       tvs[1].tv_sec = archive_entry_mtime(e);
    2109         [ +  - ]:        607 :       tvs[1].tv_nsec = archive_entry_mtime_nsec(e);
    2110                 :        607 :       (void) futimens (fd, tvs);  /* best effort */
    2111                 :            : 
    2112         [ +  + ]:        607 :       if (r != 0) // stage 3
    2113                 :            :         {
    2114                 :            :           // NB: now we know we have a complete reusable file; make fdcache
    2115                 :            :           // responsible for unlinking it later.
    2116   [ +  -  +  -  :        278 :           fdcache.intern(b_source0, fn,
                   +  - ]
    2117                 :            :                          tmppath, archive_entry_size(e),
    2118                 :            :                          false); // prefetched ones go to the prefetch cache
    2119                 :        278 :           prefetch_count --;
    2120         [ +  - ]:        278 :           close (fd); // we're not saving this fd to make a mhd-response from!
    2121                 :        278 :           continue;
    2122                 :            :         }
    2123                 :            : 
    2124                 :            :       // NB: now we know we have a complete reusable file; make fdcache
    2125                 :            :       // responsible for unlinking it later.
    2126   [ +  -  +  -  :        329 :       fdcache.intern(b_source0, b_source1,
                   +  - ]
    2127                 :            :                      tmppath, archive_entry_size(e),
    2128                 :            :                      true); // requested ones go to the front of lru
    2129                 :            : 
    2130         [ +  + ]:        329 :       if (!section.empty ())
    2131                 :            :         {
    2132   [ +  -  +  - ]:          2 :           int scn_fd = extract_section (fd, b_mtime,
    2133   [ +  -  +  -  :          4 :                                         b_source0 + ":" + b_source1,
                   -  + ]
    2134                 :            :                                         section);
    2135         [ +  - ]:          2 :           close (fd);
    2136         [ +  - ]:          2 :           if (scn_fd >= 0)
    2137                 :          2 :             fd = scn_fd;
    2138                 :            :           else
    2139                 :            :             {
    2140         [ #  # ]:          0 :               if (verbose)
    2141   [ #  #  #  # ]:          0 :                 obatched (clog) << "cannot find section " << section
    2142                 :            :                                 << " for archive " << b_source0
    2143   [ #  #  #  #  :          0 :                                 << " file " << b_source1 << endl;
          #  #  #  #  #  
                      # ]
    2144                 :          0 :               return 0;
    2145                 :            :             }
    2146                 :            : 
    2147                 :          2 :           rc = fstat(fd, &fs);
    2148         [ -  + ]:          2 :           if (rc < 0)
    2149                 :            :             {
    2150         [ #  # ]:          0 :               close (fd);
    2151   [ #  #  #  # ]:          0 :               throw libc_exception (errno,
    2152   [ #  #  #  #  :          0 :                 string ("fstat ") + b_source0 + string (" ") + section);
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
    2153                 :            :             }
    2154         [ +  - ]:          2 :           r = MHD_create_response_from_fd (fs.st_size, fd);
    2155                 :            :         }
    2156                 :            :       else
    2157   [ +  -  +  - ]:        327 :         r = MHD_create_response_from_fd (archive_entry_size(e), fd);
    2158                 :            : 
    2159   [ +  -  +  -  :        658 :       inc_metric ("http_responses_total","result",archive_extension + " archive");
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    2160         [ -  + ]:        329 :       if (r == 0)
    2161                 :            :         {
    2162         [ #  # ]:          0 :           if (verbose)
    2163   [ #  #  #  #  :          0 :             obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
                   #  # ]
    2164         [ #  # ]:          0 :           close(fd);
    2165                 :          0 :           break; // assume no chance of better luck around another iteration; no other copies of same file
    2166                 :            :         }
    2167                 :            :       else
    2168                 :            :         {
    2169         [ +  - ]:        329 :           std::string file = b_source1.substr(b_source1.find_last_of("/")+1, b_source1.length());
    2170         [ +  - ]:        329 :           add_mhd_response_header (r, "Content-Type",
    2171                 :            :                                    "application/octet-stream");
    2172         [ +  - ]:        329 :           add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
    2173   [ +  -  +  - ]:        329 :                                    to_string(archive_entry_size(e)).c_str());
    2174         [ +  - ]:        329 :           add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE",
    2175                 :            :                                    b_source0.c_str());
    2176         [ +  - ]:        329 :           add_mhd_response_header (r, "X-DEBUGINFOD-FILE", file.c_str());
    2177   [ +  -  +  - ]:        329 :           add_mhd_last_modified (r, archive_entry_mtime(e));
    2178         [ +  - ]:        329 :           if (verbose > 1)
    2179   [ +  -  +  -  :        987 :             obatched(clog) << "serving archive " << b_source0
                   -  - ]
    2180                 :            :                            << " file " << b_source1
    2181   [ +  -  +  -  :        329 :                            << " section=" << section << endl;
          +  -  +  -  +  
                      - ]
    2182                 :            :           /* libmicrohttpd will close it. */
    2183         [ +  - ]:        329 :           if (result_fd)
    2184                 :        329 :             *result_fd = fd;
    2185         [ +  + ]:        329 :           continue;
    2186                 :        329 :         }
    2187   [ -  -  -  -  :       6476 :     }
                   +  + ]
    2188                 :            : 
    2189                 :            :   // XXX: rpm/file not found: delete this R entry?
    2190                 :            :   return r;
    2191   [ -  +  +  + ]:        693 : }
    2192                 :            : 
    2193                 :            : 
    2194                 :            : static struct MHD_Response*
    2195                 :        430 : handle_buildid_match (bool internal_req_p,
    2196                 :            :                       int64_t b_mtime,
    2197                 :            :                       const string& b_stype,
    2198                 :            :                       const string& b_source0,
    2199                 :            :                       const string& b_source1,
    2200                 :            :                       const string& section,
    2201                 :            :                       int *result_fd)
    2202                 :            : {
    2203                 :        430 :   try
    2204                 :            :     {
    2205         [ +  + ]:        430 :       if (b_stype == "F")
    2206         [ +  - ]:         37 :         return handle_buildid_f_match(internal_req_p, b_mtime, b_source0,
    2207                 :            :                                       section, result_fd);
    2208         [ +  - ]:        393 :       else if (b_stype == "R")
    2209         [ +  + ]:        393 :         return handle_buildid_r_match(internal_req_p, b_mtime, b_source0,
    2210                 :            :                                       b_source1, section, result_fd);
    2211                 :            :     }
    2212         [ -  + ]:         29 :   catch (const reportable_exception &e)
    2213                 :            :     {
    2214         [ +  - ]:         29 :       e.report(clog);
    2215                 :            :       // Report but swallow libc etc. errors here; let the caller
    2216                 :            :       // iterate to other matches of the content.
    2217                 :         29 :     }
    2218                 :            : 
    2219                 :            :   return 0;
    2220                 :            : }
    2221                 :            : 
    2222                 :            : 
    2223                 :            : static int
    2224                 :       1617 : debuginfod_find_progress (debuginfod_client *, long a, long b)
    2225                 :            : {
    2226         [ -  + ]:       1617 :   if (verbose > 4)
    2227   [ #  #  #  #  :          0 :     obatched(clog) << "federated debuginfod progress=" << a << "/" << b << endl;
             #  #  #  # ]
    2228                 :            : 
    2229                 :       1617 :   return interrupted;
    2230                 :            : }
    2231                 :            : 
    2232                 :            : 
    2233                 :            : // a little lru pool of debuginfod_client*s for reuse between query threads
    2234                 :            : 
    2235                 :            : mutex dc_pool_lock;
    2236                 :            : deque<debuginfod_client*> dc_pool;
    2237                 :            : 
    2238                 :        310 : debuginfod_client* debuginfod_pool_begin()
    2239                 :            : {
    2240                 :        310 :   unique_lock<mutex> lock(dc_pool_lock);
    2241         [ +  + ]:        310 :   if (dc_pool.size() > 0)
    2242                 :            :     {
    2243   [ +  -  +  -  :        594 :       inc_metric("dc_pool_op_count","op","begin-reuse");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2244                 :        297 :       debuginfod_client *c = dc_pool.front();
    2245                 :        297 :       dc_pool.pop_front();
    2246                 :        297 :       return c;
    2247                 :            :     }
    2248   [ +  -  +  -  :         26 :   inc_metric("dc_pool_op_count","op","begin-new");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2249         [ +  - ]:         13 :   return debuginfod_begin();
    2250                 :        310 : }
    2251                 :            : 
    2252                 :            : 
    2253                 :         71 : void debuginfod_pool_groom()
    2254                 :            : {
    2255                 :         71 :   unique_lock<mutex> lock(dc_pool_lock);
    2256         [ +  + ]:         84 :   while (dc_pool.size() > 0)
    2257                 :            :     {
    2258   [ +  -  +  -  :         26 :       inc_metric("dc_pool_op_count","op","end");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2259         [ +  - ]:         13 :       debuginfod_end(dc_pool.front());
    2260                 :         13 :       dc_pool.pop_front();
    2261                 :            :     }
    2262                 :         71 : }
    2263                 :            : 
    2264                 :            : 
    2265                 :        310 : void debuginfod_pool_end(debuginfod_client* c)
    2266                 :            : {
    2267                 :        310 :   unique_lock<mutex> lock(dc_pool_lock);
    2268   [ +  -  +  -  :        620 :   inc_metric("dc_pool_op_count","op","end-save");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2269         [ +  - ]:        310 :   dc_pool.push_front(c); // accelerate reuse, vs. push_back
    2270                 :        310 : }
    2271                 :            : 
    2272                 :            : 
    2273                 :            : static struct MHD_Response*
    2274                 :        712 : handle_buildid (MHD_Connection* conn,
    2275                 :            :                 const string& buildid /* unsafe */,
    2276                 :            :                 string& artifacttype /* unsafe, cleanse on exception/return */,
    2277                 :            :                 const string& suffix /* unsafe */,
    2278                 :            :                 int *result_fd)
    2279                 :            : {
    2280                 :            :   // validate artifacttype
    2281                 :        712 :   string atype_code;
    2282   [ +  +  +  - ]:        712 :   if (artifacttype == "debuginfo") atype_code = "D";
    2283   [ +  +  +  - ]:        343 :   else if (artifacttype == "executable") atype_code = "E";
    2284   [ +  +  +  - ]:         34 :   else if (artifacttype == "source") atype_code = "S";
    2285   [ +  +  +  - ]:          6 :   else if (artifacttype == "section") atype_code = "I";
    2286                 :            :   else {
    2287         [ +  - ]:          2 :     artifacttype = "invalid"; // PR28242 ensure http_resposes metrics don't propagate unclean user data 
    2288   [ +  -  +  - ]:          6 :     throw reportable_exception("invalid artifacttype");
    2289                 :            :   }
    2290                 :            : 
    2291         [ +  + ]:        710 :   if (conn != 0)
    2292   [ +  -  +  -  :       1691 :     inc_metric("http_requests_total", "type", artifacttype);
          +  -  -  +  -  
                -  -  + ]
    2293                 :            : 
    2294                 :        710 :   string section;
    2295         [ +  + ]:        710 :   if (atype_code == "I")
    2296                 :            :     {
    2297         [ -  + ]:          4 :       if (suffix.size () < 2)
    2298   [ #  #  #  # ]:          0 :         throw reportable_exception ("invalid section suffix");
    2299                 :            : 
    2300                 :            :       // Remove leading '/'
    2301   [ +  -  -  + ]:          4 :       section = suffix.substr(1);
    2302                 :            :     }
    2303                 :            : 
    2304   [ +  +  -  + ]:        738 :   if (atype_code == "S" && suffix == "")
    2305   [ #  #  #  # ]:          0 :      throw reportable_exception("invalid source suffix");
    2306                 :            : 
    2307                 :            :   // validate buildid
    2308         [ +  + ]:        710 :   if ((buildid.size() < 2) || // not empty
    2309   [ +  +  +  -  :       1419 :       (buildid.size() % 2) || // even number
                   +  - ]
    2310                 :        709 :       (buildid.find_first_not_of("0123456789abcdef") != string::npos)) // pure tasty lowercase hex
    2311   [ +  -  -  + ]:          2 :     throw reportable_exception("invalid buildid");
    2312                 :            : 
    2313         [ +  - ]:        709 :   if (verbose > 1)
    2314   [ +  -  +  - ]:       2127 :     obatched(clog) << "searching for buildid=" << buildid << " artifacttype=" << artifacttype
    2315   [ +  -  +  -  :        709 :          << " suffix=" << suffix << endl;
          +  -  +  -  +  
                      - ]
    2316                 :            : 
    2317                 :            :   // If invoked from the scanner threads, use the scanners' read-write
    2318                 :            :   // connection.  Otherwise use the web query threads' read-only connection.
    2319         [ +  + ]:        709 :   sqlite3 *thisdb = (conn == 0) ? db : dbq;
    2320                 :            : 
    2321                 :        709 :   sqlite_ps *pp = 0;
    2322                 :            : 
    2323         [ +  + ]:        709 :   if (atype_code == "D")
    2324                 :            :     {
    2325         [ -  + ]:        369 :       pp = new sqlite_ps (thisdb, "mhd-query-d",
    2326                 :            :                           "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_d where buildid = ? "
    2327   [ +  -  +  -  :        738 :                           "order by mtime desc");
          +  -  +  -  +  
                -  -  - ]
    2328         [ +  - ]:        369 :       pp->reset();
    2329         [ +  - ]:        369 :       pp->bind(1, buildid);
    2330                 :            :     }
    2331         [ +  + ]:        340 :   else if (atype_code == "E")
    2332                 :            :     {
    2333         [ -  + ]:        308 :       pp = new sqlite_ps (thisdb, "mhd-query-e",
    2334                 :            :                           "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_e where buildid = ? "
    2335   [ +  -  +  -  :        616 :                           "order by mtime desc");
          +  -  +  -  +  
                -  -  - ]
    2336         [ +  - ]:        308 :       pp->reset();
    2337         [ +  - ]:        308 :       pp->bind(1, buildid);
    2338                 :            :     }
    2339         [ +  + ]:         32 :   else if (atype_code == "S")
    2340                 :            :     {
    2341                 :            :       // PR25548
    2342                 :            :       // Incoming source queries may come in with either dwarf-level OR canonicalized paths.
    2343                 :            :       // We let the query pass with either one.
    2344                 :            : 
    2345         [ -  + ]:         28 :       pp = new sqlite_ps (thisdb, "mhd-query-s",
    2346                 :            :                           "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_s where buildid = ? and artifactsrc in (?,?) "
    2347   [ +  -  +  -  :         56 :                           "order by sharedprefix(source0,source0ref) desc, mtime desc");
          +  -  +  -  +  
                -  -  - ]
    2348         [ +  - ]:         28 :       pp->reset();
    2349         [ +  - ]:         28 :       pp->bind(1, buildid);
    2350                 :            :       // NB: we don't store the non-canonicalized path names any more, but old databases
    2351                 :            :       // might have them (and no canon ones), so we keep searching for both.
    2352         [ +  - ]:         28 :       pp->bind(2, suffix);
    2353   [ +  -  +  -  :        365 :       pp->bind(3, canon_pathname(suffix));
                   -  + ]
    2354                 :            :     }
    2355         [ +  - ]:          4 :   else if (atype_code == "I")
    2356                 :            :     {
    2357         [ -  + ]:          4 :       pp = new sqlite_ps (thisdb, "mhd-query-i",
    2358                 :            :         "select mtime, sourcetype, source0, source1, 1 as debug_p from " BUILDIDS "_query_d where buildid = ? "
    2359                 :            :         "union all "
    2360                 :            :         "select mtime, sourcetype, source0, source1, 0 as debug_p from " BUILDIDS "_query_e where buildid = ? "
    2361   [ +  -  +  -  :          8 :         "order by debug_p desc, mtime desc");
          +  -  +  -  +  
                -  -  - ]
    2362         [ +  - ]:          4 :       pp->reset();
    2363         [ +  - ]:          4 :       pp->bind(1, buildid);
    2364         [ +  - ]:          4 :       pp->bind(2, buildid);
    2365                 :            :     }
    2366                 :        709 :   unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
    2367                 :            : 
    2368                 :        709 :   bool do_upstream_section_query = true;
    2369                 :            : 
    2370                 :            :   // consume all the rows
    2371                 :        740 :   while (1)
    2372                 :            :     {
    2373         [ +  - ]:        740 :       int rc = pp->step();
    2374         [ +  + ]:        740 :       if (rc == SQLITE_DONE) break;
    2375         [ -  + ]:        430 :       if (rc != SQLITE_ROW)
    2376   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    2377                 :            : 
    2378         [ +  - ]:        430 :       int64_t b_mtime = sqlite3_column_int64 (*pp, 0);
    2379   [ +  -  -  +  :        430 :       string b_stype = string((const char*) sqlite3_column_text (*pp, 1) ?: ""); /* by DDL may not be NULL */
                   +  - ]
    2380   [ +  -  -  +  :        430 :       string b_source0 = string((const char*) sqlite3_column_text (*pp, 2) ?: ""); /* may be NULL */
             +  -  -  - ]
    2381   [ +  -  +  +  :        467 :       string b_source1 = string((const char*) sqlite3_column_text (*pp, 3) ?: ""); /* may be NULL */
             +  -  -  - ]
    2382                 :            : 
    2383         [ +  - ]:        430 :       if (verbose > 1)
    2384   [ +  -  +  -  :       1290 :         obatched(clog) << "found mtime=" << b_mtime << " stype=" << b_stype
                   -  - ]
    2385   [ +  -  +  -  :        430 :              << " source0=" << b_source0 << " source1=" << b_source1 << endl;
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    2386                 :            : 
    2387                 :            :       // Try accessing the located match.
    2388                 :            :       // XXX: in case of multiple matches, attempt them in parallel?
    2389         [ +  - ]:        430 :       auto r = handle_buildid_match (conn ? false : true,
    2390                 :            :                                      b_mtime, b_stype, b_source0, b_source1,
    2391                 :            :                                      section, result_fd);
    2392         [ +  + ]:        430 :       if (r)
    2393         [ +  + ]:        399 :         return r;
    2394                 :            : 
    2395                 :            :       // If a debuginfo file matching BUILDID was found but didn't contain
    2396                 :            :       // the desired section, then the section should not exist.  Don't
    2397                 :            :       // bother querying upstream servers.
    2398   [ +  +  +  -  :         31 :       if (!section.empty () && (sqlite3_column_int (*pp, 4) == 1))
                   -  + ]
    2399                 :            :         {
    2400                 :          2 :           struct stat st;
    2401                 :            : 
    2402                 :            :           // For "F" sourcetype, check if the debuginfo exists. For "R"
    2403                 :            :           // sourcetype, check if the debuginfo was interned into the fdcache.
    2404         [ -  + ]:          3 :           if ((b_stype == "F" && (stat (b_source0.c_str (), &st) == 0))
    2405   [ +  +  +  -  :          3 :               || (b_stype == "R" && fdcache.probe (b_source0, b_source1)))
             +  -  -  + ]
    2406                 :            :             do_upstream_section_query = false;
    2407                 :            :         }
    2408   [ +  -  -  +  :        860 :     }
             +  -  -  + ]
    2409         [ +  - ]:        310 :   pp->reset();
    2410                 :            : 
    2411         [ -  + ]:        310 :   if (!do_upstream_section_query)
    2412   [ #  #  #  # ]:          0 :     throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
    2413                 :            : 
    2414                 :            :   // We couldn't find it in the database.  Last ditch effort
    2415                 :            :   // is to defer to other debuginfo servers.
    2416                 :            : 
    2417                 :        310 :   int fd = -1;
    2418         [ +  - ]:        310 :   debuginfod_client *client = debuginfod_pool_begin ();
    2419         [ -  + ]:        310 :   if (client == NULL)
    2420   [ #  #  #  # ]:          0 :     throw libc_exception(errno, "debuginfod client pool alloc");
    2421                 :        310 :   defer_dtor<debuginfod_client*,void> client_closer (client, debuginfod_pool_end);
    2422                 :            :   
    2423         [ +  - ]:        310 :   debuginfod_set_progressfn (client, & debuginfod_find_progress);
    2424                 :            : 
    2425         [ +  - ]:        310 :   if (conn)
    2426                 :            :     {
    2427                 :            :       // Transcribe incoming User-Agent:
    2428   [ +  -  -  +  :        310 :       string ua = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
                   +  - ]
    2429   [ +  -  +  -  :        312 :       string ua_complete = string("User-Agent: ") + ua;
                   +  - ]
    2430         [ +  - ]:        310 :       debuginfod_add_http_header (client, ua_complete.c_str());
    2431                 :            :       
    2432                 :            :       // Compute larger XFF:, for avoiding info loss during
    2433                 :            :       // federation, and for future cyclicity detection.
    2434   [ +  -  +  +  :        613 :       string xff = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
             +  -  +  - ]
    2435         [ +  + ]:        310 :       if (xff != "")
    2436   [ +  -  -  + ]:         18 :         xff += string(", "); // comma separated list
    2437                 :            :       
    2438                 :        310 :       unsigned int xff_count = 0;
    2439         [ +  + ]:        430 :       for (auto&& i : xff){
    2440         [ +  + ]:        120 :         if (i == ',') xff_count++;
    2441                 :            :       }
    2442                 :            : 
    2443                 :            :       // if X-Forwarded-For: exceeds N hops,
    2444                 :            :       // do not delegate a local lookup miss to upstream debuginfods.
    2445         [ +  + ]:        310 :       if (xff_count >= forwarded_ttl_limit)
    2446   [ +  -  +  - ]:          4 :         throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found, --forwared-ttl-limit reached \
    2447                 :          4 : and will not query the upstream servers");
    2448                 :            : 
    2449                 :            :       // Compute the client's numeric IP address only - so can't merge with conninfo()
    2450         [ +  - ]:        308 :       const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
    2451                 :            :                                                                    MHD_CONNECTION_INFO_CLIENT_ADDRESS);
    2452         [ +  - ]:        308 :       struct sockaddr *so = u ? u->client_addr : 0;
    2453                 :        308 :       char hostname[256] = ""; // RFC1035
    2454   [ +  -  -  + ]:        308 :       if (so && so->sa_family == AF_INET) {
    2455         [ #  # ]:          0 :         (void) getnameinfo (so, sizeof (struct sockaddr_in), hostname, sizeof (hostname), NULL, 0,
    2456                 :            :                             NI_NUMERICHOST);
    2457         [ +  - ]:        308 :       } else if (so && so->sa_family == AF_INET6) {
    2458                 :        308 :         struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
    2459   [ +  -  +  -  :        308 :         if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
                   -  + ]
    2460                 :        308 :           struct sockaddr_in addr4;
    2461         [ +  - ]:        308 :           memset (&addr4, 0, sizeof(addr4));
    2462                 :        308 :           addr4.sin_family = AF_INET;
    2463                 :        308 :           addr4.sin_port = addr6->sin6_port;
    2464         [ +  - ]:        308 :           memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
    2465         [ +  - ]:        308 :           (void) getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
    2466                 :            :                               hostname, sizeof (hostname), NULL, 0,
    2467                 :            :                               NI_NUMERICHOST);
    2468                 :            :         } else {
    2469         [ #  # ]:          0 :           (void) getnameinfo (so, sizeof (struct sockaddr_in6), hostname, sizeof (hostname), NULL, 0,
    2470                 :            :                               NI_NUMERICHOST);
    2471                 :            :         }
    2472                 :            :       }
    2473                 :            :           
    2474   [ +  -  +  -  :        618 :       string xff_complete = string("X-Forwarded-For: ")+xff+string(hostname);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  + ]
    2475         [ +  - ]:        308 :       debuginfod_add_http_header (client, xff_complete.c_str());
    2476   [ +  +  +  -  :        650 :     }
                   +  + ]
    2477                 :            :   
    2478         [ +  + ]:        308 :   if (artifacttype == "debuginfo")
    2479         [ +  - ]:         34 :     fd = debuginfod_find_debuginfo (client,
    2480         [ +  - ]:         34 :                                     (const unsigned char*) buildid.c_str(),
    2481                 :            :                                     0, NULL);
    2482         [ +  + ]:        274 :   else if (artifacttype == "executable")
    2483         [ +  - ]:        273 :     fd = debuginfod_find_executable (client,
    2484         [ +  - ]:        273 :                                      (const unsigned char*) buildid.c_str(),
    2485                 :            :                                      0, NULL);
    2486         [ +  - ]:          1 :   else if (artifacttype == "source")
    2487         [ +  - ]:          1 :     fd = debuginfod_find_source (client,
    2488         [ +  - ]:          1 :                                  (const unsigned char*) buildid.c_str(),
    2489                 :            :                                  0, suffix.c_str(), NULL);
    2490         [ #  # ]:          0 :   else if (artifacttype == "section")
    2491         [ #  # ]:          0 :     fd = debuginfod_find_section (client,
    2492         [ #  # ]:          0 :                                   (const unsigned char*) buildid.c_str(),
    2493                 :            :                                   0, section.c_str(), NULL);
    2494                 :            :   
    2495         [ +  + ]:        308 :   if (fd >= 0)
    2496                 :            :     {
    2497         [ +  - ]:          2 :       if (conn != 0)
    2498   [ +  -  +  -  :        312 :         inc_metric ("http_responses_total","result","upstream");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2499                 :          2 :       struct stat s;
    2500                 :          2 :       int rc = fstat (fd, &s);
    2501         [ +  - ]:          2 :       if (rc == 0)
    2502                 :            :         {
    2503         [ +  - ]:          2 :           auto r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
    2504         [ +  - ]:          2 :           if (r)
    2505                 :            :             {
    2506         [ +  - ]:          2 :               add_mhd_response_header (r, "Content-Type",
    2507                 :            :                                        "application/octet-stream");
    2508                 :            :               // Copy the incoming headers
    2509         [ +  - ]:          2 :               const char * hdrs = debuginfod_get_headers(client);
    2510         [ +  - ]:          2 :               string header_dup;
    2511         [ +  - ]:          2 :               if (hdrs)
    2512   [ +  -  -  + ]:          2 :                 header_dup = string(hdrs);
    2513                 :            :               // Parse the "header: value\n" lines into (h,v) tuples and pass on
    2514                 :         10 :               while(1)
    2515                 :            :                 {
    2516                 :          6 :                   size_t newline = header_dup.find('\n');
    2517         [ +  + ]:          6 :                   if (newline == string::npos) break;
    2518                 :          4 :                   size_t colon = header_dup.find(':');
    2519         [ +  - ]:          4 :                   if (colon == string::npos) break;
    2520         [ +  - ]:          4 :                   string header = header_dup.substr(0,colon);
    2521         [ +  - ]:          4 :                   string value = header_dup.substr(colon+1,newline-colon-1);
    2522                 :            :                   // strip leading spaces from value
    2523                 :          4 :                   size_t nonspace = value.find_first_not_of(" ");
    2524         [ +  - ]:          4 :                   if (nonspace != string::npos)
    2525   [ +  -  -  + ]:          4 :                     value = value.substr(nonspace);
    2526         [ +  - ]:          4 :                   add_mhd_response_header(r, header.c_str(), value.c_str());
    2527   [ +  -  +  +  :          6 :                   header_dup = header_dup.substr(newline+1);
             -  +  -  - ]
    2528         [ +  - ]:          8 :                 }
    2529                 :            : 
    2530         [ +  - ]:          2 :               add_mhd_last_modified (r, s.st_mtime);
    2531         [ +  - ]:          2 :               if (verbose > 1)
    2532   [ +  -  +  -  :          4 :                 obatched(clog) << "serving file from upstream debuginfod/cache" << endl;
                   -  - ]
    2533         [ +  - ]:          2 :               if (result_fd)
    2534                 :          2 :                 *result_fd = fd;
    2535         [ +  - ]:          2 :               return r; // NB: don't close fd; libmicrohttpd will
    2536                 :          2 :             }
    2537                 :            :         }
    2538         [ #  # ]:          0 :       close (fd);
    2539                 :            :     }
    2540                 :            :   else
    2541         [ +  + ]:        306 :     switch(fd)
    2542                 :            :       {
    2543                 :            :       case -ENOSYS:
    2544                 :            :         break;
    2545                 :            :       case -ENOENT:
    2546                 :            :         break;
    2547                 :        266 :       default: // some more tricky error
    2548   [ +  -  +  - ]:        532 :         throw libc_exception(-fd, "upstream debuginfod query failed");
    2549                 :            :       }
    2550                 :            : 
    2551   [ +  -  -  + ]:         80 :   throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
    2552   [ -  +  -  + ]:       1018 : }
    2553                 :            : 
    2554                 :            : 
    2555                 :            : ////////////////////////////////////////////////////////////////////////
    2556                 :            : 
    2557                 :            : static map<string,double> metrics; // arbitrary data for /metrics query
    2558                 :            : // NB: store int64_t since all our metrics are integers; prometheus accepts double
    2559                 :            : static mutex metrics_lock;
    2560                 :            : // NB: these objects get released during the process exit via global dtors
    2561                 :            : // do not call them from within other global dtors
    2562                 :            : 
    2563                 :            : // utility function for assembling prometheus-compatible
    2564                 :            : // name="escaped-value" strings
    2565                 :            : // https://prometheus.io/docs/instrumenting/exposition_formats/
    2566                 :            : static string
    2567                 :     128186 : metric_label(const string& name, const string& value)
    2568                 :            : {
    2569                 :     128186 :   string x = name + "=\"";
    2570         [ +  + ]:    2061756 :   for (auto&& c : value)
    2571   [ -  -  -  + ]:    1933617 :     switch(c)
    2572                 :            :       {
    2573         [ #  # ]:          0 :       case '\\': x += "\\\\"; break;
    2574         [ #  # ]:          0 :       case '\"': x += "\\\""; break;
    2575         [ #  # ]:          0 :       case '\n': x += "\\n"; break;
    2576         [ +  - ]:    3867193 :       default: x += c; break;
    2577                 :            :       }
    2578         [ +  - ]:     128139 :   x += "\"";
    2579                 :     128151 :   return x;
    2580                 :          0 : }
    2581                 :            : 
    2582                 :            : 
    2583                 :            : // add prometheus-format metric name + label tuple (if any) + value
    2584                 :            : 
    2585                 :            : static void
    2586                 :       4412 : set_metric(const string& metric, double value)
    2587                 :            : {
    2588                 :       4412 :   unique_lock<mutex> lock(metrics_lock);
    2589         [ +  - ]:       4412 :   metrics[metric] = value;
    2590                 :       4412 : }
    2591                 :            : #if 0 /* unused */
    2592                 :            : static void
    2593                 :            : inc_metric(const string& metric)
    2594                 :            : {
    2595                 :            :   unique_lock<mutex> lock(metrics_lock);
    2596                 :            :   metrics[metric] ++;
    2597                 :            : }
    2598                 :            : #endif
    2599                 :            : static void
    2600                 :       3569 : set_metric(const string& metric,
    2601                 :            :            const string& lname, const string& lvalue,
    2602                 :            :            double value)
    2603                 :            : {
    2604   [ +  -  +  -  :       7139 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  -  +  +  
                +  -  - ]
    2605         [ +  - ]:       3570 :   unique_lock<mutex> lock(metrics_lock);
    2606         [ +  - ]:       3570 :   metrics[key] = value;
    2607         [ +  - ]:       7140 : }
    2608                 :            : 
    2609                 :            : static void
    2610                 :      57091 : inc_metric(const string& metric,
    2611                 :            :            const string& lname, const string& lvalue)
    2612                 :            : {
    2613   [ +  -  +  -  :     122895 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  +  +  +  
                +  -  - ]
    2614         [ +  - ]:      57092 :   unique_lock<mutex> lock(metrics_lock);
    2615         [ +  - ]:      57092 :   metrics[key] ++;
    2616         [ +  - ]:     114180 : }
    2617                 :            : static void
    2618                 :      55099 : add_metric(const string& metric,
    2619                 :            :            const string& lname, const string& lvalue,
    2620                 :            :            double value)
    2621                 :            : {
    2622   [ +  -  +  -  :     118927 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  +  +  +  
                +  -  - ]
    2623         [ +  - ]:      55102 :   unique_lock<mutex> lock(metrics_lock);
    2624         [ +  - ]:      55104 :   metrics[key] += value;
    2625         [ +  - ]:     110208 : }
    2626                 :            : #if 0
    2627                 :            : static void
    2628                 :            : add_metric(const string& metric,
    2629                 :            :            double value)
    2630                 :            : {
    2631                 :            :   unique_lock<mutex> lock(metrics_lock);
    2632                 :            :   metrics[metric] += value;
    2633                 :            : }
    2634                 :            : #endif
    2635                 :            : 
    2636                 :            : 
    2637                 :            : // and more for higher arity labels if needed
    2638                 :            : 
    2639                 :            : static void
    2640                 :       3111 : inc_metric(const string& metric,
    2641                 :            :            const string& lname, const string& lvalue,
    2642                 :            :            const string& rname, const string& rvalue)
    2643                 :            : {
    2644   [ +  -  -  +  :       6222 :   string key = (metric + "{"
                   -  - ]
    2645   [ +  -  +  -  :      12444 :                 + metric_label(lname, lvalue) + ","
          -  +  -  +  +  
                +  -  - ]
    2646   [ +  -  -  +  :       9333 :                 + metric_label(rname, rvalue) + "}");
                   -  + ]
    2647         [ +  - ]:       3111 :   unique_lock<mutex> lock(metrics_lock);
    2648         [ +  - ]:       3111 :   metrics[key] ++;
    2649         [ +  - ]:       6222 : }
    2650                 :            : static void
    2651                 :       3111 : add_metric(const string& metric,
    2652                 :            :            const string& lname, const string& lvalue,
    2653                 :            :            const string& rname, const string& rvalue,
    2654                 :            :            double value)
    2655                 :            : {
    2656   [ +  -  -  +  :       6222 :   string key = (metric + "{"
                   -  - ]
    2657   [ +  -  +  -  :      12444 :                 + metric_label(lname, lvalue) + ","
          -  +  -  +  +  
                +  -  - ]
    2658   [ +  -  -  +  :       9333 :                 + metric_label(rname, rvalue) + "}");
                   -  + ]
    2659         [ +  - ]:       3111 :   unique_lock<mutex> lock(metrics_lock);
    2660         [ +  - ]:       3111 :   metrics[key] += value;
    2661         [ +  - ]:       6222 : }
    2662                 :            : 
    2663                 :            : static struct MHD_Response*
    2664                 :        342 : handle_metrics (off_t* size)
    2665                 :            : {
    2666                 :        342 :   stringstream o;
    2667                 :        342 :   {
    2668         [ +  - ]:        342 :     unique_lock<mutex> lock(metrics_lock);
    2669         [ +  + ]:      32318 :     for (auto&& i : metrics)
    2670         [ +  - ]:      31976 :       o << i.first
    2671                 :            :         << " "
    2672   [ +  -  +  - ]:      31976 :         << std::setprecision(std::numeric_limits<double>::digits10 + 1)
    2673   [ +  -  +  - ]:      31976 :         << i.second
    2674                 :      31976 :         << endl;
    2675                 :          0 :   }
    2676         [ +  - ]:        342 :   const string& os = o.str();
    2677         [ +  - ]:        342 :   MHD_Response* r = MHD_create_response_from_buffer (os.size(),
    2678         [ +  - ]:        342 :                                                      (void*) os.c_str(),
    2679                 :            :                                                      MHD_RESPMEM_MUST_COPY);
    2680         [ +  - ]:        342 :   if (r != NULL)
    2681                 :            :     {
    2682         [ +  - ]:        342 :       *size = os.size();
    2683         [ +  - ]:        342 :       add_mhd_response_header (r, "Content-Type", "text/plain");
    2684                 :            :     }
    2685         [ +  - ]:        684 :   return r;
    2686                 :        342 : }
    2687                 :            : 
    2688                 :            : static struct MHD_Response*
    2689                 :          0 : handle_root (off_t* size)
    2690                 :            : {
    2691   [ #  #  #  #  :          0 :   static string version = "debuginfod (" + string (PACKAGE_NAME) + ") "
          #  #  #  #  #  
                #  #  # ]
    2692   [ #  #  #  #  :          0 :                           + string (PACKAGE_VERSION);
          #  #  #  #  #  
                      # ]
    2693                 :          0 :   MHD_Response* r = MHD_create_response_from_buffer (version.size (),
    2694                 :          0 :                                                      (void *) version.c_str (),
    2695                 :            :                                                      MHD_RESPMEM_PERSISTENT);
    2696         [ #  # ]:          0 :   if (r != NULL)
    2697                 :            :     {
    2698                 :          0 :       *size = version.size ();
    2699                 :          0 :       add_mhd_response_header (r, "Content-Type", "text/plain");
    2700                 :            :     }
    2701                 :          0 :   return r;
    2702                 :            : }
    2703                 :            : 
    2704                 :            : 
    2705                 :            : ////////////////////////////////////////////////////////////////////////
    2706                 :            : 
    2707                 :            : 
    2708                 :            : /* libmicrohttpd callback */
    2709                 :            : static MHD_RESULT
    2710                 :       2074 : handler_cb (void * /*cls*/,
    2711                 :            :             struct MHD_Connection *connection,
    2712                 :            :             const char *url,
    2713                 :            :             const char *method,
    2714                 :            :             const char * /*version*/,
    2715                 :            :             const char * /*upload_data*/,
    2716                 :            :             size_t * /*upload_data_size*/,
    2717                 :            :             void ** ptr)
    2718                 :            : {
    2719                 :       2074 :   struct MHD_Response *r = NULL;
    2720                 :       2074 :   string url_copy = url;
    2721                 :            : 
    2722                 :            :   /* libmicrohttpd always makes (at least) two callbacks: once just
    2723                 :            :      past the headers, and one after the request body is finished
    2724                 :            :      being received.  If we process things early (first callback) and
    2725                 :            :      queue a response, libmicrohttpd would suppress http keep-alive
    2726                 :            :      (via connection->read_closed = true). */
    2727                 :       2074 :   static int aptr; /* just some random object to use as a flag */
    2728         [ +  + ]:       2074 :   if (&aptr != *ptr)
    2729                 :            :     {
    2730                 :            :       /* do never respond on first call */
    2731                 :       1037 :       *ptr = &aptr;
    2732                 :       1037 :       return MHD_YES;
    2733                 :            :     }
    2734                 :       1037 :   *ptr = NULL;                     /* reset when done */
    2735                 :            :   
    2736         [ +  - ]:       1037 :   const char *maxsize_string = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "X-DEBUGINFOD-MAXSIZE");
    2737                 :       1037 :   long maxsize = 0;
    2738   [ +  +  +  - ]:       1037 :   if (maxsize_string != NULL && maxsize_string[0] != '\0')
    2739                 :          1 :     maxsize = atol(maxsize_string);
    2740                 :            :   else
    2741                 :            :     maxsize = 0;
    2742                 :            : 
    2743                 :            : #if MHD_VERSION >= 0x00097002
    2744                 :       1037 :   enum MHD_Result rc;
    2745                 :            : #else
    2746                 :            :   int rc = MHD_NO; // mhd
    2747                 :            : #endif
    2748                 :       1037 :   int http_code = 500;
    2749                 :       1037 :   off_t http_size = -1;
    2750                 :       1037 :   struct timespec ts_start, ts_end;
    2751                 :       1037 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    2752                 :       1037 :   double afteryou = 0.0;
    2753         [ +  - ]:       1037 :   string artifacttype, suffix;
    2754                 :            : 
    2755                 :       1037 :   try
    2756                 :            :     {
    2757   [ +  -  -  +  :       2389 :       if (string(method) != "GET")
                   -  + ]
    2758   [ #  #  #  # ]:          0 :         throw reportable_exception(400, "we support GET only");
    2759                 :            : 
    2760                 :            :       /* Start decoding the URL. */
    2761                 :       1037 :       size_t slash1 = url_copy.find('/', 1);
    2762         [ +  - ]:       1037 :       string url1 = url_copy.substr(0, slash1); // ok even if slash1 not found
    2763                 :            : 
    2764   [ +  +  +  - ]:       1729 :       if (slash1 != string::npos && url1 == "/buildid")
    2765                 :            :         {
    2766                 :            :           // PR27863: block this thread awhile if another thread is already busy
    2767                 :            :           // fetching the exact same thing.  This is better for Everyone.
    2768                 :            :           // The latecomer says "... after you!" and waits.
    2769   [ +  -  +  -  :       1695 :           add_metric ("thread_busy", "role", "http-buildid-after-you", 1);
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    2770                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    2771                 :        692 :           (void) pthread_setname_np (pthread_self(), "mhd-buildid-after-you");
    2772                 :            : #endif
    2773                 :        692 :           struct timespec tsay_start, tsay_end;
    2774                 :        692 :           clock_gettime (CLOCK_MONOTONIC, &tsay_start);
    2775   [ +  +  +  - ]:        692 :           static unique_set<string> busy_urls;
    2776         [ +  - ]:        692 :           unique_set_reserver<string> after_you(busy_urls, url_copy);
    2777                 :        692 :           clock_gettime (CLOCK_MONOTONIC, &tsay_end);
    2778                 :        692 :           afteryou = (tsay_end.tv_sec - tsay_start.tv_sec) + (tsay_end.tv_nsec - tsay_start.tv_nsec)/1.e9;
    2779   [ +  -  +  -  :       1384 :           add_metric ("thread_busy", "role", "http-buildid-after-you", -1);
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    2780                 :            :           
    2781   [ +  -  +  -  :       1384 :           tmp_inc_metric m ("thread_busy", "role", "http-buildid");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2782                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    2783                 :        692 :           (void) pthread_setname_np (pthread_self(), "mhd-buildid");
    2784                 :            : #endif
    2785                 :        692 :           size_t slash2 = url_copy.find('/', slash1+1);
    2786         [ -  + ]:        692 :           if (slash2 == string::npos)
    2787   [ #  #  #  # ]:          0 :             throw reportable_exception("/buildid/ webapi error, need buildid");
    2788                 :            : 
    2789         [ +  - ]:        692 :           string buildid = url_copy.substr(slash1+1, slash2-slash1-1);
    2790                 :            : 
    2791                 :        692 :           size_t slash3 = url_copy.find('/', slash2+1);
    2792                 :            : 
    2793         [ +  + ]:        692 :           if (slash3 == string::npos)
    2794                 :            :             {
    2795   [ +  -  -  + ]:        660 :               artifacttype = url_copy.substr(slash2+1);
    2796         [ +  - ]:        660 :               suffix = "";
    2797                 :            :             }
    2798                 :            :           else
    2799                 :            :             {
    2800   [ +  -  -  + ]:         32 :               artifacttype = url_copy.substr(slash2+1, slash3-slash2-1);
    2801   [ +  -  -  +  :        343 :               suffix = url_copy.substr(slash3); // include the slash in the suffix
                   +  + ]
    2802                 :            :             }
    2803                 :            : 
    2804                 :            :           // get the resulting fd so we can report its size
    2805                 :        692 :           int fd;
    2806         [ +  + ]:        692 :           r = handle_buildid(connection, buildid, artifacttype, suffix, &fd);
    2807         [ +  - ]:        381 :           if (r)
    2808                 :            :             {
    2809                 :        381 :               struct stat fs;
    2810         [ +  - ]:        381 :               if (fstat(fd, &fs) == 0)
    2811                 :        381 :                 http_size = fs.st_size;
    2812                 :            :               // libmicrohttpd will close (fd);
    2813                 :            :             }
    2814                 :       1003 :         }
    2815         [ +  + ]:        345 :       else if (url1 == "/metrics")
    2816                 :            :         {
    2817   [ +  -  +  -  :        684 :           tmp_inc_metric m ("thread_busy", "role", "http-metrics");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2818         [ +  - ]:        342 :           artifacttype = "metrics";
    2819   [ +  -  +  -  :        684 :           inc_metric("http_requests_total", "type", artifacttype);
          +  -  -  +  -  
                      - ]
    2820         [ +  - ]:        342 :           r = handle_metrics(& http_size);
    2821                 :        342 :         }
    2822         [ -  + ]:          3 :       else if (url1 == "/")
    2823                 :            :         {
    2824         [ #  # ]:          0 :           artifacttype = "/";
    2825   [ -  -  -  -  :        315 :           inc_metric("http_requests_total", "type", artifacttype);
          -  -  -  -  -  
                -  -  + ]
    2826         [ #  # ]:          0 :           r = handle_root(& http_size);
    2827                 :            :         }
    2828                 :            :       else
    2829   [ +  -  +  -  :          9 :         throw reportable_exception("webapi error, unrecognized '" + url1 + "'");
             +  -  -  + ]
    2830                 :            : 
    2831         [ -  + ]:        723 :       if (r == 0)
    2832   [ #  #  #  # ]:          0 :         throw reportable_exception("internal error, missing response");
    2833                 :            : 
    2834   [ +  +  +  - ]:        723 :       if (maxsize > 0 && http_size > maxsize)
    2835                 :            :         {
    2836         [ +  - ]:          1 :           MHD_destroy_response(r);
    2837   [ +  -  +  -  :          3 :           throw reportable_exception(406, "File too large, max size=" + std::to_string(maxsize));
             +  -  -  + ]
    2838                 :            :         }
    2839                 :            : 
    2840         [ +  - ]:        722 :       rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
    2841                 :        722 :       http_code = MHD_HTTP_OK;
    2842         [ +  - ]:        722 :       MHD_destroy_response (r);
    2843                 :       1037 :     }
    2844         [ -  + ]:        315 :   catch (const reportable_exception& e)
    2845                 :            :     {
    2846   [ +  -  +  -  :        630 :       inc_metric("http_responses_total","result","error");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2847         [ +  - ]:        315 :       e.report(clog);
    2848                 :        315 :       http_code = e.code;
    2849         [ +  - ]:        315 :       http_size = e.message.size();
    2850         [ +  - ]:        315 :       rc = e.mhd_send_response (connection);
    2851                 :        315 :     }
    2852                 :            : 
    2853                 :       1037 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    2854                 :       1037 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    2855                 :            :   // afteryou: delay waiting for other client's identical query to complete
    2856                 :            :   // deltas: total latency, including afteryou waiting
    2857   [ +  -  +  -  :       2074 :   obatched(clog) << conninfo(connection)
                   -  - ]
    2858                 :            :                  << ' ' << method << ' ' << url
    2859   [ +  -  +  -  :       1037 :                  << ' ' << http_code << ' ' << http_size
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    2860   [ +  -  +  -  :       1037 :                  << ' ' << (int)(afteryou*1000) << '+' << (int)((deltas-afteryou)*1000) << "ms"
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    2861         [ +  - ]:       1037 :                  << endl;
    2862                 :            : 
    2863                 :            :   // related prometheus metrics
    2864                 :       1037 :   string http_code_str = to_string(http_code);
    2865   [ +  -  +  -  :       2074 :   add_metric("http_responses_transfer_bytes_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2866                 :            :              "code", http_code_str, "type", artifacttype, http_size);
    2867   [ +  -  +  -  :       2074 :   inc_metric("http_responses_transfer_bytes_count",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2868                 :            :              "code", http_code_str, "type", artifacttype);
    2869                 :            : 
    2870   [ +  -  +  -  :       2074 :   add_metric("http_responses_duration_milliseconds_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2871                 :            :              "code", http_code_str, "type", artifacttype, deltas*1000); // prometheus prefers _seconds and floating point
    2872   [ +  -  +  -  :       2074 :   inc_metric("http_responses_duration_milliseconds_count",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2873                 :            :              "code", http_code_str, "type", artifacttype);
    2874                 :            : 
    2875   [ +  -  +  -  :       2074 :   add_metric("http_responses_after_you_milliseconds_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2876                 :            :              "code", http_code_str, "type", artifacttype, afteryou*1000);
    2877   [ +  -  +  -  :       2074 :   inc_metric("http_responses_after_you_milliseconds_count",
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
    2878                 :            :              "code", http_code_str, "type", artifacttype);
    2879                 :            : 
    2880         [ -  + ]:       1037 :   return rc;
    2881   [ +  +  -  +  :       4523 : }
                   +  + ]
    2882                 :            : 
    2883                 :            : 
    2884                 :            : ////////////////////////////////////////////////////////////////////////
    2885                 :            : // borrowed originally from src/nm.c get_local_names()
    2886                 :            : 
    2887                 :            : static void
    2888                 :        105 : dwarf_extract_source_paths (Elf *elf, set<string>& debug_sourcefiles)
    2889                 :            :   noexcept // no exceptions - so we can simplify the altdbg resource release at end
    2890                 :            : {
    2891                 :        105 :   Dwarf* dbg = dwarf_begin_elf (elf, DWARF_C_READ, NULL);
    2892         [ -  + ]:        105 :   if (dbg == NULL)
    2893                 :          0 :     return;
    2894                 :            : 
    2895                 :        105 :   Dwarf* altdbg = NULL;
    2896                 :        105 :   int    altdbg_fd = -1;
    2897                 :            : 
    2898                 :            :   // DWZ handling: if we have an unsatisfied debug-alt-link, add an
    2899                 :            :   // empty string into the outgoing sourcefiles set, so the caller
    2900                 :            :   // should know that our data is incomplete.
    2901                 :        105 :   const char *alt_name_p;
    2902                 :        105 :   const void *alt_build_id; // elfutils-owned memory
    2903                 :        105 :   ssize_t sz = dwelf_dwarf_gnu_debugaltlink (dbg, &alt_name_p, &alt_build_id);
    2904         [ +  + ]:        105 :   if (sz > 0) // got one!
    2905                 :            :     {
    2906                 :         20 :       string buildid;
    2907                 :         20 :       unsigned char* build_id_bytes = (unsigned char*) alt_build_id;
    2908         [ +  + ]:        420 :       for (ssize_t idx=0; idx<sz; idx++)
    2909                 :            :         {
    2910                 :        400 :           buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
    2911                 :        400 :           buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
    2912                 :            :         }
    2913                 :            : 
    2914         [ +  - ]:         20 :       if (verbose > 3)
    2915                 :         20 :         obatched(clog) << "Need altdebug buildid=" << buildid << endl;
    2916                 :            : 
    2917                 :            :       // but is it unsatisfied the normal elfutils ways?
    2918                 :         20 :       Dwarf* alt = dwarf_getalt (dbg);
    2919         [ +  - ]:         20 :       if (alt == NULL)
    2920                 :            :         {
    2921                 :            :           // Yup, unsatisfied the normal way.  Maybe we can satisfy it
    2922                 :            :           // from our own debuginfod database.
    2923                 :         20 :           int alt_fd;
    2924                 :         20 :           struct MHD_Response *r = 0;
    2925                 :         20 :           try
    2926                 :            :             {
    2927         [ +  - ]:         20 :               string artifacttype = "debuginfo";
    2928   [ +  -  +  -  :         20 :               r = handle_buildid (0, buildid, artifacttype, "", &alt_fd);
          -  +  -  +  -  
                      - ]
    2929                 :          0 :             }
    2930         [ -  - ]:          0 :           catch (const reportable_exception& e)
    2931                 :            :             {
    2932                 :            :               // swallow exceptions
    2933                 :          0 :             }
    2934                 :            : 
    2935                 :            :           // NB: this is not actually recursive!  This invokes the web-query
    2936                 :            :           // path, which cannot get back into the scan code paths.
    2937         [ +  - ]:         20 :           if (r)
    2938                 :            :             {
    2939                 :            :               // Found it!
    2940                 :         20 :               altdbg_fd = dup(alt_fd); // ok if this fails, downstream failures ok
    2941                 :         20 :               alt = altdbg = dwarf_begin (altdbg_fd, DWARF_C_READ);
    2942                 :            :               // NB: must close this dwarf and this fd at the bottom of the function!
    2943                 :         20 :               MHD_destroy_response (r); // will close alt_fd
    2944         [ +  - ]:         20 :               if (alt)
    2945                 :         20 :                 dwarf_setalt (dbg, alt);
    2946                 :            :             }
    2947                 :            :         }
    2948                 :            :       else
    2949                 :            :         {
    2950                 :            :           // NB: dwarf_setalt(alt) inappropriate - already done!
    2951                 :            :           // NB: altdbg will stay 0 so nothing tries to redundantly dealloc.
    2952                 :            :         }
    2953                 :            : 
    2954         [ +  - ]:         20 :       if (alt)
    2955                 :            :         {
    2956         [ +  - ]:         20 :           if (verbose > 3)
    2957                 :         20 :             obatched(clog) << "Resolved altdebug buildid=" << buildid << endl;
    2958                 :            :         }
    2959                 :            :       else // (alt == NULL) - signal possible presence of poor debuginfo
    2960                 :            :         {
    2961         [ #  # ]:          0 :           debug_sourcefiles.insert("");
    2962         [ #  # ]:          0 :           if (verbose > 3)
    2963                 :          0 :             obatched(clog) << "Unresolved altdebug buildid=" << buildid << endl;
    2964                 :            :         }
    2965                 :         20 :     }
    2966                 :            : 
    2967                 :        105 :   Dwarf_Off offset = 0;
    2968                 :        105 :   Dwarf_Off old_offset;
    2969                 :        105 :   size_t hsize;
    2970                 :            : 
    2971         [ +  + ]:       1155 :   while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL, NULL) == 0)
    2972                 :            :     {
    2973                 :       1050 :       Dwarf_Die cudie_mem;
    2974                 :       1050 :       Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
    2975                 :            : 
    2976         [ -  + ]:       1050 :       if (cudie == NULL)
    2977                 :         10 :         continue;
    2978         [ +  + ]:       1050 :       if (dwarf_tag (cudie) != DW_TAG_compile_unit)
    2979                 :         10 :         continue;
    2980                 :            : 
    2981         [ -  + ]:       1040 :       const char *cuname = dwarf_diename(cudie) ?: "unknown";
    2982                 :            : 
    2983                 :       1040 :       Dwarf_Files *files;
    2984                 :       1040 :       size_t nfiles;
    2985         [ -  + ]:       1040 :       if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
    2986                 :          0 :         continue;
    2987                 :            : 
    2988                 :            :       // extract DW_AT_comp_dir to resolve relative file names
    2989                 :       1040 :       const char *comp_dir = "";
    2990                 :       1040 :       const char *const *dirs;
    2991                 :       1040 :       size_t ndirs;
    2992         [ -  + ]:       1040 :       if (dwarf_getsrcdirs (files, &dirs, &ndirs) == 0 &&
    2993         [ -  + ]:       1040 :           dirs[0] != NULL)
    2994                 :            :         comp_dir = dirs[0];
    2995                 :            :       if (comp_dir == NULL)
    2996                 :            :         comp_dir = "";
    2997                 :            : 
    2998         [ +  + ]:       1040 :       if (verbose > 3)
    2999                 :        164 :         obatched(clog) << "searching for sources for cu=" << cuname << " comp_dir=" << comp_dir
    3000                 :         82 :                        << " #files=" << nfiles << " #dirs=" << ndirs << endl;
    3001                 :            : 
    3002   [ +  -  -  - ]:       1040 :       if (comp_dir[0] == '\0' && cuname[0] != '/')
    3003                 :            :         {
    3004                 :            :           // This is a common symptom for dwz-compressed debug files,
    3005                 :            :           // where the altdebug file cannot be resolved.
    3006         [ #  # ]:          0 :           if (verbose > 3)
    3007                 :          0 :             obatched(clog) << "skipping cu=" << cuname << " due to empty comp_dir" << endl;
    3008                 :          0 :           continue;
    3009                 :            :         }
    3010                 :            : 
    3011         [ +  + ]:      16240 :       for (size_t f = 1; f < nfiles; f++)
    3012                 :            :         {
    3013                 :      15200 :           const char *hat = dwarf_filesrc (files, f, NULL, NULL);
    3014         [ -  + ]:      15200 :           if (hat == NULL)
    3015                 :          0 :             continue;
    3016                 :            : 
    3017   [ +  +  -  + ]:      29014 :           if (string(hat) == "<built-in>") // gcc intrinsics, don't bother record
    3018                 :          0 :             continue;
    3019                 :            : 
    3020         [ +  + ]:      15200 :           string waldo;
    3021         [ +  + ]:      15200 :           if (hat[0] == '/') // absolute
    3022         [ -  + ]:       9643 :             waldo = (string (hat));
    3023         [ +  - ]:       5557 :           else if (comp_dir[0] != '\0') // comp_dir relative
    3024   [ -  +  -  +  :       9728 :             waldo = (string (comp_dir) + string("/") + string (hat));
          -  +  -  +  +  
                      + ]
    3025                 :            :           else
    3026                 :            :            {
    3027         [ #  # ]:          0 :              if (verbose > 3)
    3028                 :          0 :                obatched(clog) << "skipping hat=" << hat << " due to empty comp_dir" << endl;
    3029         [ #  # ]:          0 :              continue;
    3030                 :            :            }
    3031                 :            : 
    3032                 :            :           // NB: this is the 'waldo' that a dbginfo client will have
    3033                 :            :           // to supply for us to give them the file The comp_dir
    3034                 :            :           // prefixing is a definite complication.  Otherwise we'd
    3035                 :            :           // have to return a setof comp_dirs (one per CU!) with
    3036                 :            :           // corresponding filesrc[] names, instead of one absolute
    3037                 :            :           // resoved set.  Maybe we'll have to do that anyway.  XXX
    3038                 :            : 
    3039         [ +  + ]:      15200 :           if (verbose > 4)
    3040         [ -  + ]:         50 :             obatched(clog) << waldo
    3041         [ -  + ]:         25 :                            << (debug_sourcefiles.find(waldo)==debug_sourcefiles.end() ? " new" : " dup") <<  endl;
    3042                 :            : 
    3043         [ +  - ]:      15200 :           debug_sourcefiles.insert (waldo);
    3044                 :      15200 :         }
    3045                 :            :     }
    3046                 :            : 
    3047                 :        105 :   dwarf_end(dbg);
    3048         [ +  + ]:        105 :   if (altdbg)
    3049                 :         20 :     dwarf_end(altdbg);
    3050         [ +  + ]:        105 :   if (altdbg_fd >= 0)
    3051                 :         20 :     close(altdbg_fd);
    3052                 :            : }
    3053                 :            : 
    3054                 :            : 
    3055                 :            : 
    3056                 :            : static void
    3057                 :        517 : elf_classify (int fd, bool &executable_p, bool &debuginfo_p, string &buildid, set<string>& debug_sourcefiles)
    3058                 :            : {
    3059                 :        517 :   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
    3060         [ +  - ]:        517 :   if (elf == NULL)
    3061                 :            :     return;
    3062                 :            : 
    3063                 :        517 :   try // catch our types of errors and clean up the Elf* object
    3064                 :            :     {
    3065   [ +  -  +  + ]:        517 :       if (elf_kind (elf) != ELF_K_ELF)
    3066                 :            :         {
    3067         [ +  - ]:        310 :           elf_end (elf);
    3068                 :        310 :           return;
    3069                 :            :         }
    3070                 :            : 
    3071                 :        207 :       GElf_Ehdr ehdr_storage;
    3072         [ +  - ]:        207 :       GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_storage);
    3073         [ -  + ]:        206 :       if (ehdr == NULL)
    3074                 :            :         {
    3075         [ #  # ]:          0 :           elf_end (elf);
    3076                 :            :           return;
    3077                 :            :         }
    3078                 :        206 :       auto elf_type = ehdr->e_type;
    3079                 :            : 
    3080                 :        206 :       const void *build_id; // elfutils-owned memory
    3081         [ +  - ]:        206 :       ssize_t sz = dwelf_elf_gnu_build_id (elf, & build_id);
    3082         [ -  + ]:        207 :       if (sz <= 0)
    3083                 :            :         {
    3084                 :            :           // It's not a diagnostic-worthy error for an elf file to lack build-id.
    3085                 :            :           // It might just be very old.
    3086         [ #  # ]:          0 :           elf_end (elf);
    3087                 :            :           return;
    3088                 :            :         }
    3089                 :            : 
    3090                 :            :       // build_id is a raw byte array; convert to hexadecimal *lowercase*
    3091                 :        207 :       unsigned char* build_id_bytes = (unsigned char*) build_id;
    3092         [ +  + ]:       4347 :       for (ssize_t idx=0; idx<sz; idx++)
    3093                 :            :         {
    3094         [ +  - ]:       4140 :           buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
    3095         [ +  - ]:       8280 :           buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
    3096                 :            :         }
    3097                 :            : 
    3098                 :            :       // now decide whether it's an executable - namely, any allocatable section has
    3099                 :            :       // PROGBITS;
    3100         [ +  + ]:        207 :       if (elf_type == ET_EXEC || elf_type == ET_DYN)
    3101                 :            :         {
    3102                 :        182 :           size_t shnum;
    3103         [ +  - ]:        182 :           int rc = elf_getshdrnum (elf, &shnum);
    3104         [ -  + ]:        182 :           if (rc < 0)
    3105   [ #  #  #  # ]:          0 :             throw elfutils_exception(rc, "getshdrnum");
    3106                 :            : 
    3107                 :        182 :           executable_p = false;
    3108         [ +  + ]:       3492 :           for (size_t sc = 0; sc < shnum; sc++)
    3109                 :            :             {
    3110         [ +  - ]:       3404 :               Elf_Scn *scn = elf_getscn (elf, sc);
    3111         [ -  + ]:       3404 :               if (scn == NULL)
    3112                 :          0 :                 continue;
    3113                 :            : 
    3114                 :       3404 :               GElf_Shdr shdr_mem;
    3115         [ +  - ]:       3404 :               GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
    3116         [ -  + ]:       3404 :               if (shdr == NULL)
    3117                 :          0 :                 continue;
    3118                 :            : 
    3119                 :            :               // allocated (loadable / vm-addr-assigned) section with available content?
    3120   [ +  +  +  + ]:       3404 :               if ((shdr->sh_type == SHT_PROGBITS) && (shdr->sh_flags & SHF_ALLOC))
    3121                 :            :                 {
    3122         [ +  + ]:         94 :                   if (verbose > 4)
    3123   [ +  -  +  -  :         16 :                     obatched(clog) << "executable due to SHF_ALLOC SHT_PROGBITS sc=" << sc << endl;
                   +  - ]
    3124                 :         94 :                   executable_p = true;
    3125                 :         94 :                   break; // no need to keep looking for others
    3126                 :            :                 }
    3127                 :            :             } // iterate over sections
    3128                 :            :         } // executable_p classification
    3129                 :            : 
    3130                 :            :       // now decide whether it's a debuginfo - namely, if it has any .debug* or .zdebug* sections
    3131                 :            :       // logic mostly stolen from fweimer@redhat.com's elfclassify drafts
    3132                 :        207 :       size_t shstrndx;
    3133         [ +  - ]:        207 :       int rc = elf_getshdrstrndx (elf, &shstrndx);
    3134         [ -  + ]:        207 :       if (rc < 0)
    3135   [ #  #  #  # ]:          0 :         throw elfutils_exception(rc, "getshdrstrndx");
    3136                 :            : 
    3137                 :            :       Elf_Scn *scn = NULL;
    3138                 :            :       bool symtab_p = false;
    3139                 :            :       bool bits_alloc_p = false;
    3140                 :      10651 :       while (true)
    3141                 :            :         {
    3142         [ +  - ]:       5429 :           scn = elf_nextscn (elf, scn);
    3143         [ +  + ]:       5411 :           if (scn == NULL)
    3144                 :            :             break;
    3145                 :       5309 :           GElf_Shdr shdr_storage;
    3146         [ +  - ]:       5309 :           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
    3147         [ -  + ]:       5308 :           if (shdr == NULL)
    3148                 :            :             break;
    3149         [ +  - ]:       5308 :           const char *section_name = elf_strptr (elf, shstrndx, shdr->sh_name);
    3150         [ -  + ]:       5327 :           if (section_name == NULL)
    3151                 :            :             break;
    3152         [ +  + ]:       5327 :           if (startswith (section_name, ".debug_line") ||
    3153         [ -  + ]:       5222 :               startswith (section_name, ".zdebug_line"))
    3154                 :            :             {
    3155                 :        105 :               debuginfo_p = true;
    3156         [ +  - ]:        105 :               if (scan_source_info)
    3157                 :        105 :                 dwarf_extract_source_paths (elf, debug_sourcefiles);
    3158                 :            :               break; // expecting only one .*debug_line, so no need to look for others
    3159                 :            :             }
    3160         [ +  + ]:       5222 :           else if (startswith (section_name, ".debug_") ||
    3161         [ +  # ]:       4872 :                    startswith (section_name, ".zdebug_"))
    3162                 :            :             {
    3163                 :        334 :               debuginfo_p = true;
    3164                 :            :               // NB: don't break; need to parse .debug_line for sources
    3165                 :            :             }
    3166         [ +  + ]:       4888 :           else if (shdr->sh_type == SHT_SYMTAB)
    3167                 :            :             {
    3168                 :            :               symtab_p = true;
    3169                 :            :             }
    3170                 :       4876 :           else if (shdr->sh_type != SHT_NOBITS
    3171         [ +  + ]:       4876 :                    && shdr->sh_type != SHT_NOTE
    3172         [ +  + ]:       2344 :                    && (shdr->sh_flags & SHF_ALLOC) != 0)
    3173                 :            :             {
    3174                 :       5222 :               bits_alloc_p = true;
    3175                 :            :             }
    3176                 :       5222 :         }
    3177                 :            : 
    3178                 :            :       // For more expansive elf/split-debuginfo classification, we
    3179                 :            :       // want to identify as debuginfo "strip -s"-produced files
    3180                 :            :       // without .debug_info* (like libicudata), but we don't want to
    3181                 :            :       // identify "strip -g" executables (with .symtab left there).
    3182         [ -  + ]:        207 :       if (symtab_p && !bits_alloc_p)
    3183                 :          0 :         debuginfo_p = true;
    3184                 :            :     }
    3185         [ #  # ]:          0 :   catch (const reportable_exception& e)
    3186                 :            :     {
    3187         [ #  # ]:          0 :       e.report(clog);
    3188                 :          0 :     }
    3189                 :        207 :   elf_end (elf);
    3190                 :            : }
    3191                 :            : 
    3192                 :            : 
    3193                 :            : // Intern the given file name in two parts (dirname & basename) and
    3194                 :            : // return the resulting file's id.
    3195                 :            : static int64_t
    3196                 :       4316 : register_file_name(sqlite_ps& ps_upsert_fileparts,
    3197                 :            :                    sqlite_ps& ps_upsert_file,
    3198                 :            :                    sqlite_ps& ps_lookup_file,
    3199                 :            :                    const string& name)
    3200                 :            : {
    3201                 :       4316 :   std::size_t slash = name.rfind('/');
    3202         [ +  + ]:       4316 :   string dirname, basename;
    3203         [ +  + ]:       4316 :   if (slash == std::string::npos)
    3204                 :            :     {
    3205         [ +  - ]:         45 :       dirname = "";
    3206         [ +  - ]:         45 :       basename = name;
    3207                 :            :     }
    3208                 :            :   else
    3209                 :            :     {
    3210   [ +  -  -  + ]:       4271 :       dirname = name.substr(0, slash);
    3211   [ +  -  -  +  :       4271 :       basename = name.substr(slash+1);
                   -  - ]
    3212                 :            :     }
    3213                 :            : 
    3214                 :            :   // intern the two substrings
    3215                 :       4316 :   ps_upsert_fileparts
    3216         [ +  - ]:       4316 :     .reset()
    3217         [ +  - ]:       4316 :     .bind(1, dirname)
    3218         [ +  - ]:       4316 :     .step_ok_done();
    3219                 :       4316 :   ps_upsert_fileparts
    3220         [ +  - ]:       4316 :     .reset()
    3221         [ +  - ]:       4316 :     .bind(1, basename)
    3222         [ +  - ]:       4316 :     .step_ok_done();
    3223                 :            : 
    3224                 :            :   // intern the tuple
    3225                 :       4316 :   ps_upsert_file
    3226         [ +  - ]:       4316 :     .reset()
    3227         [ +  - ]:       4316 :     .bind(1, dirname)
    3228         [ +  - ]:       4316 :     .bind(2, basename)
    3229         [ +  - ]:       4316 :     .step_ok_done();
    3230                 :            : 
    3231                 :            :   // look up the tuple's id
    3232                 :       4316 :   ps_lookup_file
    3233         [ +  - ]:       4316 :     .reset()
    3234         [ +  - ]:       4316 :     .bind(1, dirname)
    3235         [ +  - ]:       4316 :     .bind(2, basename);
    3236         [ +  - ]:       4316 :   int rc = ps_lookup_file.step();
    3237   [ -  +  -  -  :       4316 :   if (rc != SQLITE_ROW) throw sqlite_exception(rc, "step");
                   -  - ]
    3238                 :            :   
    3239         [ +  - ]:       4316 :   int64_t id = sqlite3_column_int64 (ps_lookup_file, 0);
    3240         [ +  - ]:       4316 :   ps_lookup_file.reset();
    3241         [ +  + ]:       4316 :   return id;
    3242         [ +  + ]:       8268 : }
    3243                 :            : 
    3244                 :            : 
    3245                 :            : 
    3246                 :            : static void
    3247                 :        364 : scan_source_file (const string& rps, const stat_t& st,
    3248                 :            :                   sqlite_ps& ps_upsert_buildids,
    3249                 :            :                   sqlite_ps& ps_upsert_fileparts,
    3250                 :            :                   sqlite_ps& ps_upsert_file,
    3251                 :            :                   sqlite_ps& ps_lookup_file,
    3252                 :            :                   sqlite_ps& ps_upsert_de,
    3253                 :            :                   sqlite_ps& ps_upsert_s,
    3254                 :            :                   sqlite_ps& ps_query,
    3255                 :            :                   sqlite_ps& ps_scan_done,
    3256                 :            :                   unsigned& fts_cached,
    3257                 :            :                   unsigned& fts_executable,
    3258                 :            :                   unsigned& fts_debuginfo,
    3259                 :            :                   unsigned& fts_sourcefiles)
    3260                 :            : {
    3261                 :        364 :   int64_t fileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
    3262                 :            : 
    3263                 :            :   /* See if we know of it already. */
    3264                 :        364 :   int rc = ps_query
    3265                 :        364 :     .reset()
    3266                 :        364 :     .bind(1, fileid)
    3267                 :        364 :     .bind(2, st.st_mtime)
    3268                 :        364 :     .step();
    3269                 :        364 :   ps_query.reset();
    3270         [ +  + ]:        364 :   if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
    3271                 :            :     // no need to recheck a file/version we already know
    3272                 :            :     // specifically, no need to elf-begin a file we already determined is non-elf
    3273                 :            :     // (so is stored with buildid=NULL)
    3274                 :            :     {
    3275                 :        184 :       fts_cached++;
    3276                 :        184 :       return;
    3277                 :            :     }
    3278                 :            : 
    3279                 :        180 :   bool executable_p = false, debuginfo_p = false; // E and/or D
    3280         [ +  - ]:        180 :   string buildid;
    3281         [ +  - ]:        180 :   set<string> sourcefiles;
    3282                 :            : 
    3283         [ +  - ]:        180 :   int fd = open (rps.c_str(), O_RDONLY);
    3284                 :        180 :   try
    3285                 :            :     {
    3286         [ +  - ]:        180 :       if (fd >= 0)
    3287         [ +  - ]:        180 :         elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
    3288                 :            :       else
    3289   [ #  #  #  #  :          0 :         throw libc_exception(errno, string("open ") + rps);
             #  #  #  # ]
    3290   [ +  -  +  -  :        360 :       add_metric ("scanned_bytes_total","source","file",
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    3291         [ +  - ]:        180 :                   st.st_size);
    3292   [ +  -  +  -  :        360 :       inc_metric ("scanned_files_total","source","file");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3293                 :            :     }
    3294                 :            :   // NB: we catch exceptions here too, so that we can
    3295                 :            :   // cache the corrupt-elf case (!executable_p &&
    3296                 :            :   // !debuginfo_p) just below, just as if we had an
    3297                 :            :   // EPERM error from open(2).
    3298         [ -  - ]:          0 :   catch (const reportable_exception& e)
    3299                 :            :     {
    3300         [ -  - ]:          0 :       e.report(clog);
    3301                 :          0 :     }
    3302                 :            : 
    3303         [ +  - ]:        180 :   if (fd >= 0)
    3304         [ +  - ]:        180 :     close (fd);
    3305                 :            : 
    3306         [ +  + ]:        180 :   if (buildid == "")
    3307                 :            :     {
    3308                 :            :       // no point storing an elf file without buildid
    3309                 :        149 :       executable_p = false;
    3310                 :        149 :       debuginfo_p = false;
    3311                 :            :     }
    3312                 :            :   else
    3313                 :            :     {
    3314                 :            :       // register this build-id in the interning table
    3315                 :         31 :       ps_upsert_buildids
    3316         [ +  - ]:         31 :         .reset()
    3317         [ +  - ]:         31 :         .bind(1, buildid)
    3318         [ +  - ]:         31 :         .step_ok_done();
    3319                 :            :     }
    3320                 :            : 
    3321         [ +  + ]:        180 :   if (executable_p)
    3322                 :         19 :     fts_executable ++;
    3323         [ +  + ]:        180 :   if (debuginfo_p)
    3324                 :         19 :     fts_debuginfo ++;
    3325   [ +  +  +  + ]:        180 :   if (executable_p || debuginfo_p)
    3326                 :            :     {
    3327                 :         31 :       ps_upsert_de
    3328         [ +  - ]:         31 :         .reset()
    3329         [ +  - ]:         31 :         .bind(1, buildid)
    3330   [ +  +  +  - ]:         43 :         .bind(2, debuginfo_p ? 1 : 0)
    3331   [ +  +  +  - ]:         43 :         .bind(3, executable_p ? 1 : 0)
    3332         [ +  - ]:         31 :         .bind(4, fileid)
    3333         [ +  - ]:         31 :         .bind(5, st.st_mtime)
    3334         [ +  - ]:         31 :         .step_ok_done();
    3335                 :            :     }
    3336         [ +  + ]:        180 :   if (executable_p)
    3337   [ +  -  +  -  :         38 :     inc_metric("found_executable_total","source","files");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3338         [ +  + ]:        180 :   if (debuginfo_p)
    3339   [ +  -  +  -  :         38 :     inc_metric("found_debuginfo_total","source","files");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3340                 :            : 
    3341   [ +  +  +  - ]:        199 :   if (sourcefiles.size() && buildid != "")
    3342                 :            :     {
    3343                 :         19 :       fts_sourcefiles += sourcefiles.size();
    3344                 :            : 
    3345         [ +  + ]:       1553 :       for (auto&& dwarfsrc : sourcefiles)
    3346                 :            :         {
    3347         [ +  - ]:       1534 :           char *srp = realpath(dwarfsrc.c_str(), NULL);
    3348         [ +  + ]:       1534 :           if (srp == NULL) // also if DWZ unresolved dwarfsrc=""
    3349                 :         18 :             continue; // unresolvable files are not a serious problem
    3350                 :            :           // throw libc_exception(errno, "fts/file realpath " + srcpath);
    3351         [ +  - ]:       1516 :           string srps = string(srp);
    3352                 :       1516 :           free (srp);
    3353                 :            : 
    3354                 :       1516 :           struct stat sfs;
    3355                 :       1516 :           rc = stat(srps.c_str(), &sfs);
    3356         [ -  + ]:       1516 :           if (rc != 0)
    3357         [ #  # ]:          0 :             continue;
    3358                 :            : 
    3359         [ +  - ]:       1516 :           if (verbose > 2)
    3360   [ +  -  +  -  :       4548 :             obatched(clog) << "recorded buildid=" << buildid << " file=" << srps
                   -  - ]
    3361   [ +  -  +  -  :       1516 :                            << " mtime=" << sfs.st_mtime
             +  -  +  - ]
    3362   [ +  -  +  -  :       1516 :                            << " as source " << dwarfsrc << endl;
                   +  - ]
    3363                 :            : 
    3364                 :            :           // PR25548: store canonicalized dwarfsrc path
    3365         [ +  - ]:       1516 :           string dwarfsrc_canon = canon_pathname (dwarfsrc);
    3366         [ +  + ]:       1516 :           if (dwarfsrc_canon != dwarfsrc)
    3367                 :            :             {
    3368         [ +  + ]:        254 :               if (verbose > 3)
    3369   [ +  -  +  -  :         10 :                 obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
          +  -  +  -  +  
                      - ]
    3370                 :            :             }
    3371                 :            : 
    3372         [ +  - ]:       1516 :           int64_t fileid1 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, dwarfsrc_canon);
    3373         [ +  - ]:       1516 :           int64_t fileid2 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, srps);
    3374                 :            : 
    3375                 :       1516 :           ps_upsert_s
    3376         [ +  - ]:       1516 :             .reset()
    3377         [ +  - ]:       1516 :             .bind(1, buildid)
    3378         [ +  - ]:       1516 :             .bind(2, fileid1)
    3379         [ +  - ]:       1516 :             .bind(3, fileid2)
    3380         [ +  - ]:       1516 :             .bind(4, sfs.st_mtime)
    3381         [ +  - ]:       1516 :             .step_ok_done();
    3382                 :            : 
    3383   [ +  -  +  -  :       3032 :           inc_metric("found_sourcerefs_total","source","files");
          +  -  +  -  -  
          +  -  +  +  -  
          -  -  -  -  -  
                      - ]
    3384         [ +  - ]:       3050 :         }
    3385                 :            :     }
    3386                 :            : 
    3387                 :        180 :   ps_scan_done
    3388         [ +  - ]:        180 :     .reset()
    3389         [ +  - ]:        180 :     .bind(1, fileid)
    3390         [ +  - ]:        180 :     .bind(2, st.st_mtime)
    3391         [ +  - ]:        180 :     .bind(3, st.st_size)
    3392         [ +  - ]:        180 :     .step_ok_done();
    3393                 :            : 
    3394         [ +  - ]:        180 :   if (verbose > 2)
    3395   [ +  -  +  - ]:        540 :     obatched(clog) << "recorded buildid=" << buildid << " file=" << rps
    3396   [ +  -  +  -  :        180 :                    << " mtime=" << st.st_mtime << " atype="
             +  -  +  - ]
    3397                 :            :                    << (executable_p ? "E" : "")
    3398   [ +  -  +  +  :        502 :                    << (debuginfo_p ? "D" : "") << endl;
          +  -  +  +  +  
                -  +  - ]
    3399         [ +  + ]:        211 : }
    3400                 :            : 
    3401                 :            : 
    3402                 :            : 
    3403                 :            : 
    3404                 :            : 
    3405                 :            : // Analyze given archive file of given age; record buildids / exec/debuginfo-ness of its
    3406                 :            : // constituent files with given upsert statements.
    3407                 :            : static void
    3408                 :        181 : archive_classify (const string& rps, string& archive_extension, int64_t archiveid,
    3409                 :            :                   sqlite_ps& ps_upsert_buildids, sqlite_ps& ps_upsert_fileparts, sqlite_ps& ps_upsert_file,
    3410                 :            :                   sqlite_ps& ps_lookup_file,
    3411                 :            :                   sqlite_ps& ps_upsert_de, sqlite_ps& ps_upsert_sref, sqlite_ps& ps_upsert_sdef,
    3412                 :            :                   time_t mtime,
    3413                 :            :                   unsigned& fts_executable, unsigned& fts_debuginfo, unsigned& fts_sref, unsigned& fts_sdef,
    3414                 :            :                   bool& fts_sref_complete_p)
    3415                 :            : {
    3416                 :        181 :   string archive_decoder = "/dev/null";
    3417         [ +  + ]:        448 :   for (auto&& arch : scan_archives)
    3418         [ +  + ]:        267 :     if (string_endswith(rps, arch.first))
    3419                 :            :       {
    3420         [ +  - ]:        181 :         archive_extension = arch.first;
    3421         [ +  - ]:        448 :         archive_decoder = arch.second;
    3422                 :            :       }
    3423                 :            : 
    3424                 :        181 :   FILE* fp;
    3425                 :        181 :   defer_dtor<FILE*,int>::dtor_fn dfn;
    3426         [ +  + ]:        181 :   if (archive_decoder != "cat")
    3427                 :            :     {
    3428   [ +  -  +  -  :         32 :       string popen_cmd = archive_decoder + " " + shell_escape(rps);
          +  -  -  +  -  
                -  -  - ]
    3429         [ +  - ]:         16 :       fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
    3430                 :         16 :       dfn = pclose;
    3431         [ -  + ]:         16 :       if (fp == NULL)
    3432   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("popen ") + popen_cmd);
             #  #  #  # ]
    3433                 :         16 :     }
    3434                 :            :   else
    3435                 :            :     {
    3436         [ +  - ]:        165 :       fp = fopen (rps.c_str(), "r");
    3437                 :        165 :       dfn = fclose;
    3438         [ -  + ]:        165 :       if (fp == NULL)
    3439   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("fopen ") + rps);
             #  #  #  # ]
    3440                 :            :     }
    3441                 :        181 :   defer_dtor<FILE*,int> fp_closer (fp, dfn);
    3442                 :            : 
    3443                 :        181 :   struct archive *a;
    3444         [ +  - ]:        181 :   a = archive_read_new();
    3445         [ -  + ]:        181 :   if (a == NULL)
    3446   [ #  #  #  # ]:          0 :     throw archive_exception("cannot create archive reader");
    3447                 :        181 :   defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
    3448                 :            : 
    3449         [ +  - ]:        181 :   int rc = archive_read_support_format_all(a);
    3450         [ -  + ]:        181 :   if (rc != ARCHIVE_OK)
    3451   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all formats");
    3452         [ +  - ]:        181 :   rc = archive_read_support_filter_all(a);
    3453         [ -  + ]:        181 :   if (rc != ARCHIVE_OK)
    3454   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all filters");
    3455                 :            : 
    3456         [ +  - ]:        181 :   rc = archive_read_open_FILE (a, fp);
    3457         [ -  + ]:        181 :   if (rc != ARCHIVE_OK)
    3458                 :            :     {
    3459   [ #  #  #  #  :          0 :       obatched(clog) << "cannot open archive from pipe " << rps << endl;
                   #  # ]
    3460   [ #  #  #  # ]:          0 :       throw archive_exception(a, "cannot open archive from pipe");
    3461                 :            :     }
    3462                 :            : 
    3463         [ +  + ]:        181 :   if (verbose > 3)
    3464   [ +  -  +  -  :        346 :     obatched(clog) << "libarchive scanning " << rps << " id " << archiveid << endl;
          +  -  +  -  +  
                      - ]
    3465                 :            : 
    3466                 :            :   bool any_exceptions = false;
    3467                 :       1282 :   while(1) // parse archive entries
    3468                 :            :     {
    3469         [ +  - ]:       1282 :     if (interrupted)
    3470                 :            :       break;
    3471                 :            : 
    3472                 :       1282 :     try
    3473                 :            :         {
    3474                 :       1282 :           struct archive_entry *e;
    3475         [ +  - ]:       1282 :           rc = archive_read_next_header (a, &e);
    3476         [ +  + ]:       1281 :           if (rc != ARCHIVE_OK)
    3477                 :            :             break;
    3478                 :            : 
    3479   [ +  -  +  + ]:       1100 :           if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
    3480                 :        764 :             continue;
    3481                 :            : 
    3482         [ +  - ]:        337 :           string fn = canonicalized_archive_entry_pathname (e);
    3483                 :            : 
    3484         [ +  + ]:        337 :           if (verbose > 3)
    3485   [ +  -  +  -  :        634 :             obatched(clog) << "libarchive checking " << fn << endl;
             +  -  -  - ]
    3486                 :            : 
    3487                 :            :           // extract this file to a temporary file
    3488                 :        337 :           char* tmppath = NULL;
    3489                 :        337 :           rc = asprintf (&tmppath, "%s/debuginfod.XXXXXX", tmpdir.c_str());
    3490         [ -  + ]:        337 :           if (rc < 0)
    3491   [ #  #  #  # ]:          0 :             throw libc_exception (ENOMEM, "cannot allocate tmppath");
    3492                 :        337 :           defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    3493         [ +  - ]:        337 :           int fd = mkstemp (tmppath);
    3494         [ -  + ]:        337 :           if (fd < 0)
    3495   [ #  #  #  # ]:          0 :             throw libc_exception (errno, "cannot create temporary file");
    3496                 :        337 :           unlink (tmppath); // unlink now so OS will release the file as soon as we close the fd
    3497                 :        337 :           defer_dtor<int,int> minifd_closer (fd, close);
    3498                 :            : 
    3499         [ +  - ]:        337 :           rc = archive_read_data_into_fd (a, fd);
    3500         [ -  + ]:        337 :           if (rc != ARCHIVE_OK)
    3501   [ #  #  #  # ]:          0 :             throw archive_exception(a, "cannot extract file");
    3502                 :            : 
    3503                 :            :           // finally ... time to run elf_classify on this bad boy and update the database
    3504                 :        337 :           bool executable_p = false, debuginfo_p = false;
    3505         [ +  - ]:        337 :           string buildid;
    3506         [ +  - ]:        337 :           set<string> sourcefiles;
    3507         [ +  - ]:        337 :           elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
    3508                 :            :           // NB: might throw
    3509                 :            : 
    3510         [ +  + ]:        337 :           if (buildid != "") // intern buildid
    3511                 :            :             {
    3512                 :        176 :               ps_upsert_buildids
    3513         [ +  - ]:        176 :                 .reset()
    3514         [ +  - ]:        176 :                 .bind(1, buildid)
    3515         [ +  - ]:        176 :                 .step_ok_done();
    3516                 :            :             }
    3517                 :            : 
    3518         [ +  - ]:        337 :           int64_t fileid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, fn);
    3519                 :            : 
    3520         [ +  + ]:        337 :           if (sourcefiles.size() > 0) // sref records needed
    3521                 :            :             {
    3522                 :            :               // NB: we intern each source file once.  Once raw, as it
    3523                 :            :               // appears in the DWARF file list coming back from
    3524                 :            :               // elf_classify() - because it'll end up in the
    3525                 :            :               // _norm.artifactsrc column.  We don't also put another
    3526                 :            :               // version with a '.' at the front, even though that's
    3527                 :            :               // how rpm/cpio packs names, because we hide that from
    3528                 :            :               // the database for storage efficiency.
    3529                 :            : 
    3530         [ +  + ]:        308 :               for (auto&& s : sourcefiles)
    3531                 :            :                 {
    3532         [ -  + ]:        232 :                   if (s == "")
    3533                 :            :                     {
    3534                 :          0 :                       fts_sref_complete_p = false;
    3535                 :          0 :                       continue;
    3536                 :            :                     }
    3537                 :            : 
    3538                 :            :                   // PR25548: store canonicalized source path
    3539                 :        232 :                   const string& dwarfsrc = s;
    3540         [ +  - ]:        232 :                   string dwarfsrc_canon = canon_pathname (dwarfsrc);
    3541         [ +  + ]:        232 :                   if (dwarfsrc_canon != dwarfsrc)
    3542                 :            :                     {
    3543         [ +  - ]:         16 :                       if (verbose > 3)
    3544   [ +  -  +  -  :         32 :                         obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
          +  -  +  -  +  
                -  -  - ]
    3545                 :            :                     }
    3546                 :            : 
    3547         [ +  - ]:        232 :                   int64_t srcfileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
    3548                 :            :                                                          dwarfsrc_canon);
    3549                 :            :                 
    3550                 :        232 :                   ps_upsert_sref
    3551         [ +  - ]:        232 :                     .reset()
    3552         [ +  - ]:        232 :                     .bind(1, buildid)
    3553         [ +  - ]:        232 :                     .bind(2, srcfileid)
    3554         [ +  - ]:        232 :                     .step_ok_done();
    3555                 :            : 
    3556         [ +  - ]:        232 :                   fts_sref ++;
    3557                 :        232 :                 }
    3558                 :            :             }
    3559                 :            : 
    3560         [ +  + ]:        337 :           if (executable_p)
    3561                 :         75 :             fts_executable ++;
    3562         [ +  + ]:        337 :           if (debuginfo_p)
    3563                 :        101 :             fts_debuginfo ++;
    3564                 :            : 
    3565   [ +  +  +  + ]:        337 :           if (executable_p || debuginfo_p)
    3566                 :            :             {
    3567                 :        176 :               ps_upsert_de
    3568         [ +  - ]:        176 :                 .reset()
    3569         [ +  - ]:        176 :                 .bind(1, buildid)
    3570   [ +  +  +  - ]:        251 :                 .bind(2, debuginfo_p ? 1 : 0)
    3571   [ +  +  +  - ]:        277 :                 .bind(3, executable_p ? 1 : 0)
    3572         [ +  - ]:        176 :                 .bind(4, archiveid)
    3573         [ +  - ]:        176 :                 .bind(5, mtime)
    3574         [ +  - ]:        176 :                 .bind(6, fileid)
    3575         [ +  - ]:        176 :                 .step_ok_done();
    3576                 :            :             }
    3577                 :            :           else // potential source - sdef record
    3578                 :            :             {
    3579                 :        161 :               fts_sdef ++;
    3580                 :        161 :               ps_upsert_sdef
    3581         [ +  - ]:        161 :                 .reset()
    3582         [ +  - ]:        161 :                 .bind(1, archiveid)
    3583         [ +  - ]:        161 :                 .bind(2, mtime)
    3584         [ +  - ]:        161 :                 .bind(3, fileid)
    3585         [ +  - ]:        161 :                 .step_ok_done();
    3586                 :            :             }
    3587                 :            : 
    3588   [ +  -  +  +  :        337 :           if ((verbose > 2) && (executable_p || debuginfo_p))
                   +  + ]
    3589   [ +  -  +  - ]:        528 :             obatched(clog) << "recorded buildid=" << buildid << " rpm=" << rps << " file=" << fn
    3590   [ +  -  +  -  :        176 :                            << " mtime=" << mtime << " atype="
          +  -  +  -  +  
                -  +  - ]
    3591                 :            :                            << (executable_p ? "E" : "")
    3592                 :            :                            << (debuginfo_p ? "D" : "")
    3593   [ +  -  +  +  :        352 :                            << " sourcefiles=" << sourcefiles.size() << endl;
          +  -  +  +  +  
          -  +  -  +  -  
                   +  - ]
    3594                 :            : 
    3595   [ +  +  +  + ]:        766 :         }
    3596         [ -  - ]:          0 :       catch (const reportable_exception& e)
    3597                 :            :         {
    3598         [ -  - ]:          0 :           e.report(clog);
    3599                 :          0 :           any_exceptions = true;
    3600                 :            :           // NB: but we allow the libarchive iteration to continue, in
    3601                 :            :           // case we can still gather some useful information.  That
    3602                 :            :           // would allow some webapi queries to work, until later when
    3603                 :            :           // this archive is rescanned.  (Its vitals won't go into the
    3604                 :            :           // _file_mtime_scanned table until after a successful scan.)
    3605                 :          0 :         }
    3606                 :            :     }
    3607                 :            : 
    3608         [ -  + ]:        181 :   if (any_exceptions)
    3609   [ #  #  #  # ]:          0 :     throw reportable_exception("exceptions encountered during archive scan");
    3610         [ +  + ]:        189 : }
    3611                 :            : 
    3612                 :            : 
    3613                 :            : 
    3614                 :            : // scan for archive files such as .rpm
    3615                 :            : static void
    3616                 :        351 : scan_archive_file (const string& rps, const stat_t& st,
    3617                 :            :                    sqlite_ps& ps_upsert_buildids,
    3618                 :            :                    sqlite_ps& ps_upsert_fileparts,
    3619                 :            :                    sqlite_ps& ps_upsert_file,
    3620                 :            :                    sqlite_ps& ps_lookup_file,
    3621                 :            :                    sqlite_ps& ps_upsert_de,
    3622                 :            :                    sqlite_ps& ps_upsert_sref,
    3623                 :            :                    sqlite_ps& ps_upsert_sdef,
    3624                 :            :                    sqlite_ps& ps_query,
    3625                 :            :                    sqlite_ps& ps_scan_done,
    3626                 :            :                    unsigned& fts_cached,
    3627                 :            :                    unsigned& fts_executable,
    3628                 :            :                    unsigned& fts_debuginfo,
    3629                 :            :                    unsigned& fts_sref,
    3630                 :            :                    unsigned& fts_sdef)
    3631                 :            : {
    3632                 :            :   // intern the archive file name
    3633                 :        351 :   int64_t archiveid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
    3634                 :            : 
    3635                 :            :   /* See if we know of it already. */
    3636                 :        351 :   int rc = ps_query
    3637                 :        351 :     .reset()
    3638                 :        351 :     .bind(1, archiveid)
    3639                 :        351 :     .bind(2, st.st_mtime)
    3640                 :        351 :     .step();
    3641                 :        351 :   ps_query.reset();
    3642         [ +  + ]:        351 :   if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
    3643                 :            :     // no need to recheck a file/version we already know
    3644                 :            :     // specifically, no need to parse this archive again, since we already have
    3645                 :            :     // it as a D or E or S record,
    3646                 :            :     // (so is stored with buildid=NULL)
    3647                 :            :     {
    3648                 :        170 :       fts_cached ++;
    3649                 :        170 :       return;
    3650                 :            :     }
    3651                 :            : 
    3652                 :            :   // extract the archive contents
    3653                 :        181 :   unsigned my_fts_executable = 0, my_fts_debuginfo = 0, my_fts_sref = 0, my_fts_sdef = 0;
    3654                 :        181 :   bool my_fts_sref_complete_p = true;
    3655                 :        181 :   bool any_exceptions = false;
    3656                 :        181 :   try
    3657                 :            :     {
    3658         [ +  - ]:        181 :       string archive_extension;
    3659                 :        181 :       archive_classify (rps, archive_extension, archiveid,
    3660                 :            :                         ps_upsert_buildids, ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
    3661                 :            :                         ps_upsert_de, ps_upsert_sref, ps_upsert_sdef, // dalt
    3662         [ +  - ]:        181 :                         st.st_mtime,
    3663                 :            :                         my_fts_executable, my_fts_debuginfo, my_fts_sref, my_fts_sdef,
    3664                 :            :                         my_fts_sref_complete_p);
    3665   [ +  -  +  -  :        362 :       add_metric ("scanned_bytes_total","source",archive_extension + " archive",
          +  -  -  +  +  
             +  -  -  -  
                      - ]
    3666         [ +  - ]:        181 :                   st.st_size);
    3667   [ +  -  +  -  :        362 :       inc_metric ("scanned_files_total","source",archive_extension + " archive");
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    3668   [ +  -  +  -  :        362 :       add_metric("found_debuginfo_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    3669                 :            :                  my_fts_debuginfo);
    3670   [ +  -  +  -  :        362 :       add_metric("found_executable_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    3671                 :            :                  my_fts_executable);
    3672   [ +  -  +  -  :        370 :       add_metric("found_sourcerefs_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  +  
          -  -  -  -  -  
                      - ]
    3673                 :            :                  my_fts_sref);
    3674                 :        181 :     }
    3675         [ -  - ]:          0 :   catch (const reportable_exception& e)
    3676                 :            :     {
    3677         [ -  - ]:          0 :       e.report(clog);
    3678                 :          0 :       any_exceptions = true;
    3679                 :          0 :     }
    3680                 :            : 
    3681         [ +  - ]:        181 :   if (verbose > 2)
    3682         [ +  - ]:        543 :     obatched(clog) << "scanned archive=" << rps
    3683   [ +  -  +  - ]:        181 :                    << " mtime=" << st.st_mtime
    3684         [ +  - ]:        181 :                    << " executables=" << my_fts_executable
    3685   [ +  -  +  - ]:        181 :                    << " debuginfos=" << my_fts_debuginfo
    3686   [ +  -  +  - ]:        181 :                    << " srefs=" << my_fts_sref
    3687   [ +  -  +  - ]:        181 :                    << " sdefs=" << my_fts_sdef
    3688   [ +  -  +  -  :        181 :                    << " exceptions=" << any_exceptions
             +  -  +  - ]
    3689                 :        181 :                    << endl;
    3690                 :            : 
    3691                 :        181 :   fts_executable += my_fts_executable;
    3692                 :        181 :   fts_debuginfo += my_fts_debuginfo;
    3693                 :        181 :   fts_sref += my_fts_sref;
    3694                 :        181 :   fts_sdef += my_fts_sdef;
    3695                 :            : 
    3696         [ -  + ]:        181 :   if (any_exceptions)
    3697   [ #  #  #  # ]:          0 :     throw reportable_exception("exceptions encountered during archive scan");
    3698                 :            : 
    3699         [ +  - ]:        181 :   if (my_fts_sref_complete_p) // leave incomplete?
    3700                 :        181 :     ps_scan_done
    3701                 :        181 :       .reset()
    3702                 :        181 :       .bind(1, archiveid)
    3703                 :        181 :       .bind(2, st.st_mtime)
    3704                 :        181 :       .bind(3, st.st_size)
    3705                 :        181 :       .step_ok_done();
    3706                 :            : }
    3707                 :            : 
    3708                 :            : 
    3709                 :            : 
    3710                 :            : ////////////////////////////////////////////////////////////////////////
    3711                 :            : 
    3712                 :            : 
    3713                 :            : 
    3714                 :            : // The thread that consumes file names off of the scanq.  We hold
    3715                 :            : // the persistent sqlite_ps's at this level and delegate file/archive
    3716                 :            : // scanning to other functions.
    3717                 :            : static void*
    3718                 :        128 : thread_main_scanner (void* arg)
    3719                 :            : {
    3720                 :        128 :   (void) arg;
    3721                 :            : 
    3722                 :            :   // all the prepared statements fit to use, the _f_ set:
    3723   [ +  -  +  -  :        256 :   sqlite_ps ps_f_upsert_buildids (db, "file-buildids-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
             +  -  -  - ]
    3724   [ +  -  +  -  :        256 :   sqlite_ps ps_f_upsert_fileparts (db, "file-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    3725         [ +  - ]:        128 :   sqlite_ps ps_f_upsert_file (db, "file-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
    3726                 :            :                               "(select id from " BUILDIDS "_fileparts where name = ?),\n"
    3727   [ +  -  +  -  :        256 :                               "(select id from " BUILDIDS "_fileparts where name = ?));");
          +  -  +  -  -  
                      - ]
    3728         [ +  - ]:        128 :   sqlite_ps ps_f_lookup_file (db, "file-file-lookup",
    3729                 :            :                               "select f.id\n"
    3730                 :            :                               " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
    3731   [ +  -  +  -  :        256 :                               " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
          +  -  +  -  -  
                      - ]
    3732         [ +  - ]:        128 :   sqlite_ps ps_f_upsert_de (db, "file-de-upsert",
    3733                 :            :                           "insert or ignore into " BUILDIDS "_f_de "
    3734                 :            :                           "(buildid, debuginfo_p, executable_p, file, mtime) "
    3735                 :            :                           "values ((select id from " BUILDIDS "_buildids where hex = ?),"
    3736   [ +  -  +  -  :        256 :                             "        ?,?,?,?);");
          +  -  +  -  -  
                      - ]
    3737         [ +  - ]:        128 :   sqlite_ps ps_f_upsert_s (db, "file-s-upsert",
    3738                 :            :                          "insert or ignore into " BUILDIDS "_f_s "
    3739                 :            :                          "(buildid, artifactsrc, file, mtime) "
    3740                 :            :                          "values ((select id from " BUILDIDS "_buildids where hex = ?),"
    3741   [ +  -  +  -  :        256 :                          "      ?,?,?);");
          +  -  +  -  -  
                      - ]
    3742         [ +  - ]:        128 :   sqlite_ps ps_f_query (db, "file-negativehit-find",
    3743                 :            :                         "select 1 from " BUILDIDS "_file_mtime_scanned where sourcetype = 'F' "
    3744   [ +  -  +  -  :        256 :                         "and file = ? and mtime = ?;");
          +  -  +  -  -  
                      - ]
    3745         [ +  - ]:        128 :   sqlite_ps ps_f_scan_done (db, "file-scanned",
    3746                 :            :                           "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
    3747   [ +  -  +  -  :        256 :                           "values ('F', ?,?,?);");
          +  -  +  -  -  
                      - ]
    3748                 :            : 
    3749                 :            :   // and now for the _r_ set
    3750   [ +  -  +  -  :        256 :   sqlite_ps ps_r_upsert_buildids (db, "rpm-buildid-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    3751   [ +  -  +  -  :        256 :   sqlite_ps ps_r_upsert_fileparts (db, "rpm-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    3752         [ +  - ]:        128 :   sqlite_ps ps_r_upsert_file (db, "rpm-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
    3753                 :            :                               "(select id from " BUILDIDS "_fileparts where name = ?),\n"
    3754   [ +  -  +  -  :        256 :                               "(select id from " BUILDIDS "_fileparts where name = ?));");
          +  -  +  -  -  
                      - ]
    3755         [ +  - ]:        128 :   sqlite_ps ps_r_lookup_file (db, "rpm-file-lookup",
    3756                 :            :                               "select f.id\n"
    3757                 :            :                               " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
    3758   [ +  -  +  -  :        256 :                               " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
          +  -  +  -  -  
                      - ]
    3759         [ +  - ]:        128 :   sqlite_ps ps_r_upsert_de (db, "rpm-de-insert",
    3760                 :            :                           "insert or ignore into " BUILDIDS "_r_de (buildid, debuginfo_p, executable_p, file, mtime, content) values ("
    3761   [ +  -  +  -  :        256 :                           "(select id from " BUILDIDS "_buildids where hex = ?), ?, ?, ?, ?, ?);");
          +  -  +  -  -  
                      - ]
    3762         [ +  - ]:        128 :   sqlite_ps ps_r_upsert_sref (db, "rpm-sref-insert",
    3763                 :            :                             "insert or ignore into " BUILDIDS "_r_sref (buildid, artifactsrc) values ("
    3764                 :            :                             "(select id from " BUILDIDS "_buildids where hex = ?), "
    3765   [ +  -  +  -  :        256 :                             "?);");
          +  -  +  -  -  
                      - ]
    3766         [ +  - ]:        128 :   sqlite_ps ps_r_upsert_sdef (db, "rpm-sdef-insert",
    3767                 :            :                             "insert or ignore into " BUILDIDS "_r_sdef (file, mtime, content) values ("
    3768   [ +  -  +  -  :        256 :                             "?, ?, ?);");
          +  -  +  -  -  
                      - ]
    3769         [ +  - ]:        128 :   sqlite_ps ps_r_query (db, "rpm-negativehit-query",
    3770                 :            :                       "select 1 from " BUILDIDS "_file_mtime_scanned where "
    3771   [ +  -  +  -  :        256 :                       "sourcetype = 'R' and file = ? and mtime = ?;");
          +  -  +  -  -  
                      - ]
    3772         [ +  - ]:        128 :   sqlite_ps ps_r_scan_done (db, "rpm-scanned",
    3773                 :            :                           "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
    3774   [ +  -  +  -  :        256 :                           "values ('R', ?, ?, ?);");
          +  -  +  -  -  
                      - ]
    3775                 :            :   
    3776                 :            : 
    3777                 :        128 :   unsigned fts_cached = 0, fts_executable = 0, fts_debuginfo = 0, fts_sourcefiles = 0;
    3778                 :        128 :   unsigned fts_sref = 0, fts_sdef = 0;
    3779                 :            : 
    3780   [ +  -  +  -  :        256 :   add_metric("thread_count", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3781   [ +  -  +  -  :        256 :   add_metric("thread_busy", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3782         [ +  + ]:        726 :   while (! interrupted)
    3783                 :            :     {
    3784         [ +  - ]:        598 :       scan_payload p;
    3785                 :            : 
    3786   [ +  -  +  -  :       1196 :       add_metric("thread_busy", "role", "scan", -1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3787                 :            :       // NB: threads may be blocked within either of these two waiting
    3788                 :            :       // states, if the work queue happens to run dry.  That's OK.
    3789   [ +  -  +  - ]:        598 :       if (scan_barrier) scan_barrier->count();
    3790         [ +  - ]:        598 :       bool gotone = scanq.wait_front(p);
    3791   [ +  -  +  -  :       1196 :       add_metric("thread_busy", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3792                 :            : 
    3793   [ +  +  -  + ]:        598 :       if (! gotone) continue; // go back to waiting
    3794                 :            : 
    3795                 :        470 :       try
    3796                 :            :         {
    3797                 :        470 :           bool scan_archive = false;
    3798         [ +  + ]:       1120 :           for (auto&& arch : scan_archives)
    3799         [ +  + ]:        650 :             if (string_endswith(p.first, arch.first))
    3800                 :        351 :               scan_archive = true;
    3801                 :            : 
    3802         [ +  + ]:        470 :           if (scan_archive)
    3803         [ +  - ]:        351 :             scan_archive_file (p.first, p.second,
    3804                 :            :                                ps_r_upsert_buildids,
    3805                 :            :                                ps_r_upsert_fileparts,
    3806                 :            :                                ps_r_upsert_file,
    3807                 :            :                                ps_r_lookup_file,
    3808                 :            :                                ps_r_upsert_de,
    3809                 :            :                                ps_r_upsert_sref,
    3810                 :            :                                ps_r_upsert_sdef,
    3811                 :            :                                ps_r_query,
    3812                 :            :                                ps_r_scan_done,
    3813                 :            :                                fts_cached,
    3814                 :            :                                fts_executable,
    3815                 :            :                                fts_debuginfo,
    3816                 :            :                                fts_sref,
    3817                 :            :                                fts_sdef);
    3818                 :            : 
    3819         [ +  + ]:        470 :           if (scan_files) // NB: maybe "else if" ?
    3820         [ +  - ]:        364 :             scan_source_file (p.first, p.second,
    3821                 :            :                               ps_f_upsert_buildids,
    3822                 :            :                               ps_f_upsert_fileparts,
    3823                 :            :                               ps_f_upsert_file,
    3824                 :            :                               ps_f_lookup_file,
    3825                 :            :                               ps_f_upsert_de,
    3826                 :            :                               ps_f_upsert_s,
    3827                 :            :                               ps_f_query,
    3828                 :            :                               ps_f_scan_done,
    3829                 :            :                               fts_cached, fts_executable, fts_debuginfo, fts_sourcefiles);
    3830                 :            :         }
    3831         [ -  - ]:          0 :       catch (const reportable_exception& e)
    3832                 :            :         {
    3833         [ -  - ]:          0 :           e.report(cerr);
    3834                 :          0 :         }
    3835                 :            : 
    3836         [ +  - ]:        470 :       scanq.done_front(); // let idlers run
    3837                 :            :       
    3838                 :        470 :       if (fts_cached || fts_executable || fts_debuginfo || fts_sourcefiles || fts_sref || fts_sdef)
    3839                 :            :         {} // NB: not just if a successful scan - we might have encountered -ENOSPC & failed
    3840   [ +  -  +  - ]:        470 :       (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
    3841   [ +  -  +  - ]:        470 :       (void) statfs_free_enough_p(tmpdir, "tmpdir"); // this too, in case of fdcache/tmpfile usage
    3842                 :            : 
    3843                 :            :       // finished a scanning step -- not a "loop", because we just
    3844                 :            :       // consume the traversal loop's work, whenever
    3845   [ +  -  +  -  :        940 :       inc_metric("thread_work_total","role","scan");
          +  -  +  -  -  
          +  -  +  +  -  
          -  -  -  -  -  
                      - ]
    3846                 :        598 :     }
    3847                 :            : 
    3848                 :            : 
    3849   [ +  -  +  -  :        256 :   add_metric("thread_busy", "role", "scan", -1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3850                 :        128 :   return 0;
    3851                 :        128 : }
    3852                 :            : 
    3853                 :            : 
    3854                 :            : 
    3855                 :            : // The thread that traverses all the source_paths and enqueues all the
    3856                 :            : // matching files into the file/archive scan queue.
    3857                 :            : static void
    3858                 :         59 : scan_source_paths()
    3859                 :            : {
    3860                 :            :   // NB: fedora 31 glibc/fts(3) crashes inside fts_read() on empty
    3861                 :            :   // path list.
    3862         [ +  + ]:         59 :   if (source_paths.empty())
    3863                 :          1 :     return;
    3864                 :            : 
    3865                 :            :   // Turn the source_paths into an fts(3)-compatible char**.  Since
    3866                 :            :   // source_paths[] does not change after argv processing, the
    3867                 :            :   // c_str()'s are safe to keep around awile.
    3868                 :         58 :   vector<const char *> sps;
    3869         [ +  + ]:        157 :   for (auto&& sp: source_paths)
    3870         [ +  - ]:         99 :     sps.push_back(sp.c_str());
    3871   [ +  -  -  - ]:         58 :   sps.push_back(NULL);
    3872                 :            : 
    3873   [ +  +  +  - ]:        109 :   FTS *fts = fts_open ((char * const *)sps.data(),
    3874                 :            :                       (traverse_logical ? FTS_LOGICAL : FTS_PHYSICAL|FTS_XDEV)
    3875                 :            :                       | FTS_NOCHDIR /* multithreaded */,
    3876                 :            :                       NULL);
    3877         [ -  + ]:         58 :   if (fts == NULL)
    3878   [ #  #  #  # ]:          0 :     throw libc_exception(errno, "cannot fts_open");
    3879                 :         58 :   defer_dtor<FTS*,int> fts_cleanup (fts, fts_close);
    3880                 :            : 
    3881                 :         58 :   struct timespec ts_start, ts_end;
    3882                 :         58 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    3883                 :         58 :   unsigned fts_scanned = 0, fts_regex = 0;
    3884                 :            : 
    3885                 :         58 :   FTSENT *f;
    3886   [ +  -  +  + ]:       1058 :   while ((f = fts_read (fts)) != NULL)
    3887                 :            :   {
    3888         [ +  - ]:        942 :     if (interrupted) break;
    3889                 :            : 
    3890         [ -  + ]:        942 :     if (sigusr2 != forced_groom_count) // stop early if groom triggered
    3891                 :            :       {
    3892         [ #  # ]:          0 :         scanq.clear(); // clear previously issued work for scanner threads
    3893                 :            :         break;
    3894                 :            :       }
    3895                 :            : 
    3896                 :        942 :     fts_scanned ++;
    3897                 :            : 
    3898         [ +  - ]:        942 :     if (verbose > 2)
    3899   [ +  -  +  -  :       1884 :       obatched(clog) << "fts traversing " << f->fts_path << endl;
                   +  - ]
    3900                 :            : 
    3901   [ +  +  +  +  :        942 :     switch (f->fts_info)
                      + ]
    3902                 :            :       {
    3903                 :        514 :       case FTS_F:
    3904                 :        514 :         {
    3905                 :            :           /* Found a file.  Convert it to an absolute path, so
    3906                 :            :              the buildid database does not have relative path
    3907                 :            :              names that are unresolvable from a subsequent run
    3908                 :            :              in a different cwd. */
    3909         [ +  - ]:        514 :           char *rp = realpath(f->fts_path, NULL);
    3910         [ -  + ]:        514 :           if (rp == NULL)
    3911                 :          0 :             continue; // ignore dangling symlink or such
    3912         [ +  - ]:        514 :           string rps = string(rp);
    3913                 :        514 :           free (rp);
    3914                 :            : 
    3915         [ +  - ]:        514 :           bool ri = !regexec (&file_include_regex, rps.c_str(), 0, 0, 0);
    3916         [ +  - ]:        514 :           bool rx = !regexec (&file_exclude_regex, rps.c_str(), 0, 0, 0);
    3917         [ +  + ]:        514 :           if (!ri || rx)
    3918                 :            :             {
    3919         [ +  - ]:         44 :               if (verbose > 3)
    3920         [ +  - ]:         88 :                 obatched(clog) << "fts skipped by regex "
    3921   [ +  +  +  -  :         48 :                                << (!ri ? "I" : "") << (rx ? "X" : "") << endl;
          +  +  +  -  +  
                      - ]
    3922                 :         44 :               fts_regex ++;
    3923         [ +  + ]:         44 :               if (!ri)
    3924   [ +  -  +  -  :          4 :                 inc_metric("traversed_total","type","file-skipped-I");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3925         [ +  + ]:         44 :               if (rx)
    3926   [ +  -  +  -  :         84 :                 inc_metric("traversed_total","type","file-skipped-X");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3927                 :            :             }
    3928                 :            :           else
    3929                 :            :             {
    3930   [ +  -  +  - ]:        470 :               scanq.push_back (make_pair(rps, *f->fts_statp));
    3931   [ +  -  +  -  :        940 :               inc_metric("traversed_total","type","file");
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
    3932                 :            :             }
    3933                 :          0 :         }
    3934                 :        514 :         break;
    3935                 :            : 
    3936                 :          2 :       case FTS_ERR:
    3937                 :          2 :       case FTS_NS:
    3938                 :            :         // report on some types of errors because they may reflect fixable misconfiguration
    3939                 :          2 :         {
    3940   [ +  -  +  -  :          4 :           auto x = libc_exception(f->fts_errno, string("fts traversal ") + string(f->fts_path));
          +  -  +  -  -  
             +  -  +  -  
                      - ]
    3941         [ +  - ]:          2 :           x.report(cerr);
    3942                 :          0 :         }
    3943   [ +  -  +  -  :          4 :         inc_metric("traversed_total","type","error");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3944                 :          2 :         break;
    3945                 :            : 
    3946                 :          6 :       case FTS_SL: // ignore, but count because debuginfod -L would traverse these
    3947   [ +  -  +  -  :         12 :         inc_metric("traversed_total","type","symlink");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3948                 :          6 :         break;
    3949                 :            : 
    3950                 :        210 :       case FTS_D: // ignore
    3951   [ +  -  +  -  :        420 :         inc_metric("traversed_total","type","directory");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3952                 :        210 :         break;
    3953                 :            : 
    3954                 :        210 :       default: // ignore
    3955   [ +  -  +  -  :        420 :         inc_metric("traversed_total","type","other");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3956                 :        210 :         break;
    3957                 :            :       }
    3958                 :            :   }
    3959                 :         58 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    3960                 :         58 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    3961                 :            : 
    3962   [ +  -  +  -  :        174 :   obatched(clog) << "fts traversed source paths in " << deltas << "s, scanned=" << fts_scanned
             +  -  +  - ]
    3963   [ +  -  +  -  :         58 :                  << ", regex-skipped=" << fts_regex << endl;
                   +  - ]
    3964         [ +  - ]:        116 : }
    3965                 :            : 
    3966                 :            : 
    3967                 :            : static void*
    3968                 :         32 : thread_main_fts_source_paths (void* arg)
    3969                 :            : {
    3970                 :         32 :   (void) arg; // ignore; we operate on global data
    3971                 :            : 
    3972   [ +  -  +  -  :         64 :   set_metric("thread_tid", "role","traverse", tid());
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    3973   [ +  -  +  -  :         64 :   add_metric("thread_count", "role", "traverse", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    3974                 :            : 
    3975                 :         32 :   time_t last_rescan = 0;
    3976                 :            : 
    3977         [ +  - ]:        161 :   while (! interrupted)
    3978                 :            :     {
    3979                 :        161 :       sleep (1);
    3980                 :        161 :       scanq.wait_idle(); // don't start a new traversal while scanners haven't finished the job
    3981                 :        161 :       scanq.done_idle(); // release the hounds
    3982         [ +  + ]:        161 :       if (interrupted) break;
    3983                 :            : 
    3984                 :        129 :       time_t now = time(NULL);
    3985                 :        129 :       bool rescan_now = false;
    3986         [ +  + ]:        129 :       if (last_rescan == 0) // at least one initial rescan is documented even for -t0
    3987                 :         31 :         rescan_now = true;
    3988   [ +  +  +  + ]:        129 :       if (rescan_s > 0 && (long)now > (long)(last_rescan + rescan_s))
    3989                 :        129 :         rescan_now = true;
    3990         [ +  + ]:        129 :       if (sigusr1 != forced_rescan_count)
    3991                 :            :         {
    3992                 :         31 :           forced_rescan_count = sigusr1;
    3993                 :         31 :           rescan_now = true;
    3994                 :            :         }
    3995         [ +  + ]:        129 :       if (rescan_now)
    3996                 :            :         {
    3997   [ +  -  +  -  :        118 :           set_metric("thread_busy", "role","traverse", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    3998                 :         59 :           try
    3999                 :            :             {
    4000         [ +  - ]:         59 :               scan_source_paths();
    4001                 :            :             }
    4002         [ -  - ]:          0 :           catch (const reportable_exception& e)
    4003                 :            :             {
    4004         [ -  - ]:          0 :               e.report(cerr);
    4005                 :          0 :             }
    4006                 :         59 :           last_rescan = time(NULL); // NB: now was before scanning
    4007                 :            :           // finished a traversal loop
    4008   [ +  -  +  -  :        118 :           inc_metric("thread_work_total", "role","traverse");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4009   [ +  -  +  -  :        118 :           set_metric("thread_busy", "role","traverse", 0);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4010                 :            :         }
    4011                 :            :     }
    4012                 :            : 
    4013                 :         32 :   return 0;
    4014                 :            : }
    4015                 :            : 
    4016                 :            : 
    4017                 :            : 
    4018                 :            : ////////////////////////////////////////////////////////////////////////
    4019                 :            : 
    4020                 :            : static void
    4021                 :         35 : database_stats_report()
    4022                 :            : {
    4023                 :         35 :   sqlite_ps ps_query (db, "database-overview",
    4024   [ +  -  +  -  :         70 :                       "select label,quantity from " BUILDIDS "_stats");
             +  -  -  - ]
    4025                 :            : 
    4026   [ +  -  +  - ]:         70 :   obatched(clog) << "database record counts:" << endl;
    4027                 :        805 :   while (1)
    4028                 :            :     {
    4029         [ +  - ]:        420 :       if (interrupted) break;
    4030         [ +  - ]:        420 :       if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    4031                 :            :         break;
    4032                 :            : 
    4033         [ +  - ]:        420 :       int rc = ps_query.step();
    4034         [ +  + ]:        420 :       if (rc == SQLITE_DONE) break;
    4035         [ -  + ]:        385 :       if (rc != SQLITE_ROW)
    4036   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    4037                 :            : 
    4038         [ +  - ]:        385 :       obatched(clog)
    4039   [ +  -  -  +  :        385 :         << ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL")
                   +  - ]
    4040                 :            :         << " "
    4041   [ +  -  +  -  :        770 :         << (sqlite3_column_text(ps_query, 1) ?: (const unsigned char*) "NULL")
             -  +  +  - ]
    4042                 :        385 :         << endl;
    4043                 :            : 
    4044   [ +  -  +  -  :        770 :       set_metric("groom", "statistic",
          -  +  +  -  +  
          -  +  -  +  -  
          -  +  +  +  -  
                -  -  - ]
    4045         [ +  - ]:        385 :                  ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL"),
    4046                 :            :                  (sqlite3_column_double(ps_query, 1)));
    4047                 :        385 :     }
    4048                 :         35 : }
    4049                 :            : 
    4050                 :            : 
    4051                 :            : // Do a round of database grooming that might take many minutes to run.
    4052                 :         35 : void groom()
    4053                 :            : {
    4054         [ +  - ]:         70 :   obatched(clog) << "grooming database" << endl;
    4055                 :            : 
    4056                 :         35 :   struct timespec ts_start, ts_end;
    4057                 :         35 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    4058                 :            : 
    4059                 :            :   // scan for files that have disappeared
    4060                 :         35 :   sqlite_ps files (db, "check old files",
    4061                 :            :                    "select distinct s.mtime, s.file, f.name from "
    4062                 :            :                    BUILDIDS "_file_mtime_scanned s, " BUILDIDS "_files_v f "
    4063   [ +  -  +  -  :         70 :                    "where f.id = s.file");
             +  -  -  - ]
    4064                 :            :   // NB: Because _ftime_mtime_scanned can contain both F and
    4065                 :            :   // R records for the same file, this query would return duplicates if the
    4066                 :            :   // DISTINCT qualifier were not there.
    4067         [ +  - ]:         35 :   files.reset();
    4068                 :            : 
    4069                 :            :   // DECISION TIME - we enumerate stale fileids/mtimes
    4070         [ +  - ]:         35 :   deque<pair<int64_t,int64_t> > stale_fileid_mtime;
    4071                 :            :   
    4072                 :         35 :   time_t time_start = time(NULL);
    4073                 :        191 :   while(1)
    4074                 :            :     {
    4075                 :            :       // PR28514: limit grooming iteration to O(rescan time), to avoid
    4076                 :            :       // slow filesystem tests over many files locking out rescans for
    4077                 :            :       // too long.
    4078   [ +  +  -  + ]:        113 :       if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
    4079                 :            :         {
    4080   [ #  #  #  #  :          0 :           inc_metric("groomed_total", "decision", "aborted");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    4081                 :          0 :           break;
    4082                 :            :         }
    4083                 :            : 
    4084         [ +  - ]:        113 :       if (interrupted) break;
    4085                 :            : 
    4086         [ +  - ]:        113 :       int rc = files.step();
    4087         [ +  + ]:        113 :       if (rc != SQLITE_ROW)
    4088                 :            :         break;
    4089                 :            : 
    4090         [ +  - ]:         78 :       int64_t mtime = sqlite3_column_int64 (files, 0);
    4091         [ +  - ]:         78 :       int64_t fileid = sqlite3_column_int64 (files, 1);
    4092   [ +  -  -  + ]:         78 :       const char* filename = ((const char*) sqlite3_column_text (files, 2) ?: "");
    4093                 :         78 :       struct stat s;
    4094                 :         78 :       bool regex_file_drop = 0;
    4095                 :            : 
    4096         [ +  + ]:         78 :       if (regex_groom)
    4097                 :            :         {
    4098         [ +  - ]:          8 :           bool reg_include = !regexec (&file_include_regex, filename, 0, 0, 0);
    4099         [ +  - ]:          8 :           bool reg_exclude = !regexec (&file_exclude_regex, filename, 0, 0, 0);
    4100                 :          8 :           regex_file_drop = !reg_include || reg_exclude; // match logic of scan_source_paths  
    4101                 :            :         }
    4102                 :            : 
    4103                 :         78 :       rc = stat(filename, &s);
    4104   [ +  +  -  + ]:         78 :       if ( regex_file_drop ||  rc < 0 || (mtime != (int64_t) s.st_mtime) )
    4105                 :            :         {
    4106         [ +  - ]:         12 :           if (verbose > 2)
    4107   [ +  -  +  -  :         24 :             obatched(clog) << "groom: stale file=" << filename << " mtime=" << mtime << endl;
          +  -  +  -  +  
                      - ]
    4108         [ +  - ]:         12 :           stale_fileid_mtime.push_back(make_pair(fileid,mtime));
    4109   [ +  -  +  -  :         24 :           inc_metric("groomed_total", "decision", "stale");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4110   [ +  -  +  -  :         24 :           set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4111                 :            :         }
    4112                 :            :       else
    4113   [ +  -  +  -  :        132 :         inc_metric("groomed_total", "decision", "fresh");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4114                 :            :       
    4115         [ +  - ]:         78 :       if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    4116                 :            :         break;
    4117                 :         78 :     }
    4118         [ +  - ]:         35 :   files.reset();
    4119                 :            : 
    4120                 :            :   // ACTION TIME
    4121                 :            : 
    4122                 :            :   // Now that we know which file/mtime tuples are stale, actually do
    4123                 :            :   // the deletion from the database.  Doing this during the SELECT
    4124                 :            :   // iteration above results in undefined behaviour in sqlite, as per
    4125                 :            :   // https://www.sqlite.org/isolation.html
    4126                 :            : 
    4127                 :            :   // We could shuffle stale_fileid_mtime[] here.  It'd let aborted
    4128                 :            :   // sequences of nuke operations resume at random locations, instead
    4129                 :            :   // of just starting over.  But it doesn't matter much either way,
    4130                 :            :   // as long as we make progress.
    4131                 :            : 
    4132   [ +  -  +  -  :         70 :   sqlite_ps files_del_f_de (db, "nuke f_de", "delete from " BUILDIDS "_f_de where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    4133   [ +  -  +  -  :         70 :   sqlite_ps files_del_r_de (db, "nuke r_de", "delete from " BUILDIDS "_r_de where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    4134         [ +  - ]:         35 :   sqlite_ps files_del_scan (db, "nuke f_m_s", "delete from " BUILDIDS "_file_mtime_scanned "
    4135   [ +  -  +  -  :         70 :                             "where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    4136                 :            : 
    4137         [ +  + ]:         47 :   while (! stale_fileid_mtime.empty())
    4138                 :            :     {
    4139                 :         12 :       auto stale = stale_fileid_mtime.front();
    4140                 :         12 :       stale_fileid_mtime.pop_front();
    4141   [ +  -  +  -  :         24 :       set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4142                 :            : 
    4143                 :            :       // PR28514: limit grooming iteration to O(rescan time), to avoid
    4144                 :            :       // slow nuke_* queries over many files locking out rescans for too
    4145                 :            :       // long.  We iterate over the files in random() sequence to avoid
    4146                 :            :       // partial checks going over the same set.
    4147   [ -  +  -  - ]:         12 :       if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
    4148                 :            :         {
    4149   [ #  #  #  #  :          0 :           inc_metric("groomed_total", "action", "aborted");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    4150                 :          0 :           break;
    4151                 :            :         }
    4152                 :            : 
    4153         [ +  - ]:         12 :       if (interrupted) break;
    4154                 :            : 
    4155                 :         12 :       int64_t fileid = stale.first;
    4156                 :         12 :       int64_t mtime = stale.second;
    4157   [ +  -  +  -  :         12 :       files_del_f_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    4158   [ +  -  +  -  :         12 :       files_del_r_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    4159   [ +  -  +  -  :         12 :       files_del_scan.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    4160   [ +  -  +  -  :         24 :       inc_metric("groomed_total", "action", "cleaned");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4161                 :            :       
    4162         [ +  - ]:         12 :        if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    4163                 :            :         break;
    4164                 :            :     }
    4165                 :         35 :   stale_fileid_mtime.clear(); // no need for this any longer
    4166   [ +  -  +  -  :         70 :   set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4167                 :            :       
    4168                 :            :   // delete buildids with no references in _r_de or _f_de tables;
    4169                 :            :   // cascades to _r_sref & _f_s records
    4170         [ +  - ]:         35 :   sqlite_ps buildids_del (db, "nuke orphan buildids",
    4171                 :            :                           "delete from " BUILDIDS "_buildids "
    4172                 :            :                           "where not exists (select 1 from " BUILDIDS "_f_de d where " BUILDIDS "_buildids.id = d.buildid) "
    4173   [ +  -  +  -  :         70 :                           "and not exists (select 1 from " BUILDIDS "_r_de d where " BUILDIDS "_buildids.id = d.buildid)");
          +  -  +  -  -  
                      - ]
    4174   [ +  -  +  - ]:         35 :   buildids_del.reset().step_ok_done();
    4175                 :            : 
    4176         [ -  + ]:         35 :   if (interrupted) return;
    4177                 :            : 
    4178                 :            :   // NB: "vacuum" is too heavy for even daily runs: it rewrites the entire db, so is done as maxigroom -G
    4179   [ +  -  +  -  :         70 :   sqlite_ps g1 (db, "incremental vacuum", "pragma incremental_vacuum");
          +  -  +  -  -  
                      - ]
    4180   [ +  -  +  - ]:         35 :   g1.reset().step_ok_done();
    4181   [ +  -  +  -  :         70 :   sqlite_ps g2 (db, "optimize", "pragma optimize");
          +  -  -  +  -  
                      - ]
    4182   [ +  -  +  - ]:         35 :   g2.reset().step_ok_done();
    4183   [ +  -  +  -  :         70 :   sqlite_ps g3 (db, "wal checkpoint", "pragma wal_checkpoint=truncate");
          +  -  +  -  -  
                      - ]
    4184   [ +  -  +  - ]:         35 :   g3.reset().step_ok_done();
    4185                 :            : 
    4186         [ +  - ]:         35 :   database_stats_report();
    4187                 :            : 
    4188   [ +  -  +  - ]:         35 :   (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
    4189                 :            : 
    4190         [ +  - ]:         35 :   sqlite3_db_release_memory(db); // shrink the process if possible
    4191         [ +  - ]:         35 :   sqlite3_db_release_memory(dbq); // ... for both connections
    4192         [ +  - ]:         35 :   debuginfod_pool_groom(); // and release any debuginfod_client objects we've been holding onto
    4193                 :            : 
    4194         [ +  - ]:         35 :   fdcache.limit(0,0,0,0); // release the fdcache contents
    4195         [ +  - ]:         35 :   fdcache.limit(fdcache_fds, fdcache_mbs, fdcache_prefetch_fds, fdcache_prefetch_mbs); // restore status quo parameters
    4196                 :            : 
    4197                 :         35 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    4198                 :         35 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    4199                 :            : 
    4200   [ +  -  +  -  :         70 :   obatched(clog) << "groomed database in " << deltas << "s" << endl;
             +  -  +  - ]
    4201                 :         35 : }
    4202                 :            : 
    4203                 :            : 
    4204                 :            : static void*
    4205                 :         35 : thread_main_groom (void* /*arg*/)
    4206                 :            : {
    4207   [ +  -  +  -  :         70 :   set_metric("thread_tid", "role", "groom", tid());
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4208   [ +  -  +  -  :         70 :   add_metric("thread_count", "role", "groom", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4209                 :            : 
    4210                 :         35 :   time_t last_groom = 0;
    4211                 :            : 
    4212                 :        293 :   while (1)
    4213                 :            :     {
    4214                 :        164 :       sleep (1);
    4215                 :        164 :       scanq.wait_idle(); // PR25394: block scanners during grooming!
    4216         [ +  + ]:        164 :       if (interrupted) break;
    4217                 :            : 
    4218                 :        129 :       time_t now = time(NULL);
    4219                 :        129 :       bool groom_now = false;
    4220         [ +  + ]:        129 :       if (last_groom == 0) // at least one initial groom is documented even for -g0
    4221                 :         32 :         groom_now = true;
    4222   [ +  +  +  + ]:        129 :       if (groom_s > 0 && (long)now > (long)(last_groom + groom_s))
    4223                 :        129 :         groom_now = true;
    4224         [ +  + ]:        129 :       if (sigusr2 != forced_groom_count)
    4225                 :            :         {
    4226                 :          3 :           forced_groom_count = sigusr2;
    4227                 :          3 :           groom_now = true;
    4228                 :            :         }
    4229         [ +  + ]:        129 :       if (groom_now)
    4230                 :            :         {
    4231   [ +  -  +  -  :         70 :           set_metric("thread_busy", "role", "groom", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4232                 :         35 :           try
    4233                 :            :             {
    4234         [ +  - ]:         35 :               groom ();
    4235                 :            :             }
    4236         [ -  - ]:          0 :           catch (const sqlite_exception& e)
    4237                 :            :             {
    4238   [ -  -  -  -  :          0 :               obatched(cerr) << e.message << endl;
                   -  - ]
    4239                 :          0 :             }
    4240                 :         35 :           last_groom = time(NULL); // NB: now was before grooming
    4241                 :            :           // finished a grooming loop
    4242   [ +  -  +  -  :         70 :           inc_metric("thread_work_total", "role", "groom");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4243   [ +  -  +  -  :         70 :           set_metric("thread_busy", "role", "groom", 0);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4244                 :            :         }
    4245                 :            : 
    4246                 :        129 :       scanq.done_idle();
    4247                 :        129 :     }
    4248                 :            : 
    4249                 :         35 :   return 0;
    4250                 :            : }
    4251                 :            : 
    4252                 :            : 
    4253                 :            : ////////////////////////////////////////////////////////////////////////
    4254                 :            : 
    4255                 :            : 
    4256                 :            : static void
    4257                 :         36 : signal_handler (int /* sig */)
    4258                 :            : {
    4259                 :         36 :   interrupted ++;
    4260                 :            : 
    4261         [ +  + ]:         36 :   if (db)
    4262                 :         35 :     sqlite3_interrupt (db);
    4263         [ +  - ]:         36 :   if (dbq)
    4264                 :         36 :     sqlite3_interrupt (dbq);
    4265                 :            : 
    4266                 :            :   // NB: don't do anything else in here
    4267                 :         36 : }
    4268                 :            : 
    4269                 :            : static void
    4270                 :         31 : sigusr1_handler (int /* sig */)
    4271                 :            : {
    4272                 :         31 :    sigusr1 ++;
    4273                 :            :   // NB: don't do anything else in here
    4274                 :         31 : }
    4275                 :            : 
    4276                 :            : static void
    4277                 :          3 : sigusr2_handler (int /* sig */)
    4278                 :            : {
    4279                 :          3 :    sigusr2 ++;
    4280                 :            :   // NB: don't do anything else in here
    4281                 :          3 : }
    4282                 :            : 
    4283                 :            : 
    4284                 :            : static void // error logging callback from libmicrohttpd internals
    4285                 :          0 : error_cb (void *arg, const char *fmt, va_list ap)
    4286                 :            : {
    4287                 :          0 :   (void) arg;
    4288   [ #  #  #  #  :          0 :   inc_metric("error_count","libmicrohttpd",fmt);
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    4289                 :          0 :   char errmsg[512];
    4290                 :          0 :   (void) vsnprintf (errmsg, sizeof(errmsg), fmt, ap); // ok if slightly truncated
    4291         [ #  # ]:          0 :   obatched(cerr) << "libmicrohttpd error: " << errmsg; // MHD_DLOG calls already include \n
    4292                 :          0 : }
    4293                 :            : 
    4294                 :            : 
    4295                 :            : // A user-defined sqlite function, to score the sharedness of the
    4296                 :            : // prefix of two strings.  This is used to compare candidate debuginfo
    4297                 :            : // / source-rpm names, so that the closest match
    4298                 :            : // (directory-topology-wise closest) is found.  This is important in
    4299                 :            : // case the same sref (source file name) is in many -debuginfo or
    4300                 :            : // -debugsource RPMs, such as when multiple versions/releases of the
    4301                 :            : // same package are in the database.
    4302                 :            : 
    4303                 :        148 : static void sqlite3_sharedprefix_fn (sqlite3_context* c, int argc, sqlite3_value** argv)
    4304                 :            : {
    4305         [ -  + ]:        148 :   if (argc != 2)
    4306                 :          0 :     sqlite3_result_error(c, "expect 2 string arguments", -1);
    4307   [ +  -  +  + ]:        296 :   else if ((sqlite3_value_type(argv[0]) != SQLITE_TEXT) ||
    4308                 :        148 :            (sqlite3_value_type(argv[1]) != SQLITE_TEXT))
    4309                 :          3 :     sqlite3_result_null(c);
    4310                 :            :   else
    4311                 :            :     {
    4312                 :        145 :       const unsigned char* a = sqlite3_value_text (argv[0]);
    4313                 :        145 :       const unsigned char* b = sqlite3_value_text (argv[1]);
    4314                 :        145 :       int i = 0;
    4315   [ +  +  +  -  :      17939 :       while (*a != '\0' && *b != '\0' && *a++ == *b++)
             +  +  +  + ]
    4316                 :      17524 :         i++;
    4317                 :        145 :       sqlite3_result_int (c, i);
    4318                 :            :     }
    4319                 :        148 : }
    4320                 :            : 
    4321                 :            : 
    4322                 :            : static unsigned
    4323                 :         70 : default_concurrency() // guaranteed >= 1
    4324                 :            : {
    4325                 :            :   // Prior to PR29975 & PR29976, we'd just use this: 
    4326                 :         70 :   unsigned sth = std::thread::hardware_concurrency();
    4327                 :            :   // ... but on many-CPU boxes, admins or distros may throttle
    4328                 :            :   // resources in such a way that debuginfod would mysteriously fail.
    4329                 :            :   // So we reduce the defaults:
    4330                 :            : 
    4331                 :         70 :   unsigned aff = 0;
    4332                 :            : #ifdef HAVE_SCHED_GETAFFINITY
    4333                 :         70 :   {
    4334                 :         70 :     int ret;
    4335                 :         70 :     cpu_set_t mask;
    4336                 :         70 :     CPU_ZERO(&mask);
    4337                 :         70 :     ret = sched_getaffinity(0, sizeof(mask), &mask);
    4338         [ +  - ]:         70 :     if (ret == 0)
    4339                 :         70 :       aff = CPU_COUNT(&mask);
    4340                 :            :   }
    4341                 :            : #endif
    4342                 :            :   
    4343                 :         70 :   unsigned fn = 0;
    4344                 :            : #ifdef HAVE_GETRLIMIT
    4345                 :         70 :   {
    4346                 :         70 :     struct rlimit rlim;
    4347                 :         70 :     int rc = getrlimit(RLIMIT_NOFILE, &rlim);
    4348         [ +  - ]:         70 :     if (rc == 0)
    4349         [ +  - ]:        140 :       fn = max((rlim_t)1, (rlim.rlim_cur - 100) / 4);
    4350                 :            :     // at least 2 fds are used by each listener thread etc.
    4351                 :            :     // plus a bunch to account for shared libraries and such
    4352                 :            :   }
    4353                 :            : #endif
    4354                 :            : 
    4355   [ -  +  -  +  :         70 :   unsigned d = min(max(sth, 1U),
                   -  + ]
    4356         [ -  + ]:         70 :                    min(max(aff, 1U),
    4357         [ -  + ]:         70 :                        max(fn, 1U)));
    4358                 :         70 :   return d;
    4359                 :            : }
    4360                 :            : 
    4361                 :            : 
    4362                 :            : 
    4363                 :            : int
    4364                 :         36 : main (int argc, char *argv[])
    4365                 :            : {
    4366                 :         36 :   (void) setlocale (LC_ALL, "");
    4367                 :         36 :   (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
    4368                 :         36 :   (void) textdomain (PACKAGE_TARNAME);
    4369                 :            : 
    4370                 :            :   /* Tell the library which version we are expecting.  */
    4371                 :         36 :   elf_version (EV_CURRENT);
    4372                 :            : 
    4373   [ +  -  -  + ]:         72 :   tmpdir = string(getenv("TMPDIR") ?: "/tmp");
    4374                 :            : 
    4375                 :            :   /* Set computed default values. */
    4376   [ -  +  +  -  :         36 :   db_path = string(getenv("HOME") ?: "/") + string("/.debuginfod.sqlite"); /* XDG? */
          +  -  -  +  -  
             +  +  -  -  
                      - ]
    4377                 :         36 :   int rc = regcomp (& file_include_regex, ".*", REG_EXTENDED|REG_NOSUB); // match everything
    4378         [ -  + ]:         36 :   if (rc != 0)
    4379                 :          0 :     error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
    4380                 :         36 :   rc = regcomp (& file_exclude_regex, "^$", REG_EXTENDED|REG_NOSUB); // match nothing
    4381         [ -  + ]:         36 :   if (rc != 0)
    4382                 :          0 :     error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
    4383                 :            : 
    4384                 :            :   // default parameters for fdcache are computed from system stats
    4385                 :         36 :   struct statfs sfs;
    4386                 :         36 :   rc = statfs(tmpdir.c_str(), &sfs);
    4387         [ -  + ]:         36 :   if (rc < 0)
    4388                 :          0 :     fdcache_mbs = 1024; // 1 gigabyte
    4389                 :            :   else
    4390                 :         36 :     fdcache_mbs = sfs.f_bavail * sfs.f_bsize / 1024 / 1024 / 4; // 25% of free space
    4391                 :         36 :   fdcache_mintmp = 25; // emergency flush at 25% remaining (75% full)
    4392                 :         36 :   fdcache_prefetch = 64; // guesstimate storage is this much less costly than re-decompression
    4393                 :         36 :   fdcache_fds = (concurrency + fdcache_prefetch) * 2;
    4394                 :            : 
    4395                 :            :   /* Parse and process arguments.  */
    4396                 :         36 :   int remaining;
    4397                 :         36 :   (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
    4398         [ -  + ]:         36 :   if (remaining != argc)
    4399                 :          0 :       error (EXIT_FAILURE, 0,
    4400                 :          0 :              "unexpected argument: %s", argv[remaining]);
    4401                 :            : 
    4402                 :            :   // Make the prefetch cache spaces a fraction of the main fdcache if
    4403                 :            :   // unspecified.
    4404         [ +  + ]:         36 :   if (fdcache_prefetch_fds == 0)
    4405                 :         35 :     fdcache_prefetch_fds = fdcache_fds / 2;
    4406         [ +  + ]:         36 :   if (fdcache_prefetch_mbs == 0)
    4407                 :         35 :     fdcache_prefetch_mbs = fdcache_mbs / 2;
    4408                 :            : 
    4409   [ +  +  +  +  :         36 :   if (scan_archives.size()==0 && !scan_files && source_paths.size()>0)
                   -  + ]
    4410         [ #  # ]:          0 :     obatched(clog) << "warning: without -F -R -U -Z, ignoring PATHs" << endl;
    4411                 :            : 
    4412                 :         36 :   fdcache.limit(fdcache_fds, fdcache_mbs, fdcache_prefetch_fds, fdcache_prefetch_mbs);
    4413                 :            : 
    4414                 :         36 :   (void) signal (SIGPIPE, SIG_IGN); // microhttpd can generate it incidentally, ignore
    4415                 :         36 :   (void) signal (SIGINT, signal_handler); // ^C
    4416                 :         36 :   (void) signal (SIGHUP, signal_handler); // EOF
    4417                 :         36 :   (void) signal (SIGTERM, signal_handler); // systemd
    4418                 :         36 :   (void) signal (SIGUSR1, sigusr1_handler); // end-user
    4419                 :         36 :   (void) signal (SIGUSR2, sigusr2_handler); // end-user
    4420                 :            : 
    4421                 :            :   /* Get database ready. */
    4422         [ +  + ]:         36 :   if (! passive_p)
    4423                 :            :     {
    4424                 :         35 :       rc = sqlite3_open_v2 (db_path.c_str(), &db, (SQLITE_OPEN_READWRITE
    4425                 :            :                                                    |SQLITE_OPEN_URI
    4426                 :            :                                                    |SQLITE_OPEN_PRIVATECACHE
    4427                 :            :                                                    |SQLITE_OPEN_CREATE
    4428                 :            :                                                    |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
    4429                 :            :                             NULL);
    4430         [ -  + ]:         35 :       if (rc == SQLITE_CORRUPT)
    4431                 :            :         {
    4432                 :          0 :           (void) unlink (db_path.c_str());
    4433                 :          0 :           error (EXIT_FAILURE, 0,
    4434                 :            :                  "cannot open %s, deleted database: %s", db_path.c_str(), sqlite3_errmsg(db));
    4435                 :            :         }
    4436         [ -  + ]:         35 :       else if (rc)
    4437                 :            :         {
    4438                 :          0 :           error (EXIT_FAILURE, 0,
    4439                 :            :                  "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(db));
    4440                 :            :         }
    4441                 :            :     }
    4442                 :            : 
    4443                 :            :   // open the readonly query variant
    4444                 :            :   // NB: PRIVATECACHE allows web queries to operate in parallel with
    4445                 :            :   // much other grooming/scanning operation.
    4446                 :         36 :   rc = sqlite3_open_v2 (db_path.c_str(), &dbq, (SQLITE_OPEN_READONLY
    4447                 :            :                                                 |SQLITE_OPEN_URI
    4448                 :            :                                                 |SQLITE_OPEN_PRIVATECACHE
    4449                 :            :                                                 |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
    4450                 :            :                         NULL);
    4451         [ -  + ]:         36 :   if (rc)
    4452                 :            :     {
    4453                 :          0 :       error (EXIT_FAILURE, 0,
    4454                 :            :              "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(dbq));
    4455                 :            :     }
    4456                 :            : 
    4457                 :            : 
    4458         [ +  - ]:         72 :   obatched(clog) << "opened database " << db_path
    4459   [ +  +  +  -  :         37 :                  << (db?" rw":"") << (dbq?" ro":"") << endl;
          -  +  +  -  +  
                      - ]
    4460   [ +  -  +  - ]:         72 :   obatched(clog) << "sqlite version " << sqlite3_version << endl;
    4461   [ +  +  +  -  :        107 :   obatched(clog) << "service mode " << (passive_p ? "passive":"active") << endl;
                   +  - ]
    4462                 :            : 
    4463                 :            :   // add special string-prefix-similarity function used in rpm sref/sdef resolution
    4464                 :         36 :   rc = sqlite3_create_function(dbq, "sharedprefix", 2, SQLITE_UTF8, NULL,
    4465                 :            :                                & sqlite3_sharedprefix_fn, NULL, NULL);
    4466         [ -  + ]:         36 :   if (rc != SQLITE_OK)
    4467                 :          0 :     error (EXIT_FAILURE, 0,
    4468                 :            :            "cannot create sharedprefix function: %s", sqlite3_errmsg(dbq));
    4469                 :            : 
    4470         [ +  + ]:         36 :   if (! passive_p)
    4471                 :            :     {
    4472         [ +  + ]:         35 :       if (verbose > 3)
    4473   [ +  -  +  - ]:         44 :         obatched(clog) << "ddl: " << DEBUGINFOD_SQLITE_DDL << endl;
    4474                 :         35 :       rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_DDL, NULL, NULL, NULL);
    4475         [ -  + ]:         35 :       if (rc != SQLITE_OK)
    4476                 :            :         {
    4477                 :          0 :           error (EXIT_FAILURE, 0,
    4478                 :            :                  "cannot run database schema ddl: %s", sqlite3_errmsg(db));
    4479                 :            :         }
    4480                 :            :     }
    4481                 :            : 
    4482   [ +  -  +  -  :         72 :   obatched(clog) << "libmicrohttpd version " << MHD_get_version() << endl;
                   +  - ]
    4483                 :            :   
    4484                 :            :   /* If '-C' wasn't given or was given with no arg, pick a reasonable default
    4485                 :            :      for the number of worker threads.  */
    4486         [ +  + ]:         36 :   if (connection_pool == 0)
    4487                 :         34 :     connection_pool = default_concurrency();
    4488                 :            : 
    4489                 :            :   /* Note that MHD_USE_EPOLL and MHD_USE_THREAD_PER_CONNECTION don't
    4490                 :            :      work together.  */
    4491                 :         36 :   unsigned int use_epoll = 0;
    4492                 :            : #if MHD_VERSION >= 0x00095100
    4493                 :         36 :   use_epoll = MHD_USE_EPOLL;
    4494                 :            : #endif
    4495                 :            : 
    4496                 :         36 :   unsigned int mhd_flags = (
    4497                 :            : #if MHD_VERSION >= 0x00095300
    4498                 :            :                             MHD_USE_INTERNAL_POLLING_THREAD
    4499                 :            : #else
    4500                 :            :                             MHD_USE_SELECT_INTERNALLY
    4501                 :            : #endif
    4502                 :            :                             | MHD_USE_DUAL_STACK
    4503                 :            :                             | use_epoll
    4504                 :            : #if MHD_VERSION >= 0x00095200
    4505                 :            :                             | MHD_USE_ITC
    4506                 :            : #endif
    4507                 :            :                             | MHD_USE_DEBUG); /* report errors to stderr */
    4508                 :            : 
    4509                 :            :   // Start httpd server threads.  Use a single dual-homed pool.
    4510                 :         36 :   MHD_Daemon *d46 = MHD_start_daemon (mhd_flags, http_port,
    4511                 :            :                                       NULL, NULL, /* default accept policy */
    4512                 :            :                                       handler_cb, NULL, /* handler callback */
    4513                 :            :                                       MHD_OPTION_EXTERNAL_LOGGER,
    4514                 :            :                                       error_cb, NULL,
    4515                 :            :                                       MHD_OPTION_THREAD_POOL_SIZE,
    4516                 :            :                                       (int)connection_pool,
    4517                 :            :                                       MHD_OPTION_END);
    4518                 :            : 
    4519                 :         36 :   MHD_Daemon *d4 = NULL;
    4520         [ -  + ]:         36 :   if (d46 == NULL)
    4521                 :            :     {
    4522                 :            :       // Cannot use dual_stack, use ipv4 only
    4523                 :          0 :       mhd_flags &= ~(MHD_USE_DUAL_STACK);
    4524         [ #  # ]:          0 :       d4 = MHD_start_daemon (mhd_flags, http_port,
    4525                 :            :                              NULL, NULL, /* default accept policy */
    4526                 :            :                              handler_cb, NULL, /* handler callback */
    4527                 :            :                              MHD_OPTION_EXTERNAL_LOGGER,
    4528                 :            :                              error_cb, NULL,
    4529                 :            :                              (connection_pool
    4530                 :            :                               ? MHD_OPTION_THREAD_POOL_SIZE
    4531                 :            :                               : MHD_OPTION_END),
    4532                 :            :                              (connection_pool
    4533                 :            :                               ? (int)connection_pool
    4534                 :            :                               : MHD_OPTION_END),
    4535                 :            :                              MHD_OPTION_END);
    4536         [ #  # ]:          0 :       if (d4 == NULL)
    4537                 :            :         {
    4538                 :          0 :           sqlite3 *database = db;
    4539                 :          0 :           sqlite3 *databaseq = dbq;
    4540                 :          0 :           db = dbq = 0; // for signal_handler not to freak
    4541                 :          0 :           sqlite3_close (databaseq);
    4542                 :          0 :           sqlite3_close (database);
    4543                 :          0 :           error (EXIT_FAILURE, 0, "cannot start http server at port %d",
    4544                 :            :                  http_port);
    4545                 :            :         }
    4546                 :            : 
    4547                 :            :     }
    4548                 :         36 :   obatched(clog) << "started http server on"
    4549                 :            :                  << (d4 != NULL ? " IPv4 " : " IPv4 IPv6 ")
    4550   [ +  -  +  -  :         72 :                  << "port=" << http_port << endl;
          +  -  +  -  +  
                      - ]
    4551                 :            : 
    4552                 :            :   // add maxigroom sql if -G given
    4553         [ -  + ]:         36 :   if (maxigroom)
    4554                 :            :     {
    4555         [ #  # ]:          0 :       obatched(clog) << "maxigrooming database, please wait." << endl;
    4556         [ #  # ]:          0 :       extra_ddl.push_back("create index if not exists " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);");
    4557         [ #  # ]:          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);");
    4558         [ #  # ]:          0 :       extra_ddl.push_back("drop index if exists " BUILDIDS "_r_sref_arc;");
    4559                 :            : 
    4560                 :            :       // NB: we don't maxigroom the _files interning table.  It'd require a temp index on all the
    4561                 :            :       // tables that have file foreign-keys, which is a lot.
    4562                 :            : 
    4563                 :            :       // NB: with =delete, may take up 3x disk space total during vacuum process
    4564                 :            :       //     vs.  =off (only 2x but may corrupt database if program dies mid-vacuum)
    4565                 :            :       //     vs.  =wal (>3x observed, but safe)
    4566         [ #  # ]:          0 :       extra_ddl.push_back("pragma journal_mode=delete;");
    4567         [ #  # ]:          0 :       extra_ddl.push_back("vacuum;");
    4568         [ #  # ]:          0 :       extra_ddl.push_back("pragma journal_mode=wal;");
    4569                 :            :     }
    4570                 :            : 
    4571                 :            :   // run extra -D sql if given
    4572         [ +  + ]:         36 :   if (! passive_p)
    4573         [ -  + ]:         35 :     for (auto&& i: extra_ddl)
    4574                 :            :       {
    4575         [ #  # ]:          0 :         if (verbose > 1)
    4576   [ #  #  #  # ]:          0 :           obatched(clog) << "extra ddl:\n" << i << endl;
    4577                 :          0 :         rc = sqlite3_exec (db, i.c_str(), NULL, NULL, NULL);
    4578   [ #  #  #  # ]:          0 :         if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
    4579                 :          0 :           error (0, 0,
    4580                 :            :                  "warning: cannot run database extra ddl %s: %s", i.c_str(), sqlite3_errmsg(db));
    4581                 :            : 
    4582         [ #  # ]:          0 :         if (maxigroom)
    4583         [ #  # ]:          0 :           obatched(clog) << "maxigroomed database" << endl;
    4584                 :            :       }
    4585                 :            : 
    4586         [ +  + ]:         36 :   if (! passive_p)
    4587   [ +  -  +  - ]:         70 :     obatched(clog) << "search concurrency " << concurrency << endl;
    4588                 :         36 :   obatched(clog) << "webapi connection pool " << connection_pool
    4589   [ +  -  -  +  :         36 :                  << (connection_pool ? "" : " (unlimited)") << endl;
             +  -  +  - ]
    4590         [ +  + ]:         36 :   if (! passive_p) {
    4591   [ +  -  +  - ]:         70 :     obatched(clog) << "rescan time " << rescan_s << endl;
    4592   [ +  -  +  - ]:         70 :     obatched(clog) << "scan checkpoint " << scan_checkpoint << endl;
    4593                 :            :   }
    4594   [ +  -  +  - ]:         72 :   obatched(clog) << "fdcache fds " << fdcache_fds << endl;
    4595   [ +  -  +  - ]:         72 :   obatched(clog) << "fdcache mbs " << fdcache_mbs << endl;
    4596   [ +  -  +  - ]:         72 :   obatched(clog) << "fdcache prefetch " << fdcache_prefetch << endl;
    4597   [ +  -  +  - ]:         72 :   obatched(clog) << "fdcache tmpdir " << tmpdir << endl;
    4598   [ +  -  +  - ]:         72 :   obatched(clog) << "fdcache tmpdir min% " << fdcache_mintmp << endl;
    4599         [ +  + ]:         36 :   if (! passive_p)
    4600   [ +  -  +  - ]:         70 :     obatched(clog) << "groom time " << groom_s << endl;
    4601   [ +  -  +  - ]:         72 :   obatched(clog) << "prefetch fds " << fdcache_prefetch_fds << endl;
    4602   [ +  -  +  - ]:         72 :   obatched(clog) << "prefetch mbs " << fdcache_prefetch_mbs << endl;
    4603   [ +  -  +  - ]:         72 :   obatched(clog) << "forwarded ttl limit " << forwarded_ttl_limit << endl;
    4604                 :            : 
    4605         [ +  + ]:         36 :   if (scan_archives.size()>0)
    4606                 :            :     {
    4607                 :         25 :       obatched ob(clog);
    4608         [ +  - ]:         25 :       auto& o = ob << "accepting archive types ";
    4609         [ +  + ]:         76 :       for (auto&& arch : scan_archives)
    4610   [ +  -  +  -  :         51 :         o << arch.first << "(" << arch.second << ") ";
             +  -  +  - ]
    4611         [ +  - ]:         25 :       o << endl;
    4612                 :         25 :     }
    4613                 :         36 :   const char* du = getenv(DEBUGINFOD_URLS_ENV_VAR);
    4614   [ +  +  +  + ]:         36 :   if (du && du[0] != '\0') // set to non-empty string?
    4615   [ +  -  +  - ]:         14 :     obatched(clog) << "upstream debuginfod servers: " << du << endl;
    4616                 :            : 
    4617         [ +  + ]:         36 :   vector<pthread_t> all_threads;
    4618                 :            : 
    4619         [ +  + ]:         36 :   if (! passive_p)
    4620                 :            :     {
    4621                 :         35 :       pthread_t pt;
    4622                 :         35 :       rc = pthread_create (& pt, NULL, thread_main_groom, NULL);
    4623         [ -  + ]:         35 :       if (rc)
    4624                 :          0 :         error (EXIT_FAILURE, rc, "cannot spawn thread to groom database\n");
    4625                 :            :       else
    4626                 :            :         {
    4627                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    4628                 :         35 :           (void) pthread_setname_np (pt, "groom");
    4629                 :            : #endif
    4630         [ +  - ]:         35 :           all_threads.push_back(pt);
    4631                 :            :         }
    4632                 :            : 
    4633   [ +  +  +  + ]:         35 :       if (scan_files || scan_archives.size() > 0)
    4634                 :            :         {
    4635         [ +  - ]:         32 :           if (scan_checkpoint > 0)
    4636   [ +  -  +  - ]:         32 :             scan_barrier = new sqlite_checkpoint_pb(concurrency, (unsigned) scan_checkpoint);
    4637                 :            : 
    4638                 :         32 :           rc = pthread_create (& pt, NULL, thread_main_fts_source_paths, NULL);
    4639         [ -  + ]:         32 :           if (rc)
    4640                 :          0 :             error (EXIT_FAILURE, rc, "cannot spawn thread to traverse source paths\n");
    4641                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    4642                 :         32 :           (void) pthread_setname_np (pt, "traverse");
    4643                 :            : #endif
    4644         [ +  - ]:         32 :           all_threads.push_back(pt);
    4645                 :            : 
    4646         [ +  + ]:        160 :           for (unsigned i=0; i<concurrency; i++)
    4647                 :            :             {
    4648                 :        128 :               rc = pthread_create (& pt, NULL, thread_main_scanner, NULL);
    4649         [ -  + ]:        128 :               if (rc)
    4650                 :          0 :                 error (EXIT_FAILURE, rc, "cannot spawn thread to scan source files / archives\n");
    4651                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    4652                 :        128 :               (void) pthread_setname_np (pt, "scan");
    4653                 :            : #endif
    4654         [ +  - ]:        128 :               all_threads.push_back(pt);
    4655                 :            :             }
    4656                 :            :         }
    4657                 :            :     }
    4658                 :            :   
    4659                 :            :   /* Trivial main loop! */
    4660   [ +  -  +  - ]:         36 :   set_metric("ready", 1);
    4661         [ +  + ]:        106 :   while (! interrupted)
    4662         [ +  - ]:         70 :     pause ();
    4663         [ +  - ]:         36 :   scanq.nuke(); // wake up any remaining scanq-related threads, let them die
    4664   [ +  +  +  - ]:         36 :   if (scan_barrier) scan_barrier->nuke(); // ... in case they're stuck in a barrier
    4665   [ +  -  +  - ]:         36 :   set_metric("ready", 0);
    4666                 :            : 
    4667         [ +  - ]:         36 :   if (verbose)
    4668   [ +  -  +  -  :         72 :     obatched(clog) << "stopping" << endl;
                   -  - ]
    4669                 :            : 
    4670                 :            :   /* Join all our threads. */
    4671         [ +  + ]:        231 :   for (auto&& it : all_threads)
    4672         [ +  - ]:        195 :     pthread_join (it, NULL);
    4673                 :            : 
    4674                 :            :   /* Stop all the web service threads. */
    4675   [ +  -  +  - ]:         36 :   if (d46) MHD_stop_daemon (d46);
    4676   [ -  +  -  - ]:         36 :   if (d4) MHD_stop_daemon (d4);
    4677                 :            : 
    4678         [ +  + ]:         36 :   if (! passive_p)
    4679                 :            :     {
    4680                 :            :       /* With all threads known dead, we can clean up the global resources. */
    4681         [ +  - ]:         35 :       rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_CLEANUP_DDL, NULL, NULL, NULL);
    4682         [ -  + ]:         35 :       if (rc != SQLITE_OK)
    4683                 :            :         {
    4684   [ #  #  #  # ]:          0 :           error (0, 0,
    4685                 :            :                  "warning: cannot run database cleanup ddl: %s", sqlite3_errmsg(db));
    4686                 :            :         }
    4687                 :            :     }
    4688                 :            : 
    4689         [ +  - ]:         36 :   debuginfod_pool_groom ();
    4690         [ +  + ]:         36 :   delete scan_barrier;
    4691                 :            : 
    4692                 :            :   // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
    4693         [ +  - ]:         36 :   (void) regfree (& file_include_regex);
    4694         [ +  - ]:         36 :   (void) regfree (& file_exclude_regex);
    4695                 :            : 
    4696                 :         36 :   sqlite3 *database = db;
    4697                 :         36 :   sqlite3 *databaseq = dbq;
    4698                 :         36 :   db = dbq = 0; // for signal_handler not to freak
    4699         [ +  - ]:         36 :   (void) sqlite3_close (databaseq);
    4700         [ +  + ]:         36 :   if (! passive_p)
    4701         [ +  - ]:         35 :     (void) sqlite3_close (database);
    4702                 :            : 
    4703         [ +  + ]:         36 :   return 0;
    4704                 :         36 : }

Generated by: LCOV version 1.16