2 #include "io_uring_engine.h"
19 #include <string_view>
21 #include <unordered_map>
27 using namespace std::chrono;
30 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
32 #include "turbopfor.h"
34 const char *dbpath = "/var/lib/mlocate/plocate.db";
35 bool only_count = false;
36 bool print_nul = false;
37 int64_t limit_matches = numeric_limits<int64_t>::max();
41 bool ready_to_print(int seq) { return next_seq == seq; }
42 void print_delayed(int seq, const vector<string> msg);
43 void release_current();
51 bool operator<(const Element &other) const
53 return seq > other.seq;
56 priority_queue<Element> pending;
59 void Serializer::print_delayed(int seq, const vector<string> msg)
61 pending.push(Element{ seq, move(msg) });
64 void Serializer::release_current()
68 // See if any delayed prints can now be dealt with.
69 while (!pending.empty() && pending.top().seq == next_seq) {
70 if (limit_matches-- <= 0)
72 for (const string &msg : pending.top().msg) {
74 printf("%s%c", msg.c_str(), 0);
76 printf("%s\n", msg.c_str());
84 static inline uint32_t read_unigram(const string &s, size_t idx)
87 return (unsigned char)s[idx];
93 static inline uint32_t read_trigram(const string &s, size_t start)
95 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
96 (read_unigram(s, start + 2) << 16);
99 bool has_access(const char *filename,
100 unordered_map<string, bool> *access_rx_cache)
102 const char *end = strchr(filename + 1, '/');
103 while (end != nullptr) {
104 string parent_path(filename, end);
105 auto it = access_rx_cache->find(parent_path);
107 if (it == access_rx_cache->end()) {
108 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
109 access_rx_cache->emplace(move(parent_path), ok);
116 end = strchr(end + 1, '/');
124 Corpus(int fd, IOUringEngine *engine);
126 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
127 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
128 size_t get_num_filename_blocks() const;
129 off_t offset_for_block(uint32_t docid) const
131 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
136 IOUringEngine *const engine;
141 Corpus::Corpus(int fd, IOUringEngine *engine)
142 : fd(fd), engine(engine)
144 // Enable to test cold-cache behavior (except for access()).
146 off_t len = lseek(fd, 0, SEEK_END);
151 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
154 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
155 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
156 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
159 if (hdr.version != 0) {
160 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
170 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
172 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
173 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) {
174 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
175 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
176 if (trgmptr[i].trgm == trgm) {
177 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
187 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
189 // Read the file offset from this docid and the next one.
190 // This is always allowed, since we have a sentinel block at the end.
191 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
192 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
193 off_t offset = ptr[0];
194 size_t len = ptr[1] - ptr[0];
195 engine->submit_read(fd, len, offset, cb);
199 size_t Corpus::get_num_filename_blocks() const
201 return hdr.num_docids;
204 uint64_t scan_file_block(const vector<string> &needles, string_view compressed,
205 unordered_map<string, bool> *access_rx_cache, int seq,
206 Serializer *serializer)
208 uint64_t matched = 0;
210 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
211 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
212 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
217 block.resize(uncompressed_len + 1);
219 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
221 if (ZSTD_isError(err)) {
222 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
225 block[block.size() - 1] = '\0';
227 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
228 vector<string> delayed;
230 for (const char *filename = block.data();
231 filename != block.data() + block.size();
232 filename += strlen(filename) + 1) {
234 for (const string &needle : needles) {
235 if (strstr(filename, needle.c_str()) == nullptr) {
240 if (found && has_access(filename, access_rx_cache)) {
241 if (limit_matches-- <= 0)
246 if (immediate_print) {
248 printf("%s%c", filename, 0);
250 printf("%s\n", filename);
253 delayed.push_back(filename);
257 if (serializer != nullptr && !only_count) {
258 if (immediate_print) {
259 serializer->release_current();
261 serializer->print_delayed(seq, move(delayed));
267 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
269 Serializer docids_in_order;
270 unordered_map<string, bool> access_rx_cache;
271 uint64_t matched = 0;
272 for (size_t i = 0; i < docids.size(); ++i) {
273 uint32_t docid = docids[i];
274 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
275 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
282 // We do this sequentially, as it's faster than scattering
283 // a lot of I/O through io_uring and hoping the kernel will
284 // coalesce it plus readahead for us.
285 uint64_t scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
287 unordered_map<string, bool> access_rx_cache;
288 uint32_t num_blocks = corpus.get_num_filename_blocks();
289 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
290 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
292 uint64_t matched = 0;
293 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
294 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
295 size_t io_len = offsets[last_docid] - offsets[io_docid];
296 if (compressed.size() < io_len) {
297 compressed.resize(io_len);
299 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
301 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
302 size_t relative_offset = offsets[docid] - offsets[io_docid];
303 size_t len = offsets[docid + 1] - offsets[docid];
304 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
305 if (limit_matches <= 0)
313 string print_trigram(uint32_t trgm)
316 char(trgm & 0xff), char((trgm >> 8) & 0xff), char((trgm >> 16) & 0xff)
320 for (unsigned i = 0; i < 3;) {
323 str.push_back(ch[i]);
325 } else if (int(ch[i]) >= 32 && int(ch[i]) <= 127) { // Holds no matter whether char is signed or unsigned.
326 str.push_back(ch[i]);
329 // See if we have an entire UTF-8 codepoint, and that it's reasonably printable.
330 mbtowc(nullptr, 0, 0);
332 int ret = mbtowc(&pwc, ch + i, 3 - i);
333 if (ret >= 1 && pwc >= 32) {
334 str.append(ch + i, ret);
338 snprintf(buf, sizeof(buf), "\\x{%02x}", (unsigned char)ch[i]);
348 void do_search_file(const vector<string> &needles, const char *filename)
350 int fd = open(filename, O_RDONLY);
357 if (setgid(getgid()) != 0) {
362 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
363 if (access("/", R_OK | X_OK)) {
364 // We can't find anything, no need to bother...
368 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
369 Corpus corpus(fd, &engine);
370 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
372 vector<pair<Trigram, size_t>> trigrams;
373 uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
374 for (const string &needle : needles) {
375 if (needle.size() < 3)
377 for (size_t i = 0; i < needle.size() - 2; ++i) {
378 uint32_t trgm = read_trigram(needle, i);
379 corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
380 if (trgmptr == nullptr) {
381 dprintf("trigram %s isn't found, we abort the search\n", print_trigram(trgm).c_str());
387 if (trgmptr->num_docids > shortest_so_far * 100) {
388 dprintf("not loading trigram %s with %u docids, it would be ignored later anyway\n",
389 print_trigram(trgm).c_str(), trgmptr->num_docids);
391 trigrams.emplace_back(*trgmptr, len);
392 shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
398 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
400 if (trigrams.empty()) {
401 // Too short for trigram matching. Apply brute force.
402 // (We could have searched through all trigrams that matched
403 // the pattern and done a union of them, but that's a lot of
404 // work for fairly unclear gain.)
405 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
407 printf("%zu\n", matched);
411 sort(trigrams.begin(), trigrams.end());
413 auto last = unique(trigrams.begin(), trigrams.end());
414 trigrams.erase(last, trigrams.end());
416 sort(trigrams.begin(), trigrams.end(),
417 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
418 return a.first.num_docids < b.first.num_docids;
421 vector<uint32_t> in1, in2, out;
423 for (auto [trgmptr, len] : trigrams) {
424 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
425 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
426 dprintf("trigram %s (%zu bytes) has %u entries, ignoring the rest (will "
427 "weed out false positives later)\n",
428 print_trigram(trgm).c_str(), len, trgmptr.num_docids);
432 // Only stay a certain amount ahead, so that we don't spend I/O
433 // on reading the latter, large posting lists. We are unlikely
434 // to need them anyway, even if they should come in first.
435 if (engine.get_waiting_reads() >= 5) {
440 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &in1, &in2, &out](string_view s) {
443 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
444 size_t num = trgmptr.num_docids;
445 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
447 in1.resize(num + 128);
448 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in1[0]);
450 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n",
451 print_trigram(trgm).c_str(), len, num);
453 if (in2.size() < num + 128) {
454 in2.resize(num + 128);
456 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in2[0]);
459 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
462 dprintf("trigram %s (%zu bytes) decoded to %zu entries, %zu left\n",
463 print_trigram(trgm).c_str(), len, num, in1.size());
465 dprintf("no matches (intersection list is empty)\n");
475 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
476 1e3 * duration<float>(steady_clock::now() - start).count());
478 uint64_t matched = scan_docids(needles, in1, corpus, &engine);
479 dprintf("Done in %.1f ms, found %zu matches.\n",
480 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
483 printf("%zu\n", matched);
489 // The help text comes from mlocate.
490 printf("Usage: plocate [OPTION]... PATTERN...\n");
492 printf(" -c, --count only print number of found entries\n");
493 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
494 printf(" %s)\n", dbpath);
495 printf(" -h, --help print this help\n");
496 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
497 printf(" -0, --null separate entries with NUL on output\n");
500 int main(int argc, char **argv)
502 static const struct option long_options[] = {
503 { "help", no_argument, 0, 'h' },
504 { "count", no_argument, 0, 'c' },
505 { "database", required_argument, 0, 'd' },
506 { "limit", required_argument, 0, 'l' },
507 { nullptr, required_argument, 0, 'n' },
508 { "null", no_argument, 0, '0' },
512 setlocale(LC_ALL, "");
514 int option_index = 0;
515 int c = getopt_long(argc, argv, "cd:hl:n:0", long_options, &option_index);
524 dbpath = strdup(optarg);
531 limit_matches = atoll(optarg);
541 vector<string> needles;
542 for (int i = optind; i < argc; ++i) {
543 needles.push_back(argv[i]);
545 if (needles.empty()) {
546 fprintf(stderr, "plocate: no pattern to search for specified\n");
549 do_search_file(needles, dbpath);