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