LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Hit Total Coverage
Test: elfutils-0.186 Lines: 1534 1801 85.2 %
Date: 2021-11-11 00:14:10 Functions: 115 126 91.3 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 2005 4194 47.8 %

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

Generated by: LCOV version 1.14