2 #include "io_uring_engine.h"
18 #include <unordered_map>
23 using namespace std::chrono;
26 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
28 #include "turbopfor.h"
30 const char *dbpath = "/var/lib/mlocate/plocate.db";
31 bool only_count = false;
32 bool print_nul = false;
33 int64_t limit_matches = -1;
37 bool ready_to_print(int seq) { return next_seq == seq; }
38 void print_delayed(int seq, const vector<string> msg);
39 void release_current();
47 bool operator<(const Element &other) const
49 return seq > other.seq;
52 priority_queue<Element> pending;
55 void Serializer::print_delayed(int seq, const vector<string> msg)
57 pending.push(Element{ seq, move(msg) });
60 void Serializer::release_current()
64 // See if any delayed prints can now be dealt with.
65 while (!pending.empty() && pending.top().seq == next_seq) {
66 if (limit_matches-- <= 0) return;
67 for (const string &msg : pending.top().msg) {
69 printf("%s%c", msg.c_str(), 0);
71 printf("%s\n", msg.c_str());
79 static inline uint32_t read_unigram(const string &s, size_t idx)
82 return (unsigned char)s[idx];
88 static inline uint32_t read_trigram(const string &s, size_t start)
90 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
91 (read_unigram(s, start + 2) << 16);
94 bool has_access(const char *filename,
95 unordered_map<string, bool> *access_rx_cache)
97 const char *end = strchr(filename + 1, '/');
98 while (end != nullptr) {
99 string parent_path(filename, end);
100 auto it = access_rx_cache->find(parent_path);
102 if (it == access_rx_cache->end()) {
103 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
104 access_rx_cache->emplace(move(parent_path), ok);
111 end = strchr(end + 1, '/');
119 Corpus(int fd, IOUringEngine *engine);
121 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
122 void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
123 size_t get_num_filename_blocks() const;
124 off_t offset_for_block(uint32_t docid) const
126 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
131 IOUringEngine *const engine;
136 Corpus::Corpus(int fd, IOUringEngine *engine)
137 : fd(fd), engine(engine)
139 // Enable to test cold-cache behavior (except for access()).
141 off_t len = lseek(fd, 0, SEEK_END);
146 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
149 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
150 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
151 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
154 if (hdr.version != 0) {
155 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
165 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
167 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
168 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 s) {
169 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
170 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
171 if (trgmptr[i].trgm == trgm) {
172 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
182 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
184 // Read the file offset from this docid and the next one.
185 // This is always allowed, since we have a sentinel block at the end.
186 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
187 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
188 off_t offset = ptr[0];
189 size_t len = ptr[1] - ptr[0];
190 engine->submit_read(fd, len, offset, cb);
194 size_t Corpus::get_num_filename_blocks() const
196 return hdr.num_docids;
199 uint64_t scan_file_block(const vector<string> &needles, string_view compressed,
200 unordered_map<string, bool> *access_rx_cache, int seq,
201 Serializer *serializer)
203 uint64_t matched = 0;
205 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
206 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
207 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
212 block.resize(uncompressed_len + 1);
214 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
216 if (ZSTD_isError(err)) {
217 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
220 block[block.size() - 1] = '\0';
222 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
223 vector<string> delayed;
225 for (const char *filename = block.data();
226 filename != block.data() + block.size();
227 filename += strlen(filename) + 1) {
229 for (const string &needle : needles) {
230 if (strstr(filename, needle.c_str()) == nullptr) {
235 if (found && has_access(filename, access_rx_cache)) {
236 if (limit_matches-- <= 0) break;
238 if (only_count) continue;
239 if (immediate_print) {
241 printf("%s%c", filename, 0);
243 printf("%s\n", filename);
246 delayed.push_back(filename);
250 if (serializer != nullptr && !only_count) {
251 if (immediate_print) {
252 serializer->release_current();
254 serializer->print_delayed(seq, move(delayed));
260 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
262 Serializer docids_in_order;
263 unordered_map<string, bool> access_rx_cache;
264 uint64_t matched = 0;
265 for (size_t i = 0; i < docids.size(); ++i) {
266 uint32_t docid = docids[i];
267 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
268 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
275 // We do this sequentially, as it's faster than scattering
276 // a lot of I/O through io_uring and hoping the kernel will
277 // coalesce it plus readahead for us.
278 uint64_t scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
280 unordered_map<string, bool> access_rx_cache;
281 uint32_t num_blocks = corpus.get_num_filename_blocks();
282 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
283 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
285 uint64_t matched = 0;
286 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
287 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
288 size_t io_len = offsets[last_docid] - offsets[io_docid];
289 if (compressed.size() < io_len) {
290 compressed.resize(io_len);
292 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
294 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
295 size_t relative_offset = offsets[docid] - offsets[io_docid];
296 size_t len = offsets[docid + 1] - offsets[docid];
297 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
298 if (limit_matches <= 0) return matched;
304 void do_search_file(const vector<string> &needles, const char *filename)
306 int fd = open(filename, O_RDONLY);
313 if (setgid(getgid()) != 0) {
318 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
319 if (access("/", R_OK | X_OK)) {
320 // We can't find anything, no need to bother...
324 IOUringEngine engine;
325 Corpus corpus(fd, &engine);
326 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
328 vector<pair<Trigram, size_t>> trigrams;
329 uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
330 for (const string &needle : needles) {
331 if (needle.size() < 3)
333 for (size_t i = 0; i < needle.size() - 2; ++i) {
334 uint32_t trgm = read_trigram(needle, i);
335 corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
336 if (trgmptr == nullptr) {
337 dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
338 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
344 if (trgmptr->num_docids > shortest_so_far * 100) {
345 dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
346 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
347 trgmptr->num_docids);
349 trigrams.emplace_back(*trgmptr, len);
350 shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
356 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
358 if (trigrams.empty()) {
359 // Too short for trigram matching. Apply brute force.
360 // (We could have searched through all trigrams that matched
361 // the pattern and done a union of them, but that's a lot of
362 // work for fairly unclear gain.)
363 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
364 printf("%zu\n", matched);
367 sort(trigrams.begin(), trigrams.end());
369 auto last = unique(trigrams.begin(), trigrams.end());
370 trigrams.erase(last, trigrams.end());
372 sort(trigrams.begin(), trigrams.end(),
373 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
374 return a.first.num_docids < b.first.num_docids;
377 vector<uint32_t> in1, in2, out;
379 for (auto [trgmptr, len] : trigrams) {
380 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
381 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
382 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
383 "weed out false positives later)\n",
384 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
385 len, trgmptr.num_docids);
389 // Only stay a certain amount ahead, so that we don't spend I/O
390 // on reading the latter, large posting lists. We are unlikely
391 // to need them anyway, even if they should come in first.
392 if (engine.get_waiting_reads() >= 5) {
397 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{trgmptr}, len{len}, &done, &in1, &in2, &out](string s) {
400 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
401 size_t num = trgmptr.num_docids;
402 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
404 in1.resize(num + 128);
405 decode_pfor_delta1<128>(pldata, num, /*interleaved=*/true, &in1[0]);
407 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
408 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
410 if (in2.size() < num + 128) {
411 in2.resize(num + 128);
413 decode_pfor_delta1<128>(pldata, num, /*interleaved=*/true, &in2[0]);
416 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
419 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
420 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
421 len, num, in1.size());
423 dprintf("no matches (intersection list is empty)\n");
433 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
434 1e3 * duration<float>(steady_clock::now() - start).count());
436 uint64_t matched = scan_docids(needles, in1, corpus, &engine);
437 dprintf("Done in %.1f ms, found %zu matches.\n",
438 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
441 printf("%zu\n", matched);
447 // The help text comes from mlocate.
448 printf("Usage: plocate [OPTION]... PATTERN...\n");
450 printf(" -c, --count only print number of found entries\n");
451 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
452 printf(" %s)\n", dbpath);
453 printf(" -h, --help print this help\n");
454 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
455 printf(" -0, --null separate entries with NUL on output\n");
458 int main(int argc, char **argv)
460 static const struct option long_options[] = {
461 { "help", no_argument, 0, 'h' },
462 { "count", no_argument, 0, 'c' },
463 { "database", required_argument, 0, 'd' },
464 { "limit", required_argument, 0, 'l' },
465 { nullptr, required_argument, 0, 'n' },
466 { "null", no_argument, 0, '0' },
471 int option_index = 0;
472 int c = getopt_long(argc, argv, "cd:hl:n:0", long_options, &option_index);
481 dbpath = strdup(optarg);
488 limit_matches = atoll(optarg);
498 vector<string> needles;
499 for (int i = optind; i < argc; ++i) {
500 needles.push_back(argv[i]);
502 if (needles.empty()) {
503 fprintf(stderr, "plocate: no pattern to search for specified\n");
506 do_search_file(needles, dbpath);