2 #include "io_uring_engine.h"
3 #include "parse_trigrams.h"
4 #include "unique_sort.h"
23 #include <string_view>
25 #include <unordered_map>
26 #include <unordered_set>
32 using namespace std::chrono;
35 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
37 #include "turbopfor.h"
39 const char *dbpath = "/var/lib/mlocate/plocate.db";
40 bool ignore_case = false;
41 bool only_count = false;
42 bool print_nul = false;
43 int64_t limit_matches = numeric_limits<int64_t>::max();
47 bool ready_to_print(int seq) { return next_seq == seq; }
48 void print_delayed(int seq, const vector<string> msg);
49 void release_current();
57 bool operator<(const Element &other) const
59 return seq > other.seq;
62 priority_queue<Element> pending;
65 void Serializer::print_delayed(int seq, const vector<string> msg)
67 pending.push(Element{ seq, move(msg) });
70 void Serializer::release_current()
74 // See if any delayed prints can now be dealt with.
75 while (!pending.empty() && pending.top().seq == next_seq) {
76 if (limit_matches-- <= 0)
78 for (const string &msg : pending.top().msg) {
80 printf("%s%c", msg.c_str(), 0);
82 printf("%s\n", msg.c_str());
93 string str; // Filled in no matter what.
94 regex_t re; // For REGEX.
97 bool matches(const Needle &needle, const char *haystack)
99 if (needle.type == Needle::STRSTR) {
100 return strstr(haystack, needle.str.c_str()) != nullptr;
102 assert(needle.type == Needle::REGEX);
103 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
107 bool has_access(const char *filename,
108 unordered_map<string, bool> *access_rx_cache)
110 const char *end = strchr(filename + 1, '/');
111 while (end != nullptr) {
112 string parent_path(filename, end);
113 auto it = access_rx_cache->find(parent_path);
115 if (it == access_rx_cache->end()) {
116 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
117 access_rx_cache->emplace(move(parent_path), ok);
124 end = strchr(end + 1, '/');
132 Corpus(int fd, IOUringEngine *engine);
134 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
135 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
136 size_t get_num_filename_blocks() const;
137 off_t offset_for_block(uint32_t docid) const
139 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
144 IOUringEngine *const engine;
149 Corpus::Corpus(int fd, IOUringEngine *engine)
150 : fd(fd), engine(engine)
152 // Enable to test cold-cache behavior (except for access()).
154 off_t len = lseek(fd, 0, SEEK_END);
159 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
162 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
163 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
164 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
167 if (hdr.version != 0) {
168 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
178 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
180 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
181 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) {
182 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
183 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
184 if (trgmptr[i].trgm == trgm) {
185 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
195 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
197 // Read the file offset from this docid and the next one.
198 // This is always allowed, since we have a sentinel block at the end.
199 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
200 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
201 off_t offset = ptr[0];
202 size_t len = ptr[1] - ptr[0];
203 engine->submit_read(fd, len, offset, cb);
207 size_t Corpus::get_num_filename_blocks() const
209 return hdr.num_docids;
212 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
213 unordered_map<string, bool> *access_rx_cache, int seq,
214 Serializer *serializer)
216 uint64_t matched = 0;
218 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
219 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
220 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
225 block.resize(uncompressed_len + 1);
227 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
229 if (ZSTD_isError(err)) {
230 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
233 block[block.size() - 1] = '\0';
235 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
236 vector<string> delayed;
238 for (const char *filename = block.data();
239 filename != block.data() + block.size();
240 filename += strlen(filename) + 1) {
242 for (const Needle &needle : needles) {
243 if (!matches(needle, filename)) {
248 if (found && has_access(filename, access_rx_cache)) {
249 if (limit_matches-- <= 0)
254 if (immediate_print) {
256 printf("%s%c", filename, 0);
258 printf("%s\n", filename);
261 delayed.push_back(filename);
265 if (serializer != nullptr && !only_count) {
266 if (immediate_print) {
267 serializer->release_current();
269 serializer->print_delayed(seq, move(delayed));
275 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
277 Serializer docids_in_order;
278 unordered_map<string, bool> access_rx_cache;
279 uint64_t matched = 0;
280 for (size_t i = 0; i < docids.size(); ++i) {
281 uint32_t docid = docids[i];
282 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
283 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
290 // We do this sequentially, as it's faster than scattering
291 // a lot of I/O through io_uring and hoping the kernel will
292 // coalesce it plus readahead for us.
293 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
295 unordered_map<string, bool> access_rx_cache;
296 uint32_t num_blocks = corpus.get_num_filename_blocks();
297 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
298 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
300 uint64_t matched = 0;
301 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
302 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
303 size_t io_len = offsets[last_docid] - offsets[io_docid];
304 if (compressed.size() < io_len) {
305 compressed.resize(io_len);
307 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
309 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
310 size_t relative_offset = offsets[docid] - offsets[io_docid];
311 size_t len = offsets[docid + 1] - offsets[docid];
312 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
313 if (limit_matches <= 0)
320 // Takes the given posting list, unions it into the parts of the trigram disjunction
321 // already read; if the list is complete, intersects with “cur_candidates”.
323 // Returns true if the search should be aborted (we are done).
324 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
326 if (td->docids.empty()) {
327 td->docids = move(decoded);
330 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
331 swap(*tmp, td->docids);
333 if (--td->remaining_trigrams_to_read > 0) {
334 // Need to wait for more.
336 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
337 td->remaining_trigrams_to_read, td->index, td->docids.size());
341 if (cur_candidates->empty()) {
343 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
344 td->index, td->docids.size());
346 *cur_candidates = move(td->docids);
349 set_intersection(cur_candidates->begin(), cur_candidates->end(),
350 td->docids.begin(), td->docids.end(),
351 back_inserter(*tmp));
352 swap(*cur_candidates, *tmp);
354 if (cur_candidates->empty()) {
355 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
356 td->index, td->docids.size());
359 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
360 td->index, td->docids.size(), cur_candidates->size());
367 void do_search_file(const vector<Needle> &needles, const char *filename)
369 int fd = open(filename, O_RDONLY);
376 if (setgid(getgid()) != 0) {
381 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
382 if (access("/", R_OK | X_OK)) {
383 // We can't find anything, no need to bother...
387 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
388 Corpus corpus(fd, &engine);
389 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
391 vector<TrigramDisjunction> trigram_groups;
392 for (const Needle &needle : needles) {
393 if (needle.str.size() < 3)
395 parse_trigrams(needle.str, ignore_case, &trigram_groups);
399 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
400 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
402 // Give them names for debugging.
403 unsigned td_index = 0;
404 for (TrigramDisjunction &td : trigram_groups) {
405 td.index = td_index++;
408 // Collect which trigrams we need to look up in the hash table.
409 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
410 for (TrigramDisjunction &td : trigram_groups) {
411 for (uint32_t trgm : td.trigram_alternatives) {
412 trigrams_to_lookup[trgm].push_back(&td);
415 if (trigrams_to_lookup.empty()) {
416 // Too short for trigram matching. Apply brute force.
417 // (We could have searched through all trigrams that matched
418 // the pattern and done a union of them, but that's a lot of
419 // work for fairly unclear gain.)
420 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
422 printf("%zu\n", matched);
427 // Look them all up on disk.
428 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
429 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
430 if (trgmptr == nullptr) {
431 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
432 for (TrigramDisjunction *td : *trigram_groups) {
433 --td->remaining_trigrams_to_read;
434 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
435 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
444 for (TrigramDisjunction *td : *trigram_groups) {
445 --td->remaining_trigrams_to_read;
446 td->max_num_docids += trgmptr->num_docids;
447 td->read_trigrams.emplace_back(*trgmptr, len);
452 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
454 for (TrigramDisjunction &td : trigram_groups) {
456 td.remaining_trigrams_to_read = td.read_trigrams.size();
458 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
459 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
463 // TODO: For case-insensitive (ie. more than one alternative in each),
464 // prioritize the ones with fewer seeks?
465 sort(trigram_groups.begin(), trigram_groups.end(),
466 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
467 return a.max_num_docids < b.max_num_docids;
470 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
471 for (TrigramDisjunction &td : trigram_groups) {
472 for (uint32_t trgm : td.trigram_alternatives) {
473 uses_trigram[trgm].push_back(&td);
477 unordered_set<uint32_t> trigrams_submitted_read;
478 vector<uint32_t> cur_candidates, tmp, decoded;
480 for (TrigramDisjunction &td : trigram_groups) {
481 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
482 dprintf("%s has up to %u entries, ignoring the rest (will "
483 "weed out false positives later)\n",
484 print_td(td).c_str(), td.max_num_docids);
488 for (auto &[trgmptr, len] : td.read_trigrams) {
489 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
492 trigrams_submitted_read.insert(trgmptr.trgm);
493 // Only stay a certain amount ahead, so that we don't spend I/O
494 // on reading the latter, large posting lists. We are unlikely
495 // to need them anyway, even if they should come in first.
496 if (engine.get_waiting_reads() >= 5) {
501 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
505 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
506 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
507 size_t num = trgmptr.num_docids;
509 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
511 assert(uses_trigram.count(trgm) != 0);
512 bool was_empty = cur_candidates.empty();
514 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
517 for (TrigramDisjunction *td : uses_trigram[trgm]) {
518 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
524 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
525 } else if (cur_candidates.empty()) {
526 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
528 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
538 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
539 1e3 * duration<float>(steady_clock::now() - start).count());
541 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
542 dprintf("Done in %.1f ms, found %zu matches.\n",
543 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
546 printf("%zu\n", matched);
550 regex_t needle_to_regex(const string &needle)
552 string escaped_needle;
553 for (char ch : needle) {
555 // Directly from what regex(7) considers an “atom”.
568 escaped_needle.push_back('\\');
571 escaped_needle.push_back(ch);
577 err = regcomp(&re, escaped_needle.c_str(), REG_NOSUB | REG_ICASE);
579 err = regcomp(&re, escaped_needle.c_str(), REG_NOSUB);
583 regerror(err, &re, errbuf, sizeof(errbuf));
584 fprintf(stderr, "Error when compiling regex for '%s': %s\n", needle.c_str(), errbuf);
592 // The help text comes from mlocate.
593 printf("Usage: plocate [OPTION]... PATTERN...\n");
595 printf(" -c, --count only print number of found entries\n");
596 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
597 printf(" %s)\n", dbpath);
598 printf(" -h, --help print this help\n");
599 printf(" -i, --ignore-case ignore case distinctions when matching patterns\n");
600 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
601 printf(" -0, --null separate entries with NUL on output\n");
604 int main(int argc, char **argv)
606 static const struct option long_options[] = {
607 { "help", no_argument, 0, 'h' },
608 { "count", no_argument, 0, 'c' },
609 { "database", required_argument, 0, 'd' },
610 { "ignore-case", no_argument, 0, 'i' },
611 { "limit", required_argument, 0, 'l' },
612 { nullptr, required_argument, 0, 'n' },
613 { "null", no_argument, 0, '0' },
617 setlocale(LC_ALL, "");
619 int option_index = 0;
620 int c = getopt_long(argc, argv, "cd:hil:n:0", long_options, &option_index);
629 dbpath = strdup(optarg);
639 limit_matches = atoll(optarg);
649 vector<Needle> needles;
650 for (int i = optind; i < argc; ++i) {
652 needle.str = argv[i];
654 // strcasestr() doesn't handle locales correctly (even though LSB
655 // claims it should), but somehow, the glibc regex engine does.
656 // It's much slower than strstr() for non-case-sensitive searches, though
657 // (even though it really ought to be faster, since it can precompile),
658 // so only use it for that.
659 needle.type = Needle::REGEX;
660 needle.re = needle_to_regex(argv[i]);
662 needle.type = Needle::STRSTR;
664 needles.push_back(move(needle));
666 if (needles.empty()) {
667 fprintf(stderr, "plocate: no pattern to search for specified\n");
670 do_search_file(needles, dbpath);