2 #include "io_uring_engine.h"
18 #include <unordered_map>
23 using namespace std::chrono;
26 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
28 const char *dbpath = "/var/lib/mlocate/plocate.db";
29 bool print_nul = false;
33 bool ready_to_print(int seq) { return next_seq == seq; }
34 void print_delayed(int seq, const vector<string> msg);
35 void release_current();
43 bool operator<(const Element &other) const
45 return seq > other.seq;
48 priority_queue<Element> pending;
51 void Serializer::print_delayed(int seq, const vector<string> msg)
53 pending.push(Element{ seq, move(msg) });
56 void Serializer::release_current()
60 // See if any delayed prints can now be dealt with.
61 while (!pending.empty() && pending.top().seq == next_seq) {
62 for (const string &msg : pending.top().msg) {
64 printf("%s%c", msg.c_str(), 0);
66 printf("%s\n", msg.c_str());
74 static inline uint32_t read_unigram(const string &s, size_t idx)
77 return (unsigned char)s[idx];
83 static inline uint32_t read_trigram(const string &s, size_t start)
85 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
86 (read_unigram(s, start + 2) << 16);
89 bool has_access(const char *filename,
90 unordered_map<string, bool> *access_rx_cache)
92 const char *end = strchr(filename + 1, '/');
93 while (end != nullptr) {
94 string parent_path(filename, end);
95 auto it = access_rx_cache->find(parent_path);
97 if (it == access_rx_cache->end()) {
98 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
99 access_rx_cache->emplace(move(parent_path), ok);
106 end = strchr(end + 1, '/');
114 Corpus(int fd, IOUringEngine *engine);
116 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
117 void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
118 size_t get_num_filename_blocks() const;
119 off_t offset_for_block(uint32_t docid) const
121 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
126 IOUringEngine *const engine;
131 Corpus::Corpus(int fd, IOUringEngine *engine)
132 : fd(fd), engine(engine)
134 // Enable to test cold-cache behavior (except for access()).
136 off_t len = lseek(fd, 0, SEEK_END);
141 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
144 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
145 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
146 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
149 if (hdr.version != 0) {
150 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
160 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
162 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
163 engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, bucket, cb{ move(cb) }](string s) {
164 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
165 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
166 if (trgmptr[i].trgm == trgm) {
167 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
177 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
179 // Read the file offset from this docid and the next one.
180 // This is always allowed, since we have a sentinel block at the end.
181 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
182 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
183 off_t offset = ptr[0];
184 size_t len = ptr[1] - ptr[0];
185 engine->submit_read(fd, len, offset, cb);
189 size_t Corpus::get_num_filename_blocks() const
191 // The beginning of the filename blocks is the end of the filename index blocks.
193 complete_pread(fd, &end, sizeof(end), hdr.filename_index_offset_bytes);
195 // Subtract the sentinel block.
196 return (end - hdr.filename_index_offset_bytes) / sizeof(uint64_t) - 1;
199 size_t scan_file_block(const vector<string> &needles, string_view compressed,
200 unordered_map<string, bool> *access_rx_cache, int seq,
201 Serializer *serializer)
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)) {
237 if (immediate_print) {
239 printf("%s%c", filename, 0);
241 printf("%s\n", filename);
244 delayed.push_back(filename);
248 if (serializer != nullptr) {
249 if (immediate_print) {
250 serializer->release_current();
252 serializer->print_delayed(seq, move(delayed));
258 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
260 Serializer docids_in_order;
261 unordered_map<string, bool> access_rx_cache;
263 for (size_t i = 0; i < docids.size(); ++i) {
264 uint32_t docid = docids[i];
265 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
266 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
273 // We do this sequentially, as it's faster than scattering
274 // a lot of I/O through io_uring and hoping the kernel will
275 // coalesce it plus readahead for us.
276 void scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
278 unordered_map<string, bool> access_rx_cache;
279 uint32_t num_blocks = corpus.get_num_filename_blocks();
280 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
281 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
283 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
284 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
285 size_t io_len = offsets[last_docid] - offsets[io_docid];
286 if (compressed.size() < io_len) {
287 compressed.resize(io_len);
289 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
291 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
292 size_t relative_offset = offsets[docid] - offsets[io_docid];
293 size_t len = offsets[docid + 1] - offsets[docid];
294 scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
299 void do_search_file(const vector<string> &needles, const char *filename)
301 int fd = open(filename, O_RDONLY);
308 if (setgid(getgid()) != 0) {
313 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
314 if (access("/", R_OK | X_OK)) {
315 // We can't find anything, no need to bother...
319 IOUringEngine engine;
320 Corpus corpus(fd, &engine);
321 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
323 vector<pair<Trigram, size_t>> trigrams;
324 for (const string &needle : needles) {
325 if (needle.size() < 3)
327 for (size_t i = 0; i < needle.size() - 2; ++i) {
328 uint32_t trgm = read_trigram(needle, i);
329 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
330 if (trgmptr == nullptr) {
331 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
334 trigrams.emplace_back(*trgmptr, len);
339 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
341 if (trigrams.empty()) {
342 // Too short for trigram matching. Apply brute force.
343 // (We could have searched through all trigrams that matched
344 // the pattern and done a union of them, but that's a lot of
345 // work for fairly unclear gain.)
346 scan_all_docids(needles, fd, corpus, &engine);
349 sort(trigrams.begin(), trigrams.end());
351 auto last = unique(trigrams.begin(), trigrams.end());
352 trigrams.erase(last, trigrams.end());
354 sort(trigrams.begin(), trigrams.end(),
355 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
356 return a.first.num_docids < b.first.num_docids;
359 vector<uint32_t> in1, in2, out;
361 for (auto [trgmptr, len] : trigrams) {
362 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
363 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
364 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
365 "weed out false positives later)\n",
366 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
367 len, trgmptr.num_docids);
371 // Only stay a certain amount ahead, so that we don't spend I/O
372 // on reading the latter, large posting lists. We are unlikely
373 // to need them anyway, even if they should come in first.
374 if (engine.get_waiting_reads() >= 5) {
379 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
382 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
383 size_t num = trgmptr.num_docids;
384 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
386 in1.resize(num + 128);
387 p4nd1dec128v32(pldata, num, &in1[0]);
389 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
390 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
392 if (in2.size() < num + 128) {
393 in2.resize(num + 128);
395 p4nd1dec128v32(pldata, num, &in2[0]);
398 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
401 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
402 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
403 len, num, in1.size());
405 dprintf("no matches (intersection list is empty)\n");
415 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
416 1e3 * duration<float>(steady_clock::now() - start).count());
418 size_t matched __attribute__((unused)) = scan_docids(needles, in1, corpus, &engine);
419 dprintf("Done in %.1f ms, found %zu matches.\n",
420 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
425 // The help text comes from mlocate.
426 printf("Usage: plocate [OPTION]... PATTERN...\n");
427 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
428 printf(" %s)\n", dbpath);
429 printf(" -h, --help print this help\n");
430 printf(" -0, --null separate entries with NUL on output\n");
433 int main(int argc, char **argv)
435 static const struct option long_options[] = {
436 { "help", no_argument, 0, 'h' },
437 { "database", required_argument, 0, 'd' },
438 { "null", no_argument, 0, '0' },
443 int option_index = 0;
444 int c = getopt_long(argc, argv, "d:h0", long_options, &option_index);
450 dbpath = strdup(optarg);
463 vector<string> needles;
464 for (int i = optind; i < argc; ++i) {
465 needles.push_back(argv[i]);
467 if (needles.empty()) {
468 fprintf(stderr, "plocate: no pattern to search for specified\n");
471 do_search_file(needles, dbpath);