]> git.sesse.net Git - plocate/blob - plocate.cpp
Bump version number.
[plocate] / plocate.cpp
1 #include "access_rx_cache.h"
2 #include "complete_pread.h"
3 #include "db.h"
4 #include "dprintf.h"
5 #include "io_uring_engine.h"
6 #include "needle.h"
7 #include "parse_trigrams.h"
8 #include "serializer.h"
9 #include "turbopfor.h"
10 #include "unique_sort.h"
11
12 #include <algorithm>
13 #include <assert.h>
14 #include <atomic>
15 #include <chrono>
16 #include <condition_variable>
17 #include <deque>
18 #include <fcntl.h>
19 #include <functional>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <iterator>
23 #include <limits>
24 #include <locale.h>
25 #include <memory>
26 #include <mutex>
27 #include <regex.h>
28 #include <stdint.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <string>
33 #include <string_view>
34 #include <thread>
35 #include <tuple>
36 #include <unistd.h>
37 #include <unordered_map>
38 #include <unordered_set>
39 #include <utility>
40 #include <vector>
41 #include <zstd.h>
42
43 using namespace std;
44 using namespace std::chrono;
45
46 const char *dbpath = DBFILE;
47 bool ignore_case = false;
48 bool only_count = false;
49 bool print_nul = false;
50 bool use_debug = false;
51 bool flush_cache = false;
52 bool patterns_are_regex = false;
53 bool use_extended_regex = false;
54 bool match_basename = false;
55 int64_t limit_matches = numeric_limits<int64_t>::max();
56 int64_t limit_left = numeric_limits<int64_t>::max();
57 bool stdout_is_tty = false;
58
59 steady_clock::time_point start;
60 ZSTD_DDict *ddict = nullptr;
61
62 class Corpus {
63 public:
64         Corpus(int fd, IOUringEngine *engine);
65         ~Corpus();
66         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
67         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
68         size_t get_num_filename_blocks() const;
69         off_t offset_for_block(uint32_t docid) const
70         {
71                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
72         }
73         const Header &get_hdr() const { return hdr; }
74
75 public:
76         const int fd;
77         IOUringEngine *const engine;
78
79         Header hdr;
80 };
81
82 Corpus::Corpus(int fd, IOUringEngine *engine)
83         : fd(fd), engine(engine)
84 {
85         if (flush_cache) {
86                 off_t len = lseek(fd, 0, SEEK_END);
87                 if (len == -1) {
88                         perror("lseek");
89                         exit(1);
90                 }
91                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
92         }
93
94         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
95         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
96                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
97                 exit(1);
98         }
99         if (hdr.version != 0 && hdr.version != 1) {
100                 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
101                 exit(1);
102         }
103         if (hdr.version == 0) {
104                 // These will be junk data.
105                 hdr.zstd_dictionary_offset_bytes = 0;
106                 hdr.zstd_dictionary_length_bytes = 0;
107         }
108         if (hdr.max_version < 2) {
109                 // This too. (We ignore the other max_version 2 fields.)
110                 hdr.check_visibility = true;
111         }
112 }
113
114 Corpus::~Corpus()
115 {
116         close(fd);
117 }
118
119 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
120 {
121         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
122         engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, cb{ move(cb) }](string_view s) {
123                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
124                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
125                         if (trgmptr[i].trgm == trgm) {
126                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
127                                 return;
128                         }
129                 }
130
131                 // Not found.
132                 cb(nullptr, 0);
133         });
134 }
135
136 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
137 {
138         // Read the file offset from this docid and the next one.
139         // This is always allowed, since we have a sentinel block at the end.
140         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
141                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
142                 off_t offset = ptr[0];
143                 size_t len = ptr[1] - ptr[0];
144                 engine->submit_read(fd, len, offset, cb);
145         });
146 }
147
148 size_t Corpus::get_num_filename_blocks() const
149 {
150         return hdr.num_docids;
151 }
152
153 void scan_file_block(const vector<Needle> &needles, string_view compressed,
154                      AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
155                      atomic<uint64_t> *matched)
156 {
157         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
158         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
159                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
160                 exit(1);
161         }
162
163         string block;
164         block.resize(uncompressed_len + 1);
165
166         static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx();  // Reused across calls.
167         size_t err;
168
169         if (ddict != nullptr) {
170                 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
171                                                  compressed.size(), ddict);
172         } else {
173                 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
174                                           compressed.size());
175         }
176         if (ZSTD_isError(err)) {
177                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
178                 exit(1);
179         }
180         block[block.size() - 1] = '\0';
181
182         auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
183                 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
184                         if (ok) {
185                                 ++*matched;
186                                 serializer->print(local_seq, next_seq - local_seq, filename);
187                         } else {
188                                 serializer->print(local_seq, next_seq - local_seq, "");
189                         }
190                         free(filename);
191                 });
192         };
193
194         // We need to know the next sequence number before inserting into Serializer,
195         // so always buffer one candidate.
196         const char *pending_candidate = nullptr;
197
198         uint64_t local_seq = seq << 32;
199         for (const char *filename = block.data();
200              filename != block.data() + block.size();
201              filename += strlen(filename) + 1) {
202                 const char *haystack = filename;
203                 if (match_basename) {
204                         haystack = strrchr(filename, '/');
205                         if (haystack == nullptr) {
206                                 haystack = filename;
207                         } else {
208                                 ++haystack;
209                         }
210                 }
211
212                 bool found = true;
213                 for (const Needle &needle : needles) {
214                         if (!matches(needle, haystack)) {
215                                 found = false;
216                                 break;
217                         }
218                 }
219                 if (found) {
220                         if (pending_candidate != nullptr) {
221                                 test_candidate(pending_candidate, local_seq, local_seq + 1);
222                                 ++local_seq;
223                         }
224                         pending_candidate = filename;
225                 }
226         }
227         if (pending_candidate == nullptr) {
228                 serializer->print(seq << 32, 1ULL << 32, "");
229         } else {
230                 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
231         }
232 }
233
234 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
235 {
236         Serializer docids_in_order;
237         AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
238         atomic<uint64_t> matched{ 0 };
239         for (size_t i = 0; i < docids.size(); ++i) {
240                 uint32_t docid = docids[i];
241                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
242                         scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order, &matched);
243                 });
244         }
245         engine->finish();
246         return matched;
247 }
248
249 struct WorkerThread {
250         thread t;
251
252         // We use a result queue instead of synchronizing Serializer,
253         // since a lock on it becomes a huge choke point if there are
254         // lots of threads.
255         mutex result_mu;
256         struct Result {
257                 uint64_t seq;
258                 uint64_t skip;
259                 string msg;
260         };
261         vector<Result> results;
262 };
263
264 class WorkerThreadReceiver : public ResultReceiver {
265 public:
266         WorkerThreadReceiver(WorkerThread *wt)
267                 : wt(wt) {}
268
269         void print(uint64_t seq, uint64_t skip, const string msg) override
270         {
271                 lock_guard<mutex> lock(wt->result_mu);
272                 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
273                         wt->results.back().skip += skip;
274                 } else {
275                         wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
276                 }
277         }
278
279 private:
280         WorkerThread *wt;
281 };
282
283 void deliver_results(WorkerThread *wt, Serializer *serializer)
284 {
285         vector<WorkerThread::Result> results;
286         {
287                 lock_guard<mutex> lock(wt->result_mu);
288                 results = move(wt->results);
289         }
290         for (const WorkerThread::Result &result : results) {
291                 serializer->print(result.seq, result.skip, move(result.msg));
292         }
293 }
294
295 // We do this sequentially, as it's faster than scattering
296 // a lot of I/O through io_uring and hoping the kernel will
297 // coalesce it plus readahead for us. Since we assume that
298 // we will primarily be CPU-bound, we'll be firing up one
299 // worker thread for each spare core (the last one will
300 // only be doing I/O). access() is still synchronous.
301 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
302 {
303         {
304                 const Header &hdr = corpus.get_hdr();
305                 if (hdr.zstd_dictionary_length_bytes > 0) {
306                         string dictionary;
307                         dictionary.resize(hdr.zstd_dictionary_length_bytes);
308                         complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
309                         ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
310                 }
311         }
312
313         AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
314         Serializer serializer;
315         uint32_t num_blocks = corpus.get_num_filename_blocks();
316         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
317         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
318         atomic<uint64_t> matched{ 0 };
319
320         mutex mu;
321         condition_variable queue_added, queue_removed;
322         deque<tuple<int, int, string>> work_queue;  // Under mu.
323         bool done = false;  // Under mu.
324
325         unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
326         dprintf("Using %u worker threads for linear scan.\n", num_threads);
327         unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
328         for (unsigned i = 0; i < num_threads; ++i) {
329                 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
330                         // regcomp() takes a lock on the regex, so each thread will need its own.
331                         const vector<Needle> *use_needles = &needles;
332                         vector<Needle> recompiled_needles;
333                         if (i != 0 && patterns_are_regex) {
334                                 recompiled_needles = needles;
335                                 for (Needle &needle : recompiled_needles) {
336                                         needle.re = compile_regex(needle.str);
337                                 }
338                                 use_needles = &recompiled_needles;
339                         }
340
341                         WorkerThreadReceiver receiver(&threads[i]);
342                         for (;;) {
343                                 uint32_t io_docid, last_docid;
344                                 string compressed;
345
346                                 {
347                                         unique_lock<mutex> lock(mu);
348                                         queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
349                                         if (done && work_queue.empty()) {
350                                                 return;
351                                         }
352                                         tie(io_docid, last_docid, compressed) = move(work_queue.front());
353                                         work_queue.pop_front();
354                                         queue_removed.notify_all();
355                                 }
356
357                                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
358                                         size_t relative_offset = offsets[docid] - offsets[io_docid];
359                                         size_t len = offsets[docid + 1] - offsets[docid];
360                                         scan_file_block(*use_needles, { &compressed[relative_offset], len }, &access_rx_cache, docid, &receiver, &matched);
361                                 }
362                         }
363                 });
364         }
365
366         string compressed;
367         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
368                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
369                 size_t io_len = offsets[last_docid] - offsets[io_docid];
370                 if (compressed.size() < io_len) {
371                         compressed.resize(io_len);
372                 }
373                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
374
375                 {
376                         unique_lock<mutex> lock(mu);
377                         queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; });  // Allow ~2MB of data queued up.
378                         work_queue.emplace_back(io_docid, last_docid, move(compressed));
379                         queue_added.notify_one();  // Avoid the thundering herd.
380                 }
381
382                 // Pick up some results, so that we are sure that we won't just overload.
383                 // (Seemingly, going through all of these causes slowness with many threads,
384                 // but taking only one is OK.)
385                 unsigned i = io_docid / 32;
386                 deliver_results(&threads[i % num_threads], &serializer);
387         }
388         {
389                 lock_guard<mutex> lock(mu);
390                 done = true;
391                 queue_added.notify_all();
392         }
393         for (unsigned i = 0; i < num_threads; ++i) {
394                 threads[i].t.join();
395                 deliver_results(&threads[i], &serializer);
396         }
397         return matched;
398 }
399
400 // Takes the given posting list, unions it into the parts of the trigram disjunction
401 // already read; if the list is complete, intersects with “cur_candidates”.
402 //
403 // Returns true if the search should be aborted (we are done).
404 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
405 {
406         if (td->docids.empty()) {
407                 td->docids = move(decoded);
408         } else {
409                 tmp->clear();
410                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
411                 swap(*tmp, td->docids);
412         }
413         if (--td->remaining_trigrams_to_read > 0) {
414                 // Need to wait for more.
415                 if (ignore_case) {
416                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
417                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
418                 }
419                 return false;
420         }
421         if (cur_candidates->empty()) {
422                 if (ignore_case) {
423                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
424                                 td->index, td->docids.size());
425                 }
426                 *cur_candidates = move(td->docids);
427         } else {
428                 tmp->clear();
429                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
430                                  td->docids.begin(), td->docids.end(),
431                                  back_inserter(*tmp));
432                 swap(*cur_candidates, *tmp);
433                 if (ignore_case) {
434                         if (cur_candidates->empty()) {
435                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
436                                         td->index, td->docids.size());
437                                 return true;
438                         } else {
439                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
440                                         td->index, td->docids.size(), cur_candidates->size());
441                         }
442                 }
443         }
444         return false;
445 }
446
447 void do_search_file(const vector<Needle> &needles, const char *filename)
448 {
449         int fd = open(filename, O_RDONLY);
450         if (fd == -1) {
451                 perror(filename);
452                 exit(1);
453         }
454
455         // Drop privileges.
456         if (setgid(getgid()) != 0) {
457                 perror("setgid");
458                 exit(EXIT_FAILURE);
459         }
460
461         start = steady_clock::now();
462         if (access("/", R_OK | X_OK)) {
463                 // We can't find anything, no need to bother...
464                 return;
465         }
466
467         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
468         Corpus corpus(fd, &engine);
469         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
470
471         vector<TrigramDisjunction> trigram_groups;
472         if (patterns_are_regex) {
473                 // We could parse the regex to find trigrams that have to be there
474                 // (there are actually known algorithms to deal with disjunctions
475                 // and such, too), but for now, we just go brute force.
476                 // Using locate with regexes is pretty niche.
477         } else {
478                 for (const Needle &needle : needles) {
479                         parse_trigrams(needle.str, ignore_case, &trigram_groups);
480                 }
481         }
482
483         unique_sort(
484                 &trigram_groups,
485                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
486                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
487
488         // Give them names for debugging.
489         unsigned td_index = 0;
490         for (TrigramDisjunction &td : trigram_groups) {
491                 td.index = td_index++;
492         }
493
494         // Collect which trigrams we need to look up in the hash table.
495         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
496         for (TrigramDisjunction &td : trigram_groups) {
497                 for (uint32_t trgm : td.trigram_alternatives) {
498                         trigrams_to_lookup[trgm].push_back(&td);
499                 }
500         }
501         if (trigrams_to_lookup.empty()) {
502                 // Too short for trigram matching. Apply brute force.
503                 // (We could have searched through all trigrams that matched
504                 // the pattern and done a union of them, but that's a lot of
505                 // work for fairly unclear gain.)
506                 uint64_t matched = scan_all_docids(needles, fd, corpus);
507                 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
508                         1e3 * duration<float>(steady_clock::now() - start).count(), matched);
509                 if (only_count) {
510                         printf("%" PRId64 "\n", matched);
511                 }
512                 return;
513         }
514
515         // Sneak in fetching the dictionary, if present. It's not necessarily clear
516         // exactly where it would be cheapest to get it, but it needs to be present
517         // before we can decode any of the posting lists. Most likely, it's
518         // in the same filesystem block as the header anyway, so it should be
519         // present in the cache.
520         {
521                 const Header &hdr = corpus.get_hdr();
522                 if (hdr.zstd_dictionary_length_bytes > 0) {
523                         engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
524                                 ddict = ZSTD_createDDict(s.data(), s.size());
525                                 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
526                         });
527                 }
528         }
529
530         // Look them all up on disk.
531         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
532                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
533                         if (trgmptr == nullptr) {
534                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
535                                 for (TrigramDisjunction *td : *trigram_groups) {
536                                         --td->remaining_trigrams_to_read;
537                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
538                                                 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
539                                                 if (only_count) {
540                                                         printf("0\n");
541                                                 }
542                                                 exit(0);
543                                         }
544                                 }
545                                 return;
546                         }
547                         for (TrigramDisjunction *td : *trigram_groups) {
548                                 --td->remaining_trigrams_to_read;
549                                 td->max_num_docids += trgmptr->num_docids;
550                                 td->read_trigrams.emplace_back(*trgmptr, len);
551                         }
552                 });
553         }
554         engine.finish();
555         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
556
557         for (TrigramDisjunction &td : trigram_groups) {
558                 // Reset for reads.
559                 td.remaining_trigrams_to_read = td.read_trigrams.size();
560
561                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
562                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
563                 }
564         }
565
566         // TODO: For case-insensitive (ie. more than one alternative in each),
567         // prioritize the ones with fewer seeks?
568         sort(trigram_groups.begin(), trigram_groups.end(),
569              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
570                      return a.max_num_docids < b.max_num_docids;
571              });
572
573         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
574         for (TrigramDisjunction &td : trigram_groups) {
575                 for (uint32_t trgm : td.trigram_alternatives) {
576                         uses_trigram[trgm].push_back(&td);
577                 }
578         }
579
580         unordered_set<uint32_t> trigrams_submitted_read;
581         vector<uint32_t> cur_candidates, tmp, decoded;
582         bool done = false;
583         for (TrigramDisjunction &td : trigram_groups) {
584                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
585                         dprintf("%s has up to %u entries, ignoring the rest (will "
586                                 "weed out false positives later)\n",
587                                 print_td(td).c_str(), td.max_num_docids);
588                         break;
589                 }
590
591                 for (auto &[trgmptr, len] : td.read_trigrams) {
592                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
593                                 continue;
594                         }
595                         trigrams_submitted_read.insert(trgmptr.trgm);
596                         // Only stay a certain amount ahead, so that we don't spend I/O
597                         // on reading the latter, large posting lists. We are unlikely
598                         // to need them anyway, even if they should come in first.
599                         if (engine.get_waiting_reads() >= 5) {
600                                 engine.finish();
601                                 if (done)
602                                         break;
603                         }
604                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
605                                 if (done)
606                                         return;
607
608                                 uint32_t trgm = trgmptr.trgm;
609                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
610                                 size_t num = trgmptr.num_docids;
611                                 decoded.resize(num);
612                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
613
614                                 assert(uses_trigram.count(trgm) != 0);
615                                 bool was_empty = cur_candidates.empty();
616                                 if (ignore_case) {
617                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
618                                 }
619
620                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
621                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
622                                         if (done)
623                                                 break;
624                                 }
625                                 if (!ignore_case) {
626                                         if (was_empty) {
627                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
628                                         } else if (cur_candidates.empty()) {
629                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
630                                         } else {
631                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
632                                         }
633                                 }
634                         });
635                 }
636         }
637         engine.finish();
638         if (done) {
639                 return;
640         }
641         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
642                 1e3 * duration<float>(steady_clock::now() - start).count());
643
644         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
645         dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
646                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
647
648         if (only_count) {
649                 printf("%" PRId64 "\n", matched);
650         }
651 }
652
653 void usage()
654 {
655         printf(
656                 "Usage: plocate [OPTION]... PATTERN...\n"
657                 "\n"
658                 "  -b, --basename         search only the file name portion of path names\n"
659                 "  -c, --count            print number of matches instead of the matches\n"
660                 "  -d, --database DBPATH  search for files in DBPATH\n"
661                 "                         (default is " DBFILE ")\n"
662                 "  -i, --ignore-case      search case-insensitively\n"
663                 "  -l, --limit LIMIT      stop after LIMIT matches\n"
664                 "  -0, --null             delimit matches by NUL instead of newline\n"
665                 "  -r, --regexp           interpret patterns as basic regexps (slow)\n"
666                 "      --regex            interpret patterns as extended regexps (slow)\n"
667                 "  -w, --wholename        search the entire path name (default; see -b)\n"
668                 "      --help             print this help\n"
669                 "      --version          print version information\n");
670 }
671
672 void version()
673 {
674         printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
675         printf("Copyright 2020 Steinar H. Gunderson\n");
676         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
677         printf("This is free software: you are free to change and redistribute it.\n");
678         printf("There is NO WARRANTY, to the extent permitted by law.\n");
679         exit(0);
680 }
681
682 int main(int argc, char **argv)
683 {
684         constexpr int EXTENDED_REGEX = 1000;
685         constexpr int FLUSH_CACHE = 1001;
686         static const struct option long_options[] = {
687                 { "help", no_argument, 0, 'h' },
688                 { "count", no_argument, 0, 'c' },
689                 { "basename", no_argument, 0, 'b' },
690                 { "database", required_argument, 0, 'd' },
691                 { "ignore-case", no_argument, 0, 'i' },
692                 { "limit", required_argument, 0, 'l' },
693                 { "null", no_argument, 0, '0' },
694                 { "version", no_argument, 0, 'V' },
695                 { "regexp", no_argument, 0, 'r' },
696                 { "regex", no_argument, 0, EXTENDED_REGEX },
697                 { "wholename", no_argument, 0, 'w' },
698                 { "debug", no_argument, 0, 'D' },  // Not documented.
699                 // Enable to test cold-cache behavior (except for access()). Not documented.
700                 { "flush-cache", no_argument, 0, FLUSH_CACHE },
701                 { 0, 0, 0, 0 }
702         };
703
704         setlocale(LC_ALL, "");
705         for (;;) {
706                 int option_index = 0;
707                 int c = getopt_long(argc, argv, "bcd:hil:n:0rwVD", long_options, &option_index);
708                 if (c == -1) {
709                         break;
710                 }
711                 switch (c) {
712                 case 'b':
713                         match_basename = true;
714                         break;
715                 case 'c':
716                         only_count = true;
717                         break;
718                 case 'd':
719                         dbpath = strdup(optarg);
720                         break;
721                 case 'h':
722                         usage();
723                         exit(0);
724                 case 'i':
725                         ignore_case = true;
726                         break;
727                 case 'l':
728                 case 'n':
729                         limit_matches = limit_left = atoll(optarg);
730                         if (limit_matches <= 0) {
731                                 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
732                                 exit(1);
733                         }
734                         break;
735                 case '0':
736                         print_nul = true;
737                         break;
738                 case 'r':
739                         patterns_are_regex = true;
740                         break;
741                 case EXTENDED_REGEX:
742                         patterns_are_regex = true;
743                         use_extended_regex = true;
744                         break;
745                 case 'w':
746                         match_basename = false;  // No-op unless -b is given first.
747                         break;
748                 case 'D':
749                         use_debug = true;
750                         break;
751                 case FLUSH_CACHE:
752                         flush_cache = true;
753                         break;
754                 case 'V':
755                         version();
756                         break;
757                 default:
758                         exit(1);
759                 }
760         }
761
762         if (use_debug || flush_cache) {
763                 // Debug information would leak information about which files exist,
764                 // so drop setgid before we open the file; one would either need to run
765                 // as root, or use a locally-built file. Doing the same thing for
766                 // flush_cache is mostly paranoia, in an attempt to prevent random users
767                 // from making plocate slow for everyone else.
768                 if (setgid(getgid()) != 0) {
769                         perror("setgid");
770                         exit(EXIT_FAILURE);
771                 }
772         }
773
774         if (!print_nul) {
775                 stdout_is_tty = isatty(1);
776         }
777
778         vector<Needle> needles;
779         for (int i = optind; i < argc; ++i) {
780                 Needle needle;
781                 needle.str = argv[i];
782
783                 // See if there are any wildcard characters, which indicates we should treat it
784                 // as an (anchored) glob.
785                 bool any_wildcard = false;
786                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
787                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
788                                 any_wildcard = true;
789                                 break;
790                         }
791                 }
792
793                 if (patterns_are_regex) {
794                         needle.type = Needle::REGEX;
795                         needle.re = compile_regex(needle.str);
796                 } else if (any_wildcard) {
797                         needle.type = Needle::GLOB;
798                 } else if (ignore_case) {
799                         // strcasestr() doesn't handle locales correctly (even though LSB
800                         // claims it should), but somehow, fnmatch() does, and it's about
801                         // the same speed as using a regex.
802                         needle.type = Needle::GLOB;
803                         needle.str = "*" + needle.str + "*";
804                 } else {
805                         needle.type = Needle::STRSTR;
806                         needle.str = unescape_glob_to_plain_string(needle.str);
807                 }
808                 needles.push_back(move(needle));
809         }
810         if (needles.empty()) {
811                 fprintf(stderr, "plocate: no pattern to search for specified\n");
812                 exit(0);
813         }
814         do_search_file(needles, dbpath);
815 }