2 #include "io_uring_engine.h"
3 #include "parse_trigrams.h"
4 #include "unique_sort.h"
24 #include <string_view>
26 #include <unordered_map>
27 #include <unordered_set>
33 using namespace std::chrono;
35 #define dprintf(...) \
38 fprintf(stderr, __VA_ARGS__); \
42 #include "turbopfor.h"
44 const char *dbpath = "/var/lib/mlocate/plocate.db";
45 bool ignore_case = false;
46 bool only_count = false;
47 bool print_nul = false;
48 bool use_debug = false;
49 int64_t limit_matches = numeric_limits<int64_t>::max();
53 bool ready_to_print(int seq) { return next_seq == seq; }
54 void print_delayed(int seq, const vector<string> msg);
55 void release_current();
63 bool operator<(const Element &other) const
65 return seq > other.seq;
68 priority_queue<Element> pending;
71 void Serializer::print_delayed(int seq, const vector<string> msg)
73 pending.push(Element{ seq, move(msg) });
76 void Serializer::release_current()
80 // See if any delayed prints can now be dealt with.
81 while (!pending.empty() && pending.top().seq == next_seq) {
82 if (limit_matches-- <= 0)
84 for (const string &msg : pending.top().msg) {
86 printf("%s%c", msg.c_str(), 0);
88 printf("%s\n", msg.c_str());
98 REGEX, // Not currently used.
100 string str; // Filled in no matter what.
101 regex_t re; // For REGEX.
104 bool matches(const Needle &needle, const char *haystack)
106 if (needle.type == Needle::STRSTR) {
107 return strstr(haystack, needle.str.c_str()) != nullptr;
108 } else if (needle.type == Needle::GLOB) {
109 int flags = ignore_case ? FNM_CASEFOLD : 0;
110 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
112 assert(needle.type == Needle::REGEX);
113 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
117 bool has_access(const char *filename,
118 unordered_map<string, bool> *access_rx_cache)
120 const char *end = strchr(filename + 1, '/');
121 while (end != nullptr) {
122 string parent_path(filename, end);
123 auto it = access_rx_cache->find(parent_path);
125 if (it == access_rx_cache->end()) {
126 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
127 access_rx_cache->emplace(move(parent_path), ok);
134 end = strchr(end + 1, '/');
142 Corpus(int fd, IOUringEngine *engine);
144 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
145 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
146 size_t get_num_filename_blocks() const;
147 off_t offset_for_block(uint32_t docid) const
149 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
154 IOUringEngine *const engine;
159 Corpus::Corpus(int fd, IOUringEngine *engine)
160 : fd(fd), engine(engine)
162 // Enable to test cold-cache behavior (except for access()).
164 off_t len = lseek(fd, 0, SEEK_END);
169 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
172 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
173 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
174 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
177 if (hdr.version != 0) {
178 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
188 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
190 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
191 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) {
192 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
193 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
194 if (trgmptr[i].trgm == trgm) {
195 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
205 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
207 // Read the file offset from this docid and the next one.
208 // This is always allowed, since we have a sentinel block at the end.
209 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
210 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
211 off_t offset = ptr[0];
212 size_t len = ptr[1] - ptr[0];
213 engine->submit_read(fd, len, offset, cb);
217 size_t Corpus::get_num_filename_blocks() const
219 return hdr.num_docids;
222 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
223 unordered_map<string, bool> *access_rx_cache, int seq,
224 Serializer *serializer)
226 uint64_t matched = 0;
228 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
229 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
230 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
235 block.resize(uncompressed_len + 1);
237 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
239 if (ZSTD_isError(err)) {
240 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
243 block[block.size() - 1] = '\0';
245 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
246 vector<string> delayed;
248 for (const char *filename = block.data();
249 filename != block.data() + block.size();
250 filename += strlen(filename) + 1) {
252 for (const Needle &needle : needles) {
253 if (!matches(needle, filename)) {
258 if (found && has_access(filename, access_rx_cache)) {
259 if (limit_matches-- <= 0)
264 if (immediate_print) {
266 printf("%s%c", filename, 0);
268 printf("%s\n", filename);
271 delayed.push_back(filename);
275 if (serializer != nullptr && !only_count) {
276 if (immediate_print) {
277 serializer->release_current();
279 serializer->print_delayed(seq, move(delayed));
285 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
287 Serializer docids_in_order;
288 unordered_map<string, bool> access_rx_cache;
289 uint64_t matched = 0;
290 for (size_t i = 0; i < docids.size(); ++i) {
291 uint32_t docid = docids[i];
292 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
293 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
300 // We do this sequentially, as it's faster than scattering
301 // a lot of I/O through io_uring and hoping the kernel will
302 // coalesce it plus readahead for us.
303 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
305 unordered_map<string, bool> access_rx_cache;
306 uint32_t num_blocks = corpus.get_num_filename_blocks();
307 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
308 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
310 uint64_t matched = 0;
311 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
312 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
313 size_t io_len = offsets[last_docid] - offsets[io_docid];
314 if (compressed.size() < io_len) {
315 compressed.resize(io_len);
317 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
319 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
320 size_t relative_offset = offsets[docid] - offsets[io_docid];
321 size_t len = offsets[docid + 1] - offsets[docid];
322 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
323 if (limit_matches <= 0)
330 // Takes the given posting list, unions it into the parts of the trigram disjunction
331 // already read; if the list is complete, intersects with “cur_candidates”.
333 // Returns true if the search should be aborted (we are done).
334 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
336 if (td->docids.empty()) {
337 td->docids = move(decoded);
340 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
341 swap(*tmp, td->docids);
343 if (--td->remaining_trigrams_to_read > 0) {
344 // Need to wait for more.
346 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
347 td->remaining_trigrams_to_read, td->index, td->docids.size());
351 if (cur_candidates->empty()) {
353 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
354 td->index, td->docids.size());
356 *cur_candidates = move(td->docids);
359 set_intersection(cur_candidates->begin(), cur_candidates->end(),
360 td->docids.begin(), td->docids.end(),
361 back_inserter(*tmp));
362 swap(*cur_candidates, *tmp);
364 if (cur_candidates->empty()) {
365 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
366 td->index, td->docids.size());
369 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
370 td->index, td->docids.size(), cur_candidates->size());
377 void do_search_file(const vector<Needle> &needles, const char *filename)
379 int fd = open(filename, O_RDONLY);
386 if (setgid(getgid()) != 0) {
391 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
392 if (access("/", R_OK | X_OK)) {
393 // We can't find anything, no need to bother...
397 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
398 Corpus corpus(fd, &engine);
399 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
401 vector<TrigramDisjunction> trigram_groups;
402 for (const Needle &needle : needles) {
403 if (needle.str.size() < 3)
405 parse_trigrams(needle.str, ignore_case, &trigram_groups);
409 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
410 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
412 // Give them names for debugging.
413 unsigned td_index = 0;
414 for (TrigramDisjunction &td : trigram_groups) {
415 td.index = td_index++;
418 // Collect which trigrams we need to look up in the hash table.
419 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
420 for (TrigramDisjunction &td : trigram_groups) {
421 for (uint32_t trgm : td.trigram_alternatives) {
422 trigrams_to_lookup[trgm].push_back(&td);
425 if (trigrams_to_lookup.empty()) {
426 // Too short for trigram matching. Apply brute force.
427 // (We could have searched through all trigrams that matched
428 // the pattern and done a union of them, but that's a lot of
429 // work for fairly unclear gain.)
430 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
432 printf("%zu\n", matched);
437 // Look them all up on disk.
438 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
439 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
440 if (trgmptr == nullptr) {
441 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
442 for (TrigramDisjunction *td : *trigram_groups) {
443 --td->remaining_trigrams_to_read;
444 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
445 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
454 for (TrigramDisjunction *td : *trigram_groups) {
455 --td->remaining_trigrams_to_read;
456 td->max_num_docids += trgmptr->num_docids;
457 td->read_trigrams.emplace_back(*trgmptr, len);
462 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
464 for (TrigramDisjunction &td : trigram_groups) {
466 td.remaining_trigrams_to_read = td.read_trigrams.size();
468 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
469 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
473 // TODO: For case-insensitive (ie. more than one alternative in each),
474 // prioritize the ones with fewer seeks?
475 sort(trigram_groups.begin(), trigram_groups.end(),
476 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
477 return a.max_num_docids < b.max_num_docids;
480 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
481 for (TrigramDisjunction &td : trigram_groups) {
482 for (uint32_t trgm : td.trigram_alternatives) {
483 uses_trigram[trgm].push_back(&td);
487 unordered_set<uint32_t> trigrams_submitted_read;
488 vector<uint32_t> cur_candidates, tmp, decoded;
490 for (TrigramDisjunction &td : trigram_groups) {
491 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
492 dprintf("%s has up to %u entries, ignoring the rest (will "
493 "weed out false positives later)\n",
494 print_td(td).c_str(), td.max_num_docids);
498 for (auto &[trgmptr, len] : td.read_trigrams) {
499 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
502 trigrams_submitted_read.insert(trgmptr.trgm);
503 // Only stay a certain amount ahead, so that we don't spend I/O
504 // on reading the latter, large posting lists. We are unlikely
505 // to need them anyway, even if they should come in first.
506 if (engine.get_waiting_reads() >= 5) {
511 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
515 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
516 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
517 size_t num = trgmptr.num_docids;
519 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
521 assert(uses_trigram.count(trgm) != 0);
522 bool was_empty = cur_candidates.empty();
524 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
527 for (TrigramDisjunction *td : uses_trigram[trgm]) {
528 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
534 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
535 } else if (cur_candidates.empty()) {
536 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
538 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
548 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
549 1e3 * duration<float>(steady_clock::now() - start).count());
551 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
552 dprintf("Done in %.1f ms, found %zu matches.\n",
553 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
556 printf("%zu\n", matched);
560 string unescape_glob_to_plain_string(const string &needle)
563 for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
564 uint32_t ch = read_unigram(needle, i).first;
565 assert(ch != WILDCARD_UNIGRAM);
566 if (ch == PREMATURE_END_UNIGRAM) {
567 fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
570 unescaped.push_back(ch);
577 // The help text comes from mlocate.
578 printf("Usage: plocate [OPTION]... PATTERN...\n");
580 printf(" -c, --count only print number of found entries\n");
581 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
582 printf(" %s)\n", dbpath);
583 printf(" -h, --help print this help\n");
584 printf(" -i, --ignore-case ignore case distinctions when matching patterns\n");
585 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
586 printf(" -0, --null separate entries with NUL on output\n");
587 printf(" -V, --version print version information\n");
592 printf("plocate %s\n", PLOCATE_VERSION);
593 printf("Copyright 2020 Steinar H. Gunderson\n");
594 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
595 printf("This is free software: you are free to change and redistribute it.\n");
596 printf("There is NO WARRANTY, to the extent permitted by law.\n");
600 int main(int argc, char **argv)
602 static const struct option long_options[] = {
603 { "help", no_argument, 0, 'h' },
604 { "count", no_argument, 0, 'c' },
605 { "database", required_argument, 0, 'd' },
606 { "ignore-case", no_argument, 0, 'i' },
607 { "limit", required_argument, 0, 'l' },
608 { "null", no_argument, 0, '0' },
609 { "version", no_argument, 0, 'V' },
610 { "debug", no_argument, 0, 'D' }, // Not documented.
614 setlocale(LC_ALL, "");
616 int option_index = 0;
617 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
626 dbpath = strdup(optarg);
636 limit_matches = atoll(optarg);
653 // Debug information would leak information about which files exist,
654 // so drop setgid before we open the file; one would either need to run
655 // as root, or use a locally-built file.
656 if (setgid(getgid()) != 0) {
662 vector<Needle> needles;
663 for (int i = optind; i < argc; ++i) {
665 needle.str = argv[i];
667 // See if there are any wildcard characters, which indicates we should treat it
668 // as an (anchored) glob.
669 bool any_wildcard = false;
670 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
671 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
678 needle.type = Needle::GLOB;
679 } else if (ignore_case) {
680 // strcasestr() doesn't handle locales correctly (even though LSB
681 // claims it should), but somehow, fnmatch() does, and it's about
682 // the same speed as using a regex.
683 needle.type = Needle::GLOB;
684 needle.str = "*" + needle.str + "*";
686 needle.type = Needle::STRSTR;
687 needle.str = unescape_glob_to_plain_string(needle.str);
689 needles.push_back(move(needle));
691 if (needles.empty()) {
692 fprintf(stderr, "plocate: no pattern to search for specified\n");
695 do_search_file(needles, dbpath);