]> git.sesse.net Git - plocate/blob - plocate.cpp
Multithread linear scans.
[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         vector<tuple<uint64_t, uint64_t, string>> results;
421 };
422
423 class WorkerThreadReceiver : public ResultReceiver {
424 public:
425         WorkerThreadReceiver(WorkerThread *wt) : wt(wt) {}
426
427         void print(uint64_t seq, uint64_t skip, const string msg) override
428         {
429                 lock_guard<mutex> lock(wt->result_mu);
430                 wt->results.emplace_back(seq, skip, move(msg));
431         }
432
433 private:
434         WorkerThread *wt;
435 };
436
437 void deliver_results(WorkerThread *wt, Serializer *serializer)
438 {
439         vector<tuple<uint64_t, uint64_t, string>> results;
440         {
441                 lock_guard<mutex> lock(wt->result_mu);
442                 results = move(wt->results);
443         }
444         for (const auto &result : results) {
445                 serializer->print(get<0>(result), get<1>(result), move(get<2>(result)));
446         }
447 }
448
449 // We do this sequentially, as it's faster than scattering
450 // a lot of I/O through io_uring and hoping the kernel will
451 // coalesce it plus readahead for us. Since we assume that
452 // we will primarily be CPU-bound, we'll be firing up one
453 // worker thread for each spare core (the last one will
454 // only be doing I/O). access() is still synchronous.
455 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
456 {
457         {
458                 const Header &hdr = corpus.get_hdr();
459                 if (hdr.zstd_dictionary_length_bytes > 0) {
460                         string dictionary;
461                         dictionary.resize(hdr.zstd_dictionary_length_bytes);
462                         complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
463                         ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
464                 }
465         }
466
467         AccessRXCache access_rx_cache(nullptr);
468         Serializer serializer;
469         uint32_t num_blocks = corpus.get_num_filename_blocks();
470         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
471         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
472         atomic<uint64_t> matched{0};
473
474         mutex mu;
475         condition_variable queue_added, queue_removed;
476         deque<tuple<int, int, string>> work_queue;  // Under mu.
477         bool done = false;  // Under mu.
478
479         unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
480         dprintf("Using %u worker threads for linear scan.\n", num_threads);
481         unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
482         for (unsigned i = 0; i < num_threads; ++i) {
483                 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
484                         // regcomp() takes a lock on the regex, so each thread will need its own.
485                         const vector<Needle> *use_needles = &needles;
486                         vector<Needle> recompiled_needles;
487                         if (i != 0 && patterns_are_regex) {
488                                 recompiled_needles = needles;
489                                 for (Needle &needle : recompiled_needles) {
490                                         needle.re = compile_regex(needle.str);
491                                 }
492                                 use_needles = &recompiled_needles;
493                         }
494
495                         WorkerThreadReceiver receiver(&threads[i]);
496                         for (;;) {
497                                 uint32_t io_docid, last_docid;
498                                 string compressed;
499
500                                 {
501                                         unique_lock<mutex> lock(mu);
502                                         queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
503                                         if (done && work_queue.empty()) {
504                                                 return;
505                                         }
506                                         tie(io_docid, last_docid, compressed) = move(work_queue.front());
507                                         work_queue.pop_front();
508                                         queue_removed.notify_all();
509                                 }
510
511                                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
512                                         size_t relative_offset = offsets[docid] - offsets[io_docid];
513                                         size_t len = offsets[docid + 1] - offsets[docid];
514                                         scan_file_block(*use_needles, { &compressed[relative_offset], len }, &access_rx_cache, docid, &receiver, &matched);
515                                 }
516                         }
517                 });
518         }
519
520         string compressed;
521         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
522                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
523                 size_t io_len = offsets[last_docid] - offsets[io_docid];
524                 if (compressed.size() < io_len) {
525                         compressed.resize(io_len);
526                 }
527                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
528
529                 {
530                         unique_lock<mutex> lock(mu);
531                         queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; });  // Allow ~2MB of data queued up.
532                         work_queue.emplace_back(io_docid, last_docid, move(compressed));
533                         queue_added.notify_one();  // Avoid the thundering herd.
534                 }
535
536                 // Pick up some results, so that we are sure that we won't just overload.
537                 // (Seemingly, going through all of these causes slowness with many threads,
538                 // but taking only one is OK.)
539                 unsigned i = io_docid / 32;
540                 deliver_results(&threads[i % num_threads], &serializer);
541         }
542         {
543                 lock_guard<mutex> lock(mu);
544                 done = true;
545                 queue_added.notify_all();
546         }
547         for (unsigned i = 0; i < num_threads; ++i) {
548                 threads[i].t.join();
549                 deliver_results(&threads[i], &serializer);
550         }
551         return matched;
552 }
553
554 // Takes the given posting list, unions it into the parts of the trigram disjunction
555 // already read; if the list is complete, intersects with “cur_candidates”.
556 //
557 // Returns true if the search should be aborted (we are done).
558 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
559 {
560         if (td->docids.empty()) {
561                 td->docids = move(decoded);
562         } else {
563                 tmp->clear();
564                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
565                 swap(*tmp, td->docids);
566         }
567         if (--td->remaining_trigrams_to_read > 0) {
568                 // Need to wait for more.
569                 if (ignore_case) {
570                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
571                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
572                 }
573                 return false;
574         }
575         if (cur_candidates->empty()) {
576                 if (ignore_case) {
577                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
578                                 td->index, td->docids.size());
579                 }
580                 *cur_candidates = move(td->docids);
581         } else {
582                 tmp->clear();
583                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
584                                  td->docids.begin(), td->docids.end(),
585                                  back_inserter(*tmp));
586                 swap(*cur_candidates, *tmp);
587                 if (ignore_case) {
588                         if (cur_candidates->empty()) {
589                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
590                                         td->index, td->docids.size());
591                                 return true;
592                         } else {
593                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
594                                         td->index, td->docids.size(), cur_candidates->size());
595                         }
596                 }
597         }
598         return false;
599 }
600
601 void do_search_file(const vector<Needle> &needles, const char *filename)
602 {
603         int fd = open(filename, O_RDONLY);
604         if (fd == -1) {
605                 perror(filename);
606                 exit(1);
607         }
608
609         // Drop privileges.
610         if (setgid(getgid()) != 0) {
611                 perror("setgid");
612                 exit(EXIT_FAILURE);
613         }
614
615         start = steady_clock::now();
616         if (access("/", R_OK | X_OK)) {
617                 // We can't find anything, no need to bother...
618                 return;
619         }
620
621         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
622         Corpus corpus(fd, &engine);
623         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
624
625         vector<TrigramDisjunction> trigram_groups;
626         if (patterns_are_regex) {
627                 // We could parse the regex to find trigrams that have to be there
628                 // (there are actually known algorithms to deal with disjunctions
629                 // and such, too), but for now, we just go brute force.
630                 // Using locate with regexes is pretty niche.
631         } else {
632                 for (const Needle &needle : needles) {
633                         parse_trigrams(needle.str, ignore_case, &trigram_groups);
634                 }
635         }
636
637         unique_sort(
638                 &trigram_groups,
639                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
640                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
641
642         // Give them names for debugging.
643         unsigned td_index = 0;
644         for (TrigramDisjunction &td : trigram_groups) {
645                 td.index = td_index++;
646         }
647
648         // Collect which trigrams we need to look up in the hash table.
649         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
650         for (TrigramDisjunction &td : trigram_groups) {
651                 for (uint32_t trgm : td.trigram_alternatives) {
652                         trigrams_to_lookup[trgm].push_back(&td);
653                 }
654         }
655         if (trigrams_to_lookup.empty()) {
656                 // Too short for trigram matching. Apply brute force.
657                 // (We could have searched through all trigrams that matched
658                 // the pattern and done a union of them, but that's a lot of
659                 // work for fairly unclear gain.)
660                 uint64_t matched = scan_all_docids(needles, fd, corpus);
661                 if (only_count) {
662                         printf("%" PRId64 "\n", matched);
663                 }
664                 return;
665         }
666
667         // Sneak in fetching the dictionary, if present. It's not necessarily clear
668         // exactly where it would be cheapest to get it, but it needs to be present
669         // before we can decode any of the posting lists. Most likely, it's
670         // in the same filesystem block as the header anyway, so it should be
671         // present in the cache.
672         {
673                 const Header &hdr = corpus.get_hdr();
674                 if (hdr.zstd_dictionary_length_bytes > 0) {
675                         engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
676                                 ddict = ZSTD_createDDict(s.data(), s.size());
677                                 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
678                         });
679                 }
680         }
681
682         // Look them all up on disk.
683         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
684                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
685                         if (trgmptr == nullptr) {
686                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
687                                 for (TrigramDisjunction *td : *trigram_groups) {
688                                         --td->remaining_trigrams_to_read;
689                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
690                                                 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
691                                                 if (only_count) {
692                                                         printf("0\n");
693                                                 }
694                                                 exit(0);
695                                         }
696                                 }
697                                 return;
698                         }
699                         for (TrigramDisjunction *td : *trigram_groups) {
700                                 --td->remaining_trigrams_to_read;
701                                 td->max_num_docids += trgmptr->num_docids;
702                                 td->read_trigrams.emplace_back(*trgmptr, len);
703                         }
704                 });
705         }
706         engine.finish();
707         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
708
709         for (TrigramDisjunction &td : trigram_groups) {
710                 // Reset for reads.
711                 td.remaining_trigrams_to_read = td.read_trigrams.size();
712
713                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
714                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
715                 }
716         }
717
718         // TODO: For case-insensitive (ie. more than one alternative in each),
719         // prioritize the ones with fewer seeks?
720         sort(trigram_groups.begin(), trigram_groups.end(),
721              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
722                      return a.max_num_docids < b.max_num_docids;
723              });
724
725         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
726         for (TrigramDisjunction &td : trigram_groups) {
727                 for (uint32_t trgm : td.trigram_alternatives) {
728                         uses_trigram[trgm].push_back(&td);
729                 }
730         }
731
732         unordered_set<uint32_t> trigrams_submitted_read;
733         vector<uint32_t> cur_candidates, tmp, decoded;
734         bool done = false;
735         for (TrigramDisjunction &td : trigram_groups) {
736                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
737                         dprintf("%s has up to %u entries, ignoring the rest (will "
738                                 "weed out false positives later)\n",
739                                 print_td(td).c_str(), td.max_num_docids);
740                         break;
741                 }
742
743                 for (auto &[trgmptr, len] : td.read_trigrams) {
744                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
745                                 continue;
746                         }
747                         trigrams_submitted_read.insert(trgmptr.trgm);
748                         // Only stay a certain amount ahead, so that we don't spend I/O
749                         // on reading the latter, large posting lists. We are unlikely
750                         // to need them anyway, even if they should come in first.
751                         if (engine.get_waiting_reads() >= 5) {
752                                 engine.finish();
753                                 if (done)
754                                         break;
755                         }
756                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
757                                 if (done)
758                                         return;
759
760                                 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
761                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
762                                 size_t num = trgmptr.num_docids;
763                                 decoded.resize(num);
764                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
765
766                                 assert(uses_trigram.count(trgm) != 0);
767                                 bool was_empty = cur_candidates.empty();
768                                 if (ignore_case) {
769                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
770                                 }
771
772                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
773                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
774                                         if (done)
775                                                 break;
776                                 }
777                                 if (!ignore_case) {
778                                         if (was_empty) {
779                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
780                                         } else if (cur_candidates.empty()) {
781                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
782                                         } else {
783                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
784                                         }
785                                 }
786                         });
787                 }
788         }
789         engine.finish();
790         if (done) {
791                 return;
792         }
793         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
794                 1e3 * duration<float>(steady_clock::now() - start).count());
795
796         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
797         dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
798                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
799
800         if (only_count) {
801                 printf("%" PRId64 "\n", matched);
802         }
803 }
804
805 string unescape_glob_to_plain_string(const string &needle)
806 {
807         string unescaped;
808         for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
809                 uint32_t ch = read_unigram(needle, i).first;
810                 assert(ch != WILDCARD_UNIGRAM);
811                 if (ch == PREMATURE_END_UNIGRAM) {
812                         fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
813                         exit(1);
814                 }
815                 unescaped.push_back(ch);
816         }
817         return unescaped;
818 }
819
820 regex_t compile_regex(const string &needle)
821 {
822         regex_t re;
823         int flags = REG_NOSUB;
824         if (ignore_case) {
825                 flags |= REG_ICASE;
826         }
827         if (use_extended_regex) {
828                 flags |= REG_EXTENDED;
829         }
830         int err = regcomp(&re, needle.c_str(), flags);
831         if (err != 0) {
832                 char errbuf[256];
833                 regerror(err, &re, errbuf, sizeof(errbuf));
834                 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
835                 exit(1);
836         }
837         return re;
838 }
839
840 void usage()
841 {
842         printf(
843                 "Usage: plocate [OPTION]... PATTERN...\n"
844                 "\n"
845                 "  -c, --count            print number of matches instead of the matches\n"
846                 "  -d, --database DBPATH  search for files in DBPATH\n"
847                 "                         (default is " DEFAULT_DBPATH ")\n"
848                 "  -i, --ignore-case      search case-insensitively\n"
849                 "  -l, --limit LIMIT      stop after LIMIT matches\n"
850                 "  -0, --null             delimit matches by NUL instead of newline\n"
851                 "  -r, --regexp           interpret patterns as basic regexps (slow)\n"
852                 "      --regex            interpret patterns as extended regexps (slow)\n"
853                 "      --help             print this help\n"
854                 "      --version          print version information\n");
855 }
856
857 void version()
858 {
859         printf("plocate %s\n", PLOCATE_VERSION);
860         printf("Copyright 2020 Steinar H. Gunderson\n");
861         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
862         printf("This is free software: you are free to change and redistribute it.\n");
863         printf("There is NO WARRANTY, to the extent permitted by law.\n");
864         exit(0);
865 }
866
867 int main(int argc, char **argv)
868 {
869         constexpr int EXTENDED_REGEX = 1000;
870         static const struct option long_options[] = {
871                 { "help", no_argument, 0, 'h' },
872                 { "count", no_argument, 0, 'c' },
873                 { "database", required_argument, 0, 'd' },
874                 { "ignore-case", no_argument, 0, 'i' },
875                 { "limit", required_argument, 0, 'l' },
876                 { "null", no_argument, 0, '0' },
877                 { "version", no_argument, 0, 'V' },
878                 { "regexp", no_argument, 0, 'r' },
879                 { "regex", no_argument, 0, EXTENDED_REGEX },
880                 { "debug", no_argument, 0, 'D' },  // Not documented.
881                 { 0, 0, 0, 0 }
882         };
883
884         setlocale(LC_ALL, "");
885         for (;;) {
886                 int option_index = 0;
887                 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
888                 if (c == -1) {
889                         break;
890                 }
891                 switch (c) {
892                 case 'c':
893                         only_count = true;
894                         break;
895                 case 'd':
896                         dbpath = strdup(optarg);
897                         break;
898                 case 'h':
899                         usage();
900                         exit(0);
901                 case 'i':
902                         ignore_case = true;
903                         break;
904                 case 'l':
905                 case 'n':
906                         limit_matches = limit_left = atoll(optarg);
907                         if (limit_matches <= 0) {
908                                 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
909                                 exit(1);
910                         }
911                         break;
912                 case '0':
913                         print_nul = true;
914                         break;
915                 case 'r':
916                         patterns_are_regex = true;
917                         break;
918                 case EXTENDED_REGEX:
919                         patterns_are_regex = true;
920                         use_extended_regex = true;
921                         break;
922                 case 'D':
923                         use_debug = true;
924                         break;
925                 case 'V':
926                         version();
927                         break;
928                 default:
929                         exit(1);
930                 }
931         }
932
933         if (use_debug) {
934                 // Debug information would leak information about which files exist,
935                 // so drop setgid before we open the file; one would either need to run
936                 // as root, or use a locally-built file.
937                 if (setgid(getgid()) != 0) {
938                         perror("setgid");
939                         exit(EXIT_FAILURE);
940                 }
941         }
942
943         vector<Needle> needles;
944         for (int i = optind; i < argc; ++i) {
945                 Needle needle;
946                 needle.str = argv[i];
947
948                 // See if there are any wildcard characters, which indicates we should treat it
949                 // as an (anchored) glob.
950                 bool any_wildcard = false;
951                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
952                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
953                                 any_wildcard = true;
954                                 break;
955                         }
956                 }
957
958                 if (patterns_are_regex) {
959                         needle.type = Needle::REGEX;
960                         needle.re = compile_regex(needle.str);
961                 } else if (any_wildcard) {
962                         needle.type = Needle::GLOB;
963                 } else if (ignore_case) {
964                         // strcasestr() doesn't handle locales correctly (even though LSB
965                         // claims it should), but somehow, fnmatch() does, and it's about
966                         // the same speed as using a regex.
967                         needle.type = Needle::GLOB;
968                         needle.str = "*" + needle.str + "*";
969                 } else {
970                         needle.type = Needle::STRSTR;
971                         needle.str = unescape_glob_to_plain_string(needle.str);
972                 }
973                 needles.push_back(move(needle));
974         }
975         if (needles.empty()) {
976                 fprintf(stderr, "plocate: no pattern to search for specified\n");
977                 exit(0);
978         }
979         do_search_file(needles, dbpath);
980 }