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;
36 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
38 #include "turbopfor.h"
40 const char *dbpath = "/var/lib/mlocate/plocate.db";
41 bool ignore_case = false;
42 bool only_count = false;
43 bool print_nul = false;
44 int64_t limit_matches = numeric_limits<int64_t>::max();
48 bool ready_to_print(int seq) { return next_seq == seq; }
49 void print_delayed(int seq, const vector<string> msg);
50 void release_current();
58 bool operator<(const Element &other) const
60 return seq > other.seq;
63 priority_queue<Element> pending;
66 void Serializer::print_delayed(int seq, const vector<string> msg)
68 pending.push(Element{ seq, move(msg) });
71 void Serializer::release_current()
75 // See if any delayed prints can now be dealt with.
76 while (!pending.empty() && pending.top().seq == next_seq) {
77 if (limit_matches-- <= 0)
79 for (const string &msg : pending.top().msg) {
81 printf("%s%c", msg.c_str(), 0);
83 printf("%s\n", msg.c_str());
93 REGEX, // Not currently used.
95 string str; // Filled in no matter what.
96 regex_t re; // For REGEX.
99 bool matches(const Needle &needle, const char *haystack)
101 if (needle.type == Needle::STRSTR) {
102 return strstr(haystack, needle.str.c_str()) != nullptr;
103 } else if (needle.type == Needle::GLOB) {
104 int flags = ignore_case ? FNM_CASEFOLD : 0;
105 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
107 assert(needle.type == Needle::REGEX);
108 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
112 bool has_access(const char *filename,
113 unordered_map<string, bool> *access_rx_cache)
115 const char *end = strchr(filename + 1, '/');
116 while (end != nullptr) {
117 string parent_path(filename, end);
118 auto it = access_rx_cache->find(parent_path);
120 if (it == access_rx_cache->end()) {
121 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
122 access_rx_cache->emplace(move(parent_path), ok);
129 end = strchr(end + 1, '/');
137 Corpus(int fd, IOUringEngine *engine);
139 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
140 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
141 size_t get_num_filename_blocks() const;
142 off_t offset_for_block(uint32_t docid) const
144 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
149 IOUringEngine *const engine;
154 Corpus::Corpus(int fd, IOUringEngine *engine)
155 : fd(fd), engine(engine)
157 // Enable to test cold-cache behavior (except for access()).
159 off_t len = lseek(fd, 0, SEEK_END);
164 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
167 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
168 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
169 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
172 if (hdr.version != 0) {
173 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
183 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
185 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
186 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) {
187 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
188 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
189 if (trgmptr[i].trgm == trgm) {
190 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
200 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
202 // Read the file offset from this docid and the next one.
203 // This is always allowed, since we have a sentinel block at the end.
204 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
205 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
206 off_t offset = ptr[0];
207 size_t len = ptr[1] - ptr[0];
208 engine->submit_read(fd, len, offset, cb);
212 size_t Corpus::get_num_filename_blocks() const
214 return hdr.num_docids;
217 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
218 unordered_map<string, bool> *access_rx_cache, int seq,
219 Serializer *serializer)
221 uint64_t matched = 0;
223 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
224 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
225 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
230 block.resize(uncompressed_len + 1);
232 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
234 if (ZSTD_isError(err)) {
235 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
238 block[block.size() - 1] = '\0';
240 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
241 vector<string> delayed;
243 for (const char *filename = block.data();
244 filename != block.data() + block.size();
245 filename += strlen(filename) + 1) {
247 for (const Needle &needle : needles) {
248 if (!matches(needle, filename)) {
253 if (found && has_access(filename, access_rx_cache)) {
254 if (limit_matches-- <= 0)
259 if (immediate_print) {
261 printf("%s%c", filename, 0);
263 printf("%s\n", filename);
266 delayed.push_back(filename);
270 if (serializer != nullptr && !only_count) {
271 if (immediate_print) {
272 serializer->release_current();
274 serializer->print_delayed(seq, move(delayed));
280 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
282 Serializer docids_in_order;
283 unordered_map<string, bool> access_rx_cache;
284 uint64_t matched = 0;
285 for (size_t i = 0; i < docids.size(); ++i) {
286 uint32_t docid = docids[i];
287 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
288 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
295 // We do this sequentially, as it's faster than scattering
296 // a lot of I/O through io_uring and hoping the kernel will
297 // coalesce it plus readahead for us.
298 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
300 unordered_map<string, bool> access_rx_cache;
301 uint32_t num_blocks = corpus.get_num_filename_blocks();
302 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
303 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
305 uint64_t matched = 0;
306 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
307 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
308 size_t io_len = offsets[last_docid] - offsets[io_docid];
309 if (compressed.size() < io_len) {
310 compressed.resize(io_len);
312 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
314 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
315 size_t relative_offset = offsets[docid] - offsets[io_docid];
316 size_t len = offsets[docid + 1] - offsets[docid];
317 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
318 if (limit_matches <= 0)
325 // Takes the given posting list, unions it into the parts of the trigram disjunction
326 // already read; if the list is complete, intersects with “cur_candidates”.
328 // Returns true if the search should be aborted (we are done).
329 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
331 if (td->docids.empty()) {
332 td->docids = move(decoded);
335 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
336 swap(*tmp, td->docids);
338 if (--td->remaining_trigrams_to_read > 0) {
339 // Need to wait for more.
341 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
342 td->remaining_trigrams_to_read, td->index, td->docids.size());
346 if (cur_candidates->empty()) {
348 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
349 td->index, td->docids.size());
351 *cur_candidates = move(td->docids);
354 set_intersection(cur_candidates->begin(), cur_candidates->end(),
355 td->docids.begin(), td->docids.end(),
356 back_inserter(*tmp));
357 swap(*cur_candidates, *tmp);
359 if (cur_candidates->empty()) {
360 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
361 td->index, td->docids.size());
364 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
365 td->index, td->docids.size(), cur_candidates->size());
372 void do_search_file(const vector<Needle> &needles, const char *filename)
374 int fd = open(filename, O_RDONLY);
381 if (setgid(getgid()) != 0) {
386 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
387 if (access("/", R_OK | X_OK)) {
388 // We can't find anything, no need to bother...
392 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
393 Corpus corpus(fd, &engine);
394 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
396 vector<TrigramDisjunction> trigram_groups;
397 for (const Needle &needle : needles) {
398 if (needle.str.size() < 3)
400 parse_trigrams(needle.str, ignore_case, &trigram_groups);
404 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
405 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
407 // Give them names for debugging.
408 unsigned td_index = 0;
409 for (TrigramDisjunction &td : trigram_groups) {
410 td.index = td_index++;
413 // Collect which trigrams we need to look up in the hash table.
414 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
415 for (TrigramDisjunction &td : trigram_groups) {
416 for (uint32_t trgm : td.trigram_alternatives) {
417 trigrams_to_lookup[trgm].push_back(&td);
420 if (trigrams_to_lookup.empty()) {
421 // Too short for trigram matching. Apply brute force.
422 // (We could have searched through all trigrams that matched
423 // the pattern and done a union of them, but that's a lot of
424 // work for fairly unclear gain.)
425 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
427 printf("%zu\n", matched);
432 // Look them all up on disk.
433 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
434 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
435 if (trgmptr == nullptr) {
436 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
437 for (TrigramDisjunction *td : *trigram_groups) {
438 --td->remaining_trigrams_to_read;
439 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
440 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
449 for (TrigramDisjunction *td : *trigram_groups) {
450 --td->remaining_trigrams_to_read;
451 td->max_num_docids += trgmptr->num_docids;
452 td->read_trigrams.emplace_back(*trgmptr, len);
457 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
459 for (TrigramDisjunction &td : trigram_groups) {
461 td.remaining_trigrams_to_read = td.read_trigrams.size();
463 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
464 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
468 // TODO: For case-insensitive (ie. more than one alternative in each),
469 // prioritize the ones with fewer seeks?
470 sort(trigram_groups.begin(), trigram_groups.end(),
471 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
472 return a.max_num_docids < b.max_num_docids;
475 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
476 for (TrigramDisjunction &td : trigram_groups) {
477 for (uint32_t trgm : td.trigram_alternatives) {
478 uses_trigram[trgm].push_back(&td);
482 unordered_set<uint32_t> trigrams_submitted_read;
483 vector<uint32_t> cur_candidates, tmp, decoded;
485 for (TrigramDisjunction &td : trigram_groups) {
486 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
487 dprintf("%s has up to %u entries, ignoring the rest (will "
488 "weed out false positives later)\n",
489 print_td(td).c_str(), td.max_num_docids);
493 for (auto &[trgmptr, len] : td.read_trigrams) {
494 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
497 trigrams_submitted_read.insert(trgmptr.trgm);
498 // Only stay a certain amount ahead, so that we don't spend I/O
499 // on reading the latter, large posting lists. We are unlikely
500 // to need them anyway, even if they should come in first.
501 if (engine.get_waiting_reads() >= 5) {
506 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
510 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
511 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
512 size_t num = trgmptr.num_docids;
514 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
516 assert(uses_trigram.count(trgm) != 0);
517 bool was_empty = cur_candidates.empty();
519 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
522 for (TrigramDisjunction *td : uses_trigram[trgm]) {
523 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
529 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
530 } else if (cur_candidates.empty()) {
531 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
533 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
543 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
544 1e3 * duration<float>(steady_clock::now() - start).count());
546 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
547 dprintf("Done in %.1f ms, found %zu matches.\n",
548 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
551 printf("%zu\n", matched);
555 string unescape_glob_to_plain_string(const string &needle)
558 for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
559 uint32_t ch = read_unigram(needle, i).first;
560 assert(ch != WILDCARD_UNIGRAM);
561 if (ch == PREMATURE_END_UNIGRAM) {
562 fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
565 unescaped.push_back(ch);
572 // The help text comes from mlocate.
573 printf("Usage: plocate [OPTION]... PATTERN...\n");
575 printf(" -c, --count only print number of found entries\n");
576 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
577 printf(" %s)\n", dbpath);
578 printf(" -h, --help print this help\n");
579 printf(" -i, --ignore-case ignore case distinctions when matching patterns\n");
580 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
581 printf(" -0, --null separate entries with NUL on output\n");
584 int main(int argc, char **argv)
586 static const struct option long_options[] = {
587 { "help", no_argument, 0, 'h' },
588 { "count", no_argument, 0, 'c' },
589 { "database", required_argument, 0, 'd' },
590 { "ignore-case", no_argument, 0, 'i' },
591 { "limit", required_argument, 0, 'l' },
592 { nullptr, required_argument, 0, 'n' },
593 { "null", no_argument, 0, '0' },
597 setlocale(LC_ALL, "");
599 int option_index = 0;
600 int c = getopt_long(argc, argv, "cd:hil:n:0", long_options, &option_index);
609 dbpath = strdup(optarg);
619 limit_matches = atoll(optarg);
629 vector<Needle> needles;
630 for (int i = optind; i < argc; ++i) {
632 needle.str = argv[i];
634 // See if there are any wildcard characters, which indicates we should treat it
635 // as an (anchored) glob.
636 bool any_wildcard = false;
637 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
638 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
645 needle.type = Needle::GLOB;
646 } else if (ignore_case) {
647 // strcasestr() doesn't handle locales correctly (even though LSB
648 // claims it should), but somehow, fnmatch() does, and it's about
649 // the same speed as using a regex.
650 needle.type = Needle::GLOB;
651 needle.str = "*" + needle.str + "*";
653 needle.type = Needle::STRSTR;
654 needle.str = unescape_glob_to_plain_string(needle.str);
656 needles.push_back(move(needle));
658 if (needles.empty()) {
659 fprintf(stderr, "plocate: no pattern to search for specified\n");
662 do_search_file(needles, dbpath);