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