3 #include "io_uring_engine.h"
4 #include "parse_trigrams.h"
6 #include "unique_sort.h"
28 #include <string_view>
30 #include <unordered_map>
31 #include <unordered_set>
37 using namespace std::chrono;
39 #define DEFAULT_DBPATH "/var/lib/mlocate/plocate.db"
41 const char *dbpath = DEFAULT_DBPATH;
42 bool ignore_case = false;
43 bool only_count = false;
44 bool print_nul = false;
45 bool use_debug = false;
46 bool patterns_are_regex = false;
47 bool use_extended_regex = false;
48 int64_t limit_matches = numeric_limits<int64_t>::max();
49 int64_t limit_left = numeric_limits<int64_t>::max();
51 steady_clock::time_point start;
55 if (--limit_left > 0) {
58 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
59 1e3 * duration<float>(steady_clock::now() - start).count(), limit_matches);
61 printf("%ld\n", limit_matches);
68 ~Serializer() { assert(limit_left <= 0 || pending.empty()); }
69 void print(uint64_t seq, uint64_t skip, const string msg);
72 uint64_t next_seq = 0;
77 bool operator<(const Element &other) const
79 return seq > other.seq;
82 priority_queue<Element> pending;
85 void Serializer::print(uint64_t seq, uint64_t skip, const string msg)
94 if (next_seq != seq) {
95 pending.push(Element{ seq, skip, move(msg) });
101 printf("%s%c", msg.c_str(), 0);
103 printf("%s\n", msg.c_str());
109 // See if any delayed prints can now be dealt with.
110 while (!pending.empty() && pending.top().seq == next_seq) {
111 if (!pending.top().msg.empty()) {
113 printf("%s%c", pending.top().msg.c_str(), 0);
115 printf("%s\n", pending.top().msg.c_str());
119 next_seq += pending.top().skip;
128 string str; // Filled in no matter what.
129 regex_t re; // For REGEX.
132 bool matches(const Needle &needle, const char *haystack)
134 if (needle.type == Needle::STRSTR) {
135 return strstr(haystack, needle.str.c_str()) != nullptr;
136 } else if (needle.type == Needle::GLOB) {
137 int flags = ignore_case ? FNM_CASEFOLD : 0;
138 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
140 assert(needle.type == Needle::REGEX);
141 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
145 class AccessRXCache {
147 AccessRXCache(IOUringEngine *engine)
149 void check_access(const char *filename, bool allow_async, function<void(bool)> cb);
152 unordered_map<string, bool> cache;
155 function<void(bool)> cb;
157 map<string, vector<PendingStat>> pending_stats;
158 IOUringEngine *engine;
161 void AccessRXCache::check_access(const char *filename, bool allow_async, function<void(bool)> cb)
163 if (!engine->get_supports_stat()) {
167 for (const char *end = strchr(filename + 1, '/'); end != nullptr; end = strchr(end + 1, '/')) {
168 string parent_path(filename, end - filename); // string_view from C++20.
169 auto cache_it = cache.find(parent_path);
170 if (cache_it != cache.end()) {
171 // Found in the cache.
172 if (!cache_it->second) {
180 bool ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
181 cache.emplace(parent_path, ok);
189 // We want to call access(), but it could block on I/O. io_uring doesn't support
190 // access(), but we can do a dummy asynchonous statx() to populate the kernel's cache,
191 // which nearly always makes the next access() instantaneous.
193 // See if there's already a pending stat that matches this,
194 // or is a subdirectory.
195 auto it = pending_stats.lower_bound(parent_path);
196 if (it != pending_stats.end() && it->first.size() >= parent_path.size() &&
197 it->first.compare(0, parent_path.size(), parent_path) == 0) {
198 it->second.emplace_back(PendingStat{ filename, move(cb) });
200 it = pending_stats.emplace(filename, vector<PendingStat>{}).first;
201 engine->submit_stat(filename, [this, it, filename{ strdup(filename) }, cb{ move(cb) }] {
202 // The stat returned, so now do the actual access() calls.
203 // All of them should be in cache, so don't fire off new statx()
204 // calls during that check.
205 check_access(filename, /*allow_async=*/false, move(cb));
208 // Call all others that waited for the same stat() to finish.
209 // They may fire off new stat() calls if needed.
210 vector<PendingStat> pending = move(it->second);
211 pending_stats.erase(it);
212 for (PendingStat &ps : pending) {
213 check_access(ps.filename.c_str(), /*allow_async=*/true, move(ps.cb));
217 return; // The rest will happen in async context.
220 // Passed all checks.
226 Corpus(int fd, IOUringEngine *engine);
228 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
229 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
230 size_t get_num_filename_blocks() const;
231 off_t offset_for_block(uint32_t docid) const
233 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
238 IOUringEngine *const engine;
243 Corpus::Corpus(int fd, IOUringEngine *engine)
244 : fd(fd), engine(engine)
246 // Enable to test cold-cache behavior (except for access()).
248 off_t len = lseek(fd, 0, SEEK_END);
253 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
256 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
257 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
258 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
261 if (hdr.version != 0) {
262 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
272 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
274 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
275 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) {
276 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
277 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
278 if (trgmptr[i].trgm == trgm) {
279 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
289 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
291 // Read the file offset from this docid and the next one.
292 // This is always allowed, since we have a sentinel block at the end.
293 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
294 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
295 off_t offset = ptr[0];
296 size_t len = ptr[1] - ptr[0];
297 engine->submit_read(fd, len, offset, cb);
301 size_t Corpus::get_num_filename_blocks() const
303 return hdr.num_docids;
306 void scan_file_block(const vector<Needle> &needles, string_view compressed,
307 AccessRXCache *access_rx_cache, uint64_t seq, Serializer *serializer, IOUringEngine *engine,
310 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
311 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
312 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
317 block.resize(uncompressed_len + 1);
319 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
321 if (ZSTD_isError(err)) {
322 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
325 block[block.size() - 1] = '\0';
327 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
328 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
331 serializer->print(local_seq, next_seq - local_seq, filename);
333 serializer->print(local_seq, next_seq - local_seq, "");
339 // We need to know the next sequence number before inserting into Serializer,
340 // so always buffer one candidate.
341 const char *pending_candidate = nullptr;
343 uint64_t local_seq = seq << 32;
344 for (const char *filename = block.data();
345 filename != block.data() + block.size();
346 filename += strlen(filename) + 1) {
348 for (const Needle &needle : needles) {
349 if (!matches(needle, filename)) {
355 if (pending_candidate != nullptr) {
356 test_candidate(pending_candidate, local_seq, local_seq + 1);
359 pending_candidate = filename;
362 if (pending_candidate == nullptr) {
363 serializer->print(seq << 32, 1ULL << 32, "");
365 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
369 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
371 Serializer docids_in_order;
372 AccessRXCache access_rx_cache(engine);
373 uint64_t matched = 0;
374 for (size_t i = 0; i < docids.size(); ++i) {
375 uint32_t docid = docids[i];
376 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, engine, &docids_in_order](string_view compressed) {
377 scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order, engine, &matched);
384 // We do this sequentially, as it's faster than scattering
385 // a lot of I/O through io_uring and hoping the kernel will
386 // coalesce it plus readahead for us.
387 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
389 AccessRXCache access_rx_cache(engine);
390 uint32_t num_blocks = corpus.get_num_filename_blocks();
391 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
392 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
394 uint64_t matched = 0;
395 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
396 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
397 size_t io_len = offsets[last_docid] - offsets[io_docid];
398 if (compressed.size() < io_len) {
399 compressed.resize(io_len);
401 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
403 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
404 size_t relative_offset = offsets[docid] - offsets[io_docid];
405 size_t len = offsets[docid + 1] - offsets[docid];
406 scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr, engine, &matched);
412 // Takes the given posting list, unions it into the parts of the trigram disjunction
413 // already read; if the list is complete, intersects with “cur_candidates”.
415 // Returns true if the search should be aborted (we are done).
416 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
418 if (td->docids.empty()) {
419 td->docids = move(decoded);
422 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
423 swap(*tmp, td->docids);
425 if (--td->remaining_trigrams_to_read > 0) {
426 // Need to wait for more.
428 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
429 td->remaining_trigrams_to_read, td->index, td->docids.size());
433 if (cur_candidates->empty()) {
435 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
436 td->index, td->docids.size());
438 *cur_candidates = move(td->docids);
441 set_intersection(cur_candidates->begin(), cur_candidates->end(),
442 td->docids.begin(), td->docids.end(),
443 back_inserter(*tmp));
444 swap(*cur_candidates, *tmp);
446 if (cur_candidates->empty()) {
447 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
448 td->index, td->docids.size());
451 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
452 td->index, td->docids.size(), cur_candidates->size());
459 void do_search_file(const vector<Needle> &needles, const char *filename)
461 int fd = open(filename, O_RDONLY);
468 if (setgid(getgid()) != 0) {
473 start = steady_clock::now();
474 if (access("/", R_OK | X_OK)) {
475 // We can't find anything, no need to bother...
479 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
480 Corpus corpus(fd, &engine);
481 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
483 vector<TrigramDisjunction> trigram_groups;
484 if (patterns_are_regex) {
485 // We could parse the regex to find trigrams that have to be there
486 // (there are actually known algorithms to deal with disjunctions
487 // and such, too), but for now, we just go brute force.
488 // Using locate with regexes is pretty niche.
490 for (const Needle &needle : needles) {
491 parse_trigrams(needle.str, ignore_case, &trigram_groups);
497 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
498 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
500 // Give them names for debugging.
501 unsigned td_index = 0;
502 for (TrigramDisjunction &td : trigram_groups) {
503 td.index = td_index++;
506 // Collect which trigrams we need to look up in the hash table.
507 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
508 for (TrigramDisjunction &td : trigram_groups) {
509 for (uint32_t trgm : td.trigram_alternatives) {
510 trigrams_to_lookup[trgm].push_back(&td);
513 if (trigrams_to_lookup.empty()) {
514 // Too short for trigram matching. Apply brute force.
515 // (We could have searched through all trigrams that matched
516 // the pattern and done a union of them, but that's a lot of
517 // work for fairly unclear gain.)
518 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
520 printf("%" PRId64 "\n", matched);
525 // Look them all up on disk.
526 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
527 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
528 if (trgmptr == nullptr) {
529 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
530 for (TrigramDisjunction *td : *trigram_groups) {
531 --td->remaining_trigrams_to_read;
532 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
533 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
542 for (TrigramDisjunction *td : *trigram_groups) {
543 --td->remaining_trigrams_to_read;
544 td->max_num_docids += trgmptr->num_docids;
545 td->read_trigrams.emplace_back(*trgmptr, len);
550 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
552 for (TrigramDisjunction &td : trigram_groups) {
554 td.remaining_trigrams_to_read = td.read_trigrams.size();
556 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
557 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
561 // TODO: For case-insensitive (ie. more than one alternative in each),
562 // prioritize the ones with fewer seeks?
563 sort(trigram_groups.begin(), trigram_groups.end(),
564 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
565 return a.max_num_docids < b.max_num_docids;
568 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
569 for (TrigramDisjunction &td : trigram_groups) {
570 for (uint32_t trgm : td.trigram_alternatives) {
571 uses_trigram[trgm].push_back(&td);
575 unordered_set<uint32_t> trigrams_submitted_read;
576 vector<uint32_t> cur_candidates, tmp, decoded;
578 for (TrigramDisjunction &td : trigram_groups) {
579 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
580 dprintf("%s has up to %u entries, ignoring the rest (will "
581 "weed out false positives later)\n",
582 print_td(td).c_str(), td.max_num_docids);
586 for (auto &[trgmptr, len] : td.read_trigrams) {
587 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
590 trigrams_submitted_read.insert(trgmptr.trgm);
591 // Only stay a certain amount ahead, so that we don't spend I/O
592 // on reading the latter, large posting lists. We are unlikely
593 // to need them anyway, even if they should come in first.
594 if (engine.get_waiting_reads() >= 5) {
599 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
603 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
604 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
605 size_t num = trgmptr.num_docids;
607 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
609 assert(uses_trigram.count(trgm) != 0);
610 bool was_empty = cur_candidates.empty();
612 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
615 for (TrigramDisjunction *td : uses_trigram[trgm]) {
616 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
622 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
623 } else if (cur_candidates.empty()) {
624 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
626 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
636 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
637 1e3 * duration<float>(steady_clock::now() - start).count());
639 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
640 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
641 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
644 printf("%" PRId64 "\n", matched);
648 string unescape_glob_to_plain_string(const string &needle)
651 for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
652 uint32_t ch = read_unigram(needle, i).first;
653 assert(ch != WILDCARD_UNIGRAM);
654 if (ch == PREMATURE_END_UNIGRAM) {
655 fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
658 unescaped.push_back(ch);
663 regex_t compile_regex(const string &needle)
666 int flags = REG_NOSUB;
670 if (use_extended_regex) {
671 flags |= REG_EXTENDED;
673 int err = regcomp(&re, needle.c_str(), flags);
676 regerror(err, &re, errbuf, sizeof(errbuf));
677 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
686 "Usage: plocate [OPTION]... PATTERN...\n"
688 " -c, --count print number of matches instead of the matches\n"
689 " -d, --database DBPATH search for files in DBPATH\n"
690 " (default is " DEFAULT_DBPATH ")\n"
691 " -i, --ignore-case search case-insensitively\n"
692 " -l, --limit LIMIT stop after LIMIT matches\n"
693 " -0, --null delimit matches by NUL instead of newline\n"
694 " -r, --regexp interpret patterns as basic regexps (slow)\n"
695 " --regex interpret patterns as extended regexps (slow)\n"
696 " --help print this help\n"
697 " --version print version information\n");
702 printf("plocate %s\n", PLOCATE_VERSION);
703 printf("Copyright 2020 Steinar H. Gunderson\n");
704 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
705 printf("This is free software: you are free to change and redistribute it.\n");
706 printf("There is NO WARRANTY, to the extent permitted by law.\n");
710 int main(int argc, char **argv)
712 constexpr int EXTENDED_REGEX = 1000;
713 static const struct option long_options[] = {
714 { "help", no_argument, 0, 'h' },
715 { "count", no_argument, 0, 'c' },
716 { "database", required_argument, 0, 'd' },
717 { "ignore-case", no_argument, 0, 'i' },
718 { "limit", required_argument, 0, 'l' },
719 { "null", no_argument, 0, '0' },
720 { "version", no_argument, 0, 'V' },
721 { "regexp", no_argument, 0, 'r' },
722 { "regex", no_argument, 0, EXTENDED_REGEX },
723 { "debug", no_argument, 0, 'D' }, // Not documented.
727 setlocale(LC_ALL, "");
729 int option_index = 0;
730 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
739 dbpath = strdup(optarg);
749 limit_matches = limit_left = atoll(optarg);
750 if (limit_matches <= 0) {
751 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
759 patterns_are_regex = true;
762 patterns_are_regex = true;
763 use_extended_regex = true;
777 // Debug information would leak information about which files exist,
778 // so drop setgid before we open the file; one would either need to run
779 // as root, or use a locally-built file.
780 if (setgid(getgid()) != 0) {
786 vector<Needle> needles;
787 for (int i = optind; i < argc; ++i) {
789 needle.str = argv[i];
791 // See if there are any wildcard characters, which indicates we should treat it
792 // as an (anchored) glob.
793 bool any_wildcard = false;
794 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
795 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
801 if (patterns_are_regex) {
802 needle.type = Needle::REGEX;
803 needle.re = compile_regex(needle.str);
804 } else if (any_wildcard) {
805 needle.type = Needle::GLOB;
806 } else if (ignore_case) {
807 // strcasestr() doesn't handle locales correctly (even though LSB
808 // claims it should), but somehow, fnmatch() does, and it's about
809 // the same speed as using a regex.
810 needle.type = Needle::GLOB;
811 needle.str = "*" + needle.str + "*";
813 needle.type = Needle::STRSTR;
814 needle.str = unescape_glob_to_plain_string(needle.str);
816 needles.push_back(move(needle));
818 if (needles.empty()) {
819 fprintf(stderr, "plocate: no pattern to search for specified\n");
822 do_search_file(needles, dbpath);