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