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