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