3 #include "io_uring_engine.h"
4 #include "parse_trigrams.h"
6 #include "unique_sort.h"
12 #include <condition_variable>
31 #include <string_view>
34 #include <unordered_map>
35 #include <unordered_set>
41 using namespace std::chrono;
43 #define DEFAULT_DBPATH "/var/lib/mlocate/plocate.db"
45 const char *dbpath = DEFAULT_DBPATH;
46 bool ignore_case = false;
47 bool only_count = false;
48 bool print_nul = false;
49 bool use_debug = false;
50 bool patterns_are_regex = false;
51 bool use_extended_regex = false;
52 int64_t limit_matches = numeric_limits<int64_t>::max();
53 int64_t limit_left = numeric_limits<int64_t>::max();
55 steady_clock::time_point start;
56 ZSTD_DDict *ddict = nullptr;
58 regex_t compile_regex(const string &needle);
62 if (--limit_left > 0) {
65 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
66 1e3 * duration<float>(steady_clock::now() - start).count(), limit_matches);
68 printf("%" PRId64 "\n", limit_matches);
73 class ResultReceiver {
75 virtual ~ResultReceiver() = default;
76 virtual void print(uint64_t seq, uint64_t skip, const string msg) = 0;
79 class Serializer : public ResultReceiver {
81 ~Serializer() { assert(limit_left <= 0 || pending.empty()); }
82 void print(uint64_t seq, uint64_t skip, const string msg) override;
85 uint64_t next_seq = 0;
90 bool operator<(const Element &other) const
92 return seq > other.seq;
95 priority_queue<Element> pending;
98 void Serializer::print(uint64_t seq, uint64_t skip, const string msg)
107 if (next_seq != seq) {
108 pending.push(Element{ seq, skip, move(msg) });
114 printf("%s%c", msg.c_str(), 0);
116 printf("%s\n", msg.c_str());
122 // See if any delayed prints can now be dealt with.
123 while (!pending.empty() && pending.top().seq == next_seq) {
124 if (!pending.top().msg.empty()) {
126 printf("%s%c", pending.top().msg.c_str(), 0);
128 printf("%s\n", pending.top().msg.c_str());
132 next_seq += pending.top().skip;
141 string str; // Filled in no matter what.
142 regex_t re; // For REGEX.
145 bool matches(const Needle &needle, const char *haystack)
147 if (needle.type == Needle::STRSTR) {
148 return strstr(haystack, needle.str.c_str()) != nullptr;
149 } else if (needle.type == Needle::GLOB) {
150 int flags = ignore_case ? FNM_CASEFOLD : 0;
151 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
153 assert(needle.type == Needle::REGEX);
154 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
158 class AccessRXCache {
160 AccessRXCache(IOUringEngine *engine)
162 void check_access(const char *filename, bool allow_async, function<void(bool)> cb);
165 unordered_map<string, bool> cache;
168 function<void(bool)> cb;
170 map<string, vector<PendingStat>> pending_stats;
171 IOUringEngine *engine;
175 void AccessRXCache::check_access(const char *filename, bool allow_async, function<void(bool)> cb)
177 lock_guard<mutex> lock(mu);
178 if (engine == nullptr || !engine->get_supports_stat()) {
182 for (const char *end = strchr(filename + 1, '/'); end != nullptr; end = strchr(end + 1, '/')) {
183 string parent_path(filename, end - filename); // string_view from C++20.
184 auto cache_it = cache.find(parent_path);
185 if (cache_it != cache.end()) {
186 // Found in the cache.
187 if (!cache_it->second) {
195 bool ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
196 cache.emplace(parent_path, ok);
204 // We want to call access(), but it could block on I/O. io_uring doesn't support
205 // access(), but we can do a dummy asynchonous statx() to populate the kernel's cache,
206 // which nearly always makes the next access() instantaneous.
208 // See if there's already a pending stat that matches this,
209 // or is a subdirectory.
210 auto it = pending_stats.lower_bound(parent_path);
211 if (it != pending_stats.end() && it->first.size() >= parent_path.size() &&
212 it->first.compare(0, parent_path.size(), parent_path) == 0) {
213 it->second.emplace_back(PendingStat{ filename, move(cb) });
215 it = pending_stats.emplace(filename, vector<PendingStat>{}).first;
216 engine->submit_stat(filename, [this, it, filename{ strdup(filename) }, cb{ move(cb) }] {
217 // The stat returned, so now do the actual access() calls.
218 // All of them should be in cache, so don't fire off new statx()
219 // calls during that check.
220 check_access(filename, /*allow_async=*/false, move(cb));
223 // Call all others that waited for the same stat() to finish.
224 // They may fire off new stat() calls if needed.
225 vector<PendingStat> pending = move(it->second);
226 pending_stats.erase(it);
227 for (PendingStat &ps : pending) {
228 check_access(ps.filename.c_str(), /*allow_async=*/true, move(ps.cb));
232 return; // The rest will happen in async context.
235 // Passed all checks.
241 Corpus(int fd, IOUringEngine *engine);
243 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
244 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
245 size_t get_num_filename_blocks() const;
246 off_t offset_for_block(uint32_t docid) const
248 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
250 const Header &get_hdr() const { return hdr; }
254 IOUringEngine *const engine;
259 Corpus::Corpus(int fd, IOUringEngine *engine)
260 : fd(fd), engine(engine)
262 // Enable to test cold-cache behavior (except for access()).
264 off_t len = lseek(fd, 0, SEEK_END);
269 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
272 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
273 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
274 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
277 if (hdr.version != 0 && hdr.version != 1) {
278 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
281 if (hdr.version == 0) {
282 // These will be junk data.
283 hdr.zstd_dictionary_offset_bytes = 0;
284 hdr.zstd_dictionary_length_bytes = 0;
293 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
295 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
296 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) {
297 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
298 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
299 if (trgmptr[i].trgm == trgm) {
300 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
310 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
312 // Read the file offset from this docid and the next one.
313 // This is always allowed, since we have a sentinel block at the end.
314 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
315 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
316 off_t offset = ptr[0];
317 size_t len = ptr[1] - ptr[0];
318 engine->submit_read(fd, len, offset, cb);
322 size_t Corpus::get_num_filename_blocks() const
324 return hdr.num_docids;
327 void scan_file_block(const vector<Needle> &needles, string_view compressed,
328 AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
329 atomic<uint64_t> *matched)
331 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
332 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
333 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
338 block.resize(uncompressed_len + 1);
340 static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx(); // Reused across calls.
343 if (ddict != nullptr) {
344 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
345 compressed.size(), ddict);
347 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
350 if (ZSTD_isError(err)) {
351 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
354 block[block.size() - 1] = '\0';
356 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
357 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
360 serializer->print(local_seq, next_seq - local_seq, filename);
362 serializer->print(local_seq, next_seq - local_seq, "");
368 // We need to know the next sequence number before inserting into Serializer,
369 // so always buffer one candidate.
370 const char *pending_candidate = nullptr;
372 uint64_t local_seq = seq << 32;
373 for (const char *filename = block.data();
374 filename != block.data() + block.size();
375 filename += strlen(filename) + 1) {
377 for (const Needle &needle : needles) {
378 if (!matches(needle, filename)) {
384 if (pending_candidate != nullptr) {
385 test_candidate(pending_candidate, local_seq, local_seq + 1);
388 pending_candidate = filename;
391 if (pending_candidate == nullptr) {
392 serializer->print(seq << 32, 1ULL << 32, "");
394 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
398 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
400 Serializer docids_in_order;
401 AccessRXCache access_rx_cache(engine);
402 atomic<uint64_t> matched{0};
403 for (size_t i = 0; i < docids.size(); ++i) {
404 uint32_t docid = docids[i];
405 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
406 scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order, &matched);
413 struct WorkerThread {
416 // We use a result queue instead of synchronizing Serializer,
417 // since a lock on it becomes a huge choke point if there are
425 vector<Result> results;
428 class WorkerThreadReceiver : public ResultReceiver {
430 WorkerThreadReceiver(WorkerThread *wt) : wt(wt) {}
432 void print(uint64_t seq, uint64_t skip, const string msg) override
434 lock_guard<mutex> lock(wt->result_mu);
435 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
436 wt->results.back().skip += skip;
438 wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
446 void deliver_results(WorkerThread *wt, Serializer *serializer)
448 vector<WorkerThread::Result> results;
450 lock_guard<mutex> lock(wt->result_mu);
451 results = move(wt->results);
453 for (const WorkerThread::Result &result : results) {
454 serializer->print(result.seq, result.skip, move(result.msg));
458 // We do this sequentially, as it's faster than scattering
459 // a lot of I/O through io_uring and hoping the kernel will
460 // coalesce it plus readahead for us. Since we assume that
461 // we will primarily be CPU-bound, we'll be firing up one
462 // worker thread for each spare core (the last one will
463 // only be doing I/O). access() is still synchronous.
464 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
467 const Header &hdr = corpus.get_hdr();
468 if (hdr.zstd_dictionary_length_bytes > 0) {
470 dictionary.resize(hdr.zstd_dictionary_length_bytes);
471 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
472 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
476 AccessRXCache access_rx_cache(nullptr);
477 Serializer serializer;
478 uint32_t num_blocks = corpus.get_num_filename_blocks();
479 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
480 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
481 atomic<uint64_t> matched{0};
484 condition_variable queue_added, queue_removed;
485 deque<tuple<int, int, string>> work_queue; // Under mu.
486 bool done = false; // Under mu.
488 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
489 dprintf("Using %u worker threads for linear scan.\n", num_threads);
490 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
491 for (unsigned i = 0; i < num_threads; ++i) {
492 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
493 // regcomp() takes a lock on the regex, so each thread will need its own.
494 const vector<Needle> *use_needles = &needles;
495 vector<Needle> recompiled_needles;
496 if (i != 0 && patterns_are_regex) {
497 recompiled_needles = needles;
498 for (Needle &needle : recompiled_needles) {
499 needle.re = compile_regex(needle.str);
501 use_needles = &recompiled_needles;
504 WorkerThreadReceiver receiver(&threads[i]);
506 uint32_t io_docid, last_docid;
510 unique_lock<mutex> lock(mu);
511 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
512 if (done && work_queue.empty()) {
515 tie(io_docid, last_docid, compressed) = move(work_queue.front());
516 work_queue.pop_front();
517 queue_removed.notify_all();
520 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
521 size_t relative_offset = offsets[docid] - offsets[io_docid];
522 size_t len = offsets[docid + 1] - offsets[docid];
523 scan_file_block(*use_needles, { &compressed[relative_offset], len }, &access_rx_cache, docid, &receiver, &matched);
530 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
531 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
532 size_t io_len = offsets[last_docid] - offsets[io_docid];
533 if (compressed.size() < io_len) {
534 compressed.resize(io_len);
536 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
539 unique_lock<mutex> lock(mu);
540 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
541 work_queue.emplace_back(io_docid, last_docid, move(compressed));
542 queue_added.notify_one(); // Avoid the thundering herd.
545 // Pick up some results, so that we are sure that we won't just overload.
546 // (Seemingly, going through all of these causes slowness with many threads,
547 // but taking only one is OK.)
548 unsigned i = io_docid / 32;
549 deliver_results(&threads[i % num_threads], &serializer);
552 lock_guard<mutex> lock(mu);
554 queue_added.notify_all();
556 for (unsigned i = 0; i < num_threads; ++i) {
558 deliver_results(&threads[i], &serializer);
563 // Takes the given posting list, unions it into the parts of the trigram disjunction
564 // already read; if the list is complete, intersects with “cur_candidates”.
566 // Returns true if the search should be aborted (we are done).
567 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
569 if (td->docids.empty()) {
570 td->docids = move(decoded);
573 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
574 swap(*tmp, td->docids);
576 if (--td->remaining_trigrams_to_read > 0) {
577 // Need to wait for more.
579 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
580 td->remaining_trigrams_to_read, td->index, td->docids.size());
584 if (cur_candidates->empty()) {
586 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
587 td->index, td->docids.size());
589 *cur_candidates = move(td->docids);
592 set_intersection(cur_candidates->begin(), cur_candidates->end(),
593 td->docids.begin(), td->docids.end(),
594 back_inserter(*tmp));
595 swap(*cur_candidates, *tmp);
597 if (cur_candidates->empty()) {
598 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
599 td->index, td->docids.size());
602 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
603 td->index, td->docids.size(), cur_candidates->size());
610 void do_search_file(const vector<Needle> &needles, const char *filename)
612 int fd = open(filename, O_RDONLY);
619 if (setgid(getgid()) != 0) {
624 start = steady_clock::now();
625 if (access("/", R_OK | X_OK)) {
626 // We can't find anything, no need to bother...
630 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
631 Corpus corpus(fd, &engine);
632 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
634 vector<TrigramDisjunction> trigram_groups;
635 if (patterns_are_regex) {
636 // We could parse the regex to find trigrams that have to be there
637 // (there are actually known algorithms to deal with disjunctions
638 // and such, too), but for now, we just go brute force.
639 // Using locate with regexes is pretty niche.
641 for (const Needle &needle : needles) {
642 parse_trigrams(needle.str, ignore_case, &trigram_groups);
648 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
649 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
651 // Give them names for debugging.
652 unsigned td_index = 0;
653 for (TrigramDisjunction &td : trigram_groups) {
654 td.index = td_index++;
657 // Collect which trigrams we need to look up in the hash table.
658 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
659 for (TrigramDisjunction &td : trigram_groups) {
660 for (uint32_t trgm : td.trigram_alternatives) {
661 trigrams_to_lookup[trgm].push_back(&td);
664 if (trigrams_to_lookup.empty()) {
665 // Too short for trigram matching. Apply brute force.
666 // (We could have searched through all trigrams that matched
667 // the pattern and done a union of them, but that's a lot of
668 // work for fairly unclear gain.)
669 uint64_t matched = scan_all_docids(needles, fd, corpus);
671 printf("%" PRId64 "\n", matched);
676 // Sneak in fetching the dictionary, if present. It's not necessarily clear
677 // exactly where it would be cheapest to get it, but it needs to be present
678 // before we can decode any of the posting lists. Most likely, it's
679 // in the same filesystem block as the header anyway, so it should be
680 // present in the cache.
682 const Header &hdr = corpus.get_hdr();
683 if (hdr.zstd_dictionary_length_bytes > 0) {
684 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
685 ddict = ZSTD_createDDict(s.data(), s.size());
686 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
691 // Look them all up on disk.
692 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
693 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
694 if (trgmptr == nullptr) {
695 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
696 for (TrigramDisjunction *td : *trigram_groups) {
697 --td->remaining_trigrams_to_read;
698 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
699 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
708 for (TrigramDisjunction *td : *trigram_groups) {
709 --td->remaining_trigrams_to_read;
710 td->max_num_docids += trgmptr->num_docids;
711 td->read_trigrams.emplace_back(*trgmptr, len);
716 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
718 for (TrigramDisjunction &td : trigram_groups) {
720 td.remaining_trigrams_to_read = td.read_trigrams.size();
722 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
723 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
727 // TODO: For case-insensitive (ie. more than one alternative in each),
728 // prioritize the ones with fewer seeks?
729 sort(trigram_groups.begin(), trigram_groups.end(),
730 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
731 return a.max_num_docids < b.max_num_docids;
734 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
735 for (TrigramDisjunction &td : trigram_groups) {
736 for (uint32_t trgm : td.trigram_alternatives) {
737 uses_trigram[trgm].push_back(&td);
741 unordered_set<uint32_t> trigrams_submitted_read;
742 vector<uint32_t> cur_candidates, tmp, decoded;
744 for (TrigramDisjunction &td : trigram_groups) {
745 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
746 dprintf("%s has up to %u entries, ignoring the rest (will "
747 "weed out false positives later)\n",
748 print_td(td).c_str(), td.max_num_docids);
752 for (auto &[trgmptr, len] : td.read_trigrams) {
753 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
756 trigrams_submitted_read.insert(trgmptr.trgm);
757 // Only stay a certain amount ahead, so that we don't spend I/O
758 // on reading the latter, large posting lists. We are unlikely
759 // to need them anyway, even if they should come in first.
760 if (engine.get_waiting_reads() >= 5) {
765 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
769 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
770 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
771 size_t num = trgmptr.num_docids;
773 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
775 assert(uses_trigram.count(trgm) != 0);
776 bool was_empty = cur_candidates.empty();
778 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
781 for (TrigramDisjunction *td : uses_trigram[trgm]) {
782 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
788 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
789 } else if (cur_candidates.empty()) {
790 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
792 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
802 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
803 1e3 * duration<float>(steady_clock::now() - start).count());
805 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
806 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
807 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
810 printf("%" PRId64 "\n", matched);
814 string unescape_glob_to_plain_string(const string &needle)
817 for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
818 uint32_t ch = read_unigram(needle, i).first;
819 assert(ch != WILDCARD_UNIGRAM);
820 if (ch == PREMATURE_END_UNIGRAM) {
821 fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
824 unescaped.push_back(ch);
829 regex_t compile_regex(const string &needle)
832 int flags = REG_NOSUB;
836 if (use_extended_regex) {
837 flags |= REG_EXTENDED;
839 int err = regcomp(&re, needle.c_str(), flags);
842 regerror(err, &re, errbuf, sizeof(errbuf));
843 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
852 "Usage: plocate [OPTION]... PATTERN...\n"
854 " -c, --count print number of matches instead of the matches\n"
855 " -d, --database DBPATH search for files in DBPATH\n"
856 " (default is " DEFAULT_DBPATH ")\n"
857 " -i, --ignore-case search case-insensitively\n"
858 " -l, --limit LIMIT stop after LIMIT matches\n"
859 " -0, --null delimit matches by NUL instead of newline\n"
860 " -r, --regexp interpret patterns as basic regexps (slow)\n"
861 " --regex interpret patterns as extended regexps (slow)\n"
862 " --help print this help\n"
863 " --version print version information\n");
868 printf("plocate %s\n", PLOCATE_VERSION);
869 printf("Copyright 2020 Steinar H. Gunderson\n");
870 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
871 printf("This is free software: you are free to change and redistribute it.\n");
872 printf("There is NO WARRANTY, to the extent permitted by law.\n");
876 int main(int argc, char **argv)
878 constexpr int EXTENDED_REGEX = 1000;
879 static const struct option long_options[] = {
880 { "help", no_argument, 0, 'h' },
881 { "count", no_argument, 0, 'c' },
882 { "database", required_argument, 0, 'd' },
883 { "ignore-case", no_argument, 0, 'i' },
884 { "limit", required_argument, 0, 'l' },
885 { "null", no_argument, 0, '0' },
886 { "version", no_argument, 0, 'V' },
887 { "regexp", no_argument, 0, 'r' },
888 { "regex", no_argument, 0, EXTENDED_REGEX },
889 { "debug", no_argument, 0, 'D' }, // Not documented.
893 setlocale(LC_ALL, "");
895 int option_index = 0;
896 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
905 dbpath = strdup(optarg);
915 limit_matches = limit_left = atoll(optarg);
916 if (limit_matches <= 0) {
917 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
925 patterns_are_regex = true;
928 patterns_are_regex = true;
929 use_extended_regex = true;
943 // Debug information would leak information about which files exist,
944 // so drop setgid before we open the file; one would either need to run
945 // as root, or use a locally-built file.
946 if (setgid(getgid()) != 0) {
952 vector<Needle> needles;
953 for (int i = optind; i < argc; ++i) {
955 needle.str = argv[i];
957 // See if there are any wildcard characters, which indicates we should treat it
958 // as an (anchored) glob.
959 bool any_wildcard = false;
960 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
961 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
967 if (patterns_are_regex) {
968 needle.type = Needle::REGEX;
969 needle.re = compile_regex(needle.str);
970 } else if (any_wildcard) {
971 needle.type = Needle::GLOB;
972 } else if (ignore_case) {
973 // strcasestr() doesn't handle locales correctly (even though LSB
974 // claims it should), but somehow, fnmatch() does, and it's about
975 // the same speed as using a regex.
976 needle.type = Needle::GLOB;
977 needle.str = "*" + needle.str + "*";
979 needle.type = Needle::STRSTR;
980 needle.str = unescape_glob_to_plain_string(needle.str);
982 needles.push_back(move(needle));
984 if (needles.empty()) {
985 fprintf(stderr, "plocate: no pattern to search for specified\n");
988 do_search_file(needles, dbpath);