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