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
420 vector<tuple<uint64_t, uint64_t, string>> results;
423 class WorkerThreadReceiver : public ResultReceiver {
425 WorkerThreadReceiver(WorkerThread *wt) : wt(wt) {}
427 void print(uint64_t seq, uint64_t skip, const string msg) override
429 lock_guard<mutex> lock(wt->result_mu);
430 wt->results.emplace_back(seq, skip, move(msg));
437 void deliver_results(WorkerThread *wt, Serializer *serializer)
439 vector<tuple<uint64_t, uint64_t, string>> results;
441 lock_guard<mutex> lock(wt->result_mu);
442 results = move(wt->results);
444 for (const auto &result : results) {
445 serializer->print(get<0>(result), get<1>(result), move(get<2>(result)));
449 // We do this sequentially, as it's faster than scattering
450 // a lot of I/O through io_uring and hoping the kernel will
451 // coalesce it plus readahead for us. Since we assume that
452 // we will primarily be CPU-bound, we'll be firing up one
453 // worker thread for each spare core (the last one will
454 // only be doing I/O). access() is still synchronous.
455 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
458 const Header &hdr = corpus.get_hdr();
459 if (hdr.zstd_dictionary_length_bytes > 0) {
461 dictionary.resize(hdr.zstd_dictionary_length_bytes);
462 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
463 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
467 AccessRXCache access_rx_cache(nullptr);
468 Serializer serializer;
469 uint32_t num_blocks = corpus.get_num_filename_blocks();
470 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
471 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
472 atomic<uint64_t> matched{0};
475 condition_variable queue_added, queue_removed;
476 deque<tuple<int, int, string>> work_queue; // Under mu.
477 bool done = false; // Under mu.
479 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
480 dprintf("Using %u worker threads for linear scan.\n", num_threads);
481 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
482 for (unsigned i = 0; i < num_threads; ++i) {
483 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
484 // regcomp() takes a lock on the regex, so each thread will need its own.
485 const vector<Needle> *use_needles = &needles;
486 vector<Needle> recompiled_needles;
487 if (i != 0 && patterns_are_regex) {
488 recompiled_needles = needles;
489 for (Needle &needle : recompiled_needles) {
490 needle.re = compile_regex(needle.str);
492 use_needles = &recompiled_needles;
495 WorkerThreadReceiver receiver(&threads[i]);
497 uint32_t io_docid, last_docid;
501 unique_lock<mutex> lock(mu);
502 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
503 if (done && work_queue.empty()) {
506 tie(io_docid, last_docid, compressed) = move(work_queue.front());
507 work_queue.pop_front();
508 queue_removed.notify_all();
511 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
512 size_t relative_offset = offsets[docid] - offsets[io_docid];
513 size_t len = offsets[docid + 1] - offsets[docid];
514 scan_file_block(*use_needles, { &compressed[relative_offset], len }, &access_rx_cache, docid, &receiver, &matched);
521 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
522 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
523 size_t io_len = offsets[last_docid] - offsets[io_docid];
524 if (compressed.size() < io_len) {
525 compressed.resize(io_len);
527 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
530 unique_lock<mutex> lock(mu);
531 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
532 work_queue.emplace_back(io_docid, last_docid, move(compressed));
533 queue_added.notify_one(); // Avoid the thundering herd.
536 // Pick up some results, so that we are sure that we won't just overload.
537 // (Seemingly, going through all of these causes slowness with many threads,
538 // but taking only one is OK.)
539 unsigned i = io_docid / 32;
540 deliver_results(&threads[i % num_threads], &serializer);
543 lock_guard<mutex> lock(mu);
545 queue_added.notify_all();
547 for (unsigned i = 0; i < num_threads; ++i) {
549 deliver_results(&threads[i], &serializer);
554 // Takes the given posting list, unions it into the parts of the trigram disjunction
555 // already read; if the list is complete, intersects with “cur_candidates”.
557 // Returns true if the search should be aborted (we are done).
558 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
560 if (td->docids.empty()) {
561 td->docids = move(decoded);
564 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
565 swap(*tmp, td->docids);
567 if (--td->remaining_trigrams_to_read > 0) {
568 // Need to wait for more.
570 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
571 td->remaining_trigrams_to_read, td->index, td->docids.size());
575 if (cur_candidates->empty()) {
577 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
578 td->index, td->docids.size());
580 *cur_candidates = move(td->docids);
583 set_intersection(cur_candidates->begin(), cur_candidates->end(),
584 td->docids.begin(), td->docids.end(),
585 back_inserter(*tmp));
586 swap(*cur_candidates, *tmp);
588 if (cur_candidates->empty()) {
589 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
590 td->index, td->docids.size());
593 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
594 td->index, td->docids.size(), cur_candidates->size());
601 void do_search_file(const vector<Needle> &needles, const char *filename)
603 int fd = open(filename, O_RDONLY);
610 if (setgid(getgid()) != 0) {
615 start = steady_clock::now();
616 if (access("/", R_OK | X_OK)) {
617 // We can't find anything, no need to bother...
621 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
622 Corpus corpus(fd, &engine);
623 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
625 vector<TrigramDisjunction> trigram_groups;
626 if (patterns_are_regex) {
627 // We could parse the regex to find trigrams that have to be there
628 // (there are actually known algorithms to deal with disjunctions
629 // and such, too), but for now, we just go brute force.
630 // Using locate with regexes is pretty niche.
632 for (const Needle &needle : needles) {
633 parse_trigrams(needle.str, ignore_case, &trigram_groups);
639 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
640 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
642 // Give them names for debugging.
643 unsigned td_index = 0;
644 for (TrigramDisjunction &td : trigram_groups) {
645 td.index = td_index++;
648 // Collect which trigrams we need to look up in the hash table.
649 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
650 for (TrigramDisjunction &td : trigram_groups) {
651 for (uint32_t trgm : td.trigram_alternatives) {
652 trigrams_to_lookup[trgm].push_back(&td);
655 if (trigrams_to_lookup.empty()) {
656 // Too short for trigram matching. Apply brute force.
657 // (We could have searched through all trigrams that matched
658 // the pattern and done a union of them, but that's a lot of
659 // work for fairly unclear gain.)
660 uint64_t matched = scan_all_docids(needles, fd, corpus);
662 printf("%" PRId64 "\n", matched);
667 // Sneak in fetching the dictionary, if present. It's not necessarily clear
668 // exactly where it would be cheapest to get it, but it needs to be present
669 // before we can decode any of the posting lists. Most likely, it's
670 // in the same filesystem block as the header anyway, so it should be
671 // present in the cache.
673 const Header &hdr = corpus.get_hdr();
674 if (hdr.zstd_dictionary_length_bytes > 0) {
675 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
676 ddict = ZSTD_createDDict(s.data(), s.size());
677 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
682 // Look them all up on disk.
683 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
684 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
685 if (trgmptr == nullptr) {
686 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
687 for (TrigramDisjunction *td : *trigram_groups) {
688 --td->remaining_trigrams_to_read;
689 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
690 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
699 for (TrigramDisjunction *td : *trigram_groups) {
700 --td->remaining_trigrams_to_read;
701 td->max_num_docids += trgmptr->num_docids;
702 td->read_trigrams.emplace_back(*trgmptr, len);
707 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
709 for (TrigramDisjunction &td : trigram_groups) {
711 td.remaining_trigrams_to_read = td.read_trigrams.size();
713 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
714 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
718 // TODO: For case-insensitive (ie. more than one alternative in each),
719 // prioritize the ones with fewer seeks?
720 sort(trigram_groups.begin(), trigram_groups.end(),
721 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
722 return a.max_num_docids < b.max_num_docids;
725 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
726 for (TrigramDisjunction &td : trigram_groups) {
727 for (uint32_t trgm : td.trigram_alternatives) {
728 uses_trigram[trgm].push_back(&td);
732 unordered_set<uint32_t> trigrams_submitted_read;
733 vector<uint32_t> cur_candidates, tmp, decoded;
735 for (TrigramDisjunction &td : trigram_groups) {
736 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
737 dprintf("%s has up to %u entries, ignoring the rest (will "
738 "weed out false positives later)\n",
739 print_td(td).c_str(), td.max_num_docids);
743 for (auto &[trgmptr, len] : td.read_trigrams) {
744 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
747 trigrams_submitted_read.insert(trgmptr.trgm);
748 // Only stay a certain amount ahead, so that we don't spend I/O
749 // on reading the latter, large posting lists. We are unlikely
750 // to need them anyway, even if they should come in first.
751 if (engine.get_waiting_reads() >= 5) {
756 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
760 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
761 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
762 size_t num = trgmptr.num_docids;
764 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
766 assert(uses_trigram.count(trgm) != 0);
767 bool was_empty = cur_candidates.empty();
769 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
772 for (TrigramDisjunction *td : uses_trigram[trgm]) {
773 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
779 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
780 } else if (cur_candidates.empty()) {
781 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
783 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
793 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
794 1e3 * duration<float>(steady_clock::now() - start).count());
796 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
797 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
798 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
801 printf("%" PRId64 "\n", matched);
805 string unescape_glob_to_plain_string(const string &needle)
808 for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
809 uint32_t ch = read_unigram(needle, i).first;
810 assert(ch != WILDCARD_UNIGRAM);
811 if (ch == PREMATURE_END_UNIGRAM) {
812 fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
815 unescaped.push_back(ch);
820 regex_t compile_regex(const string &needle)
823 int flags = REG_NOSUB;
827 if (use_extended_regex) {
828 flags |= REG_EXTENDED;
830 int err = regcomp(&re, needle.c_str(), flags);
833 regerror(err, &re, errbuf, sizeof(errbuf));
834 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
843 "Usage: plocate [OPTION]... PATTERN...\n"
845 " -c, --count print number of matches instead of the matches\n"
846 " -d, --database DBPATH search for files in DBPATH\n"
847 " (default is " DEFAULT_DBPATH ")\n"
848 " -i, --ignore-case search case-insensitively\n"
849 " -l, --limit LIMIT stop after LIMIT matches\n"
850 " -0, --null delimit matches by NUL instead of newline\n"
851 " -r, --regexp interpret patterns as basic regexps (slow)\n"
852 " --regex interpret patterns as extended regexps (slow)\n"
853 " --help print this help\n"
854 " --version print version information\n");
859 printf("plocate %s\n", PLOCATE_VERSION);
860 printf("Copyright 2020 Steinar H. Gunderson\n");
861 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
862 printf("This is free software: you are free to change and redistribute it.\n");
863 printf("There is NO WARRANTY, to the extent permitted by law.\n");
867 int main(int argc, char **argv)
869 constexpr int EXTENDED_REGEX = 1000;
870 static const struct option long_options[] = {
871 { "help", no_argument, 0, 'h' },
872 { "count", no_argument, 0, 'c' },
873 { "database", required_argument, 0, 'd' },
874 { "ignore-case", no_argument, 0, 'i' },
875 { "limit", required_argument, 0, 'l' },
876 { "null", no_argument, 0, '0' },
877 { "version", no_argument, 0, 'V' },
878 { "regexp", no_argument, 0, 'r' },
879 { "regex", no_argument, 0, EXTENDED_REGEX },
880 { "debug", no_argument, 0, 'D' }, // Not documented.
884 setlocale(LC_ALL, "");
886 int option_index = 0;
887 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
896 dbpath = strdup(optarg);
906 limit_matches = limit_left = atoll(optarg);
907 if (limit_matches <= 0) {
908 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
916 patterns_are_regex = true;
919 patterns_are_regex = true;
920 use_extended_regex = true;
934 // Debug information would leak information about which files exist,
935 // so drop setgid before we open the file; one would either need to run
936 // as root, or use a locally-built file.
937 if (setgid(getgid()) != 0) {
943 vector<Needle> needles;
944 for (int i = optind; i < argc; ++i) {
946 needle.str = argv[i];
948 // See if there are any wildcard characters, which indicates we should treat it
949 // as an (anchored) glob.
950 bool any_wildcard = false;
951 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
952 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
958 if (patterns_are_regex) {
959 needle.type = Needle::REGEX;
960 needle.re = compile_regex(needle.str);
961 } else if (any_wildcard) {
962 needle.type = Needle::GLOB;
963 } else if (ignore_case) {
964 // strcasestr() doesn't handle locales correctly (even though LSB
965 // claims it should), but somehow, fnmatch() does, and it's about
966 // the same speed as using a regex.
967 needle.type = Needle::GLOB;
968 needle.str = "*" + needle.str + "*";
970 needle.type = Needle::STRSTR;
971 needle.str = unescape_glob_to_plain_string(needle.str);
973 needles.push_back(move(needle));
975 if (needles.empty()) {
976 fprintf(stderr, "plocate: no pattern to search for specified\n");
979 do_search_file(needles, dbpath);