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