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