1 #include "access_rx_cache.h"
2 #include "complete_pread.h"
5 #include "io_uring_engine.h"
7 #include "parse_trigrams.h"
8 #include "serializer.h"
10 #include "unique_sort.h"
16 #include <condition_variable>
33 #include <string_view>
34 #include <sys/types.h>
39 #include <unordered_map>
40 #include <unordered_set>
46 using namespace std::chrono;
48 bool ignore_case = false;
49 bool only_count = false;
50 bool print_nul = false;
51 bool use_debug = false;
52 bool flush_cache = false;
53 bool patterns_are_regex = false;
54 bool use_extended_regex = false;
55 bool match_basename = false;
56 int64_t limit_matches = numeric_limits<int64_t>::max();
57 int64_t limit_left = numeric_limits<int64_t>::max();
58 bool stdout_is_tty = false;
59 static bool in_forked_child = false;
61 steady_clock::time_point start;
62 ZSTD_DDict *ddict = nullptr;
66 Corpus(int fd, IOUringEngine *engine);
68 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
69 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
70 size_t get_num_filename_blocks() const;
71 off_t offset_for_block(uint32_t docid) const
73 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
75 const Header &get_hdr() const { return hdr; }
79 IOUringEngine *const engine;
84 Corpus::Corpus(int fd, IOUringEngine *engine)
85 : fd(fd), engine(engine)
88 off_t len = lseek(fd, 0, SEEK_END);
93 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
96 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
97 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
98 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
101 if (hdr.version != 0 && hdr.version != 1) {
102 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
105 if (hdr.version == 0) {
106 // These will be junk data.
107 hdr.zstd_dictionary_offset_bytes = 0;
108 hdr.zstd_dictionary_length_bytes = 0;
110 if (hdr.max_version < 2) {
111 // This too. (We ignore the other max_version 2 fields.)
112 hdr.check_visibility = true;
121 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
123 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
124 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) {
125 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
126 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
127 if (trgmptr[i].trgm == trgm) {
128 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
138 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
140 // Read the file offset from this docid and the next one.
141 // This is always allowed, since we have a sentinel block at the end.
142 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
143 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
144 off_t offset = ptr[0];
145 size_t len = ptr[1] - ptr[0];
146 engine->submit_read(fd, len, offset, cb);
150 size_t Corpus::get_num_filename_blocks() const
152 return hdr.num_docids;
155 void scan_file_block(const vector<Needle> &needles, string_view compressed,
156 AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
157 atomic<uint64_t> *matched)
159 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
160 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
161 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
166 block.resize(uncompressed_len + 1);
168 static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx(); // Reused across calls.
171 if (ddict != nullptr) {
172 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
173 compressed.size(), ddict);
175 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
178 if (ZSTD_isError(err)) {
179 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
182 block[block.size() - 1] = '\0';
184 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
185 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
188 serializer->print(local_seq, next_seq - local_seq, filename);
190 serializer->print(local_seq, next_seq - local_seq, "");
196 // We need to know the next sequence number before inserting into Serializer,
197 // so always buffer one candidate.
198 const char *pending_candidate = nullptr;
200 uint64_t local_seq = seq << 32;
201 for (const char *filename = block.data();
202 filename != block.data() + block.size();
203 filename += strlen(filename) + 1) {
204 const char *haystack = filename;
205 if (match_basename) {
206 haystack = strrchr(filename, '/');
207 if (haystack == nullptr) {
215 for (const Needle &needle : needles) {
216 if (!matches(needle, haystack)) {
222 if (pending_candidate != nullptr) {
223 test_candidate(pending_candidate, local_seq, local_seq + 1);
226 pending_candidate = filename;
229 if (pending_candidate == nullptr) {
230 serializer->print(seq << 32, 1ULL << 32, "");
232 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
236 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
238 Serializer docids_in_order;
239 AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
240 atomic<uint64_t> matched{ 0 };
241 for (size_t i = 0; i < docids.size(); ++i) {
242 uint32_t docid = docids[i];
243 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
244 scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order, &matched);
251 struct WorkerThread {
254 // We use a result queue instead of synchronizing Serializer,
255 // since a lock on it becomes a huge choke point if there are
263 vector<Result> results;
266 class WorkerThreadReceiver : public ResultReceiver {
268 WorkerThreadReceiver(WorkerThread *wt)
271 void print(uint64_t seq, uint64_t skip, const string msg) override
273 lock_guard<mutex> lock(wt->result_mu);
274 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
275 wt->results.back().skip += skip;
277 wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
285 void deliver_results(WorkerThread *wt, Serializer *serializer)
287 vector<WorkerThread::Result> results;
289 lock_guard<mutex> lock(wt->result_mu);
290 results = move(wt->results);
292 for (const WorkerThread::Result &result : results) {
293 serializer->print(result.seq, result.skip, move(result.msg));
297 // We do this sequentially, as it's faster than scattering
298 // a lot of I/O through io_uring and hoping the kernel will
299 // coalesce it plus readahead for us. Since we assume that
300 // we will primarily be CPU-bound, we'll be firing up one
301 // worker thread for each spare core (the last one will
302 // only be doing I/O). access() is still synchronous.
303 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
306 const Header &hdr = corpus.get_hdr();
307 if (hdr.zstd_dictionary_length_bytes > 0) {
309 dictionary.resize(hdr.zstd_dictionary_length_bytes);
310 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
311 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
315 AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
316 Serializer serializer;
317 uint32_t num_blocks = corpus.get_num_filename_blocks();
318 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
319 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
320 atomic<uint64_t> matched{ 0 };
323 condition_variable queue_added, queue_removed;
324 deque<tuple<int, int, string>> work_queue; // Under mu.
325 bool done = false; // Under mu.
327 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
328 dprintf("Using %u worker threads for linear scan.\n", num_threads);
329 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
330 for (unsigned i = 0; i < num_threads; ++i) {
331 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
332 // regcomp() takes a lock on the regex, so each thread will need its own.
333 const vector<Needle> *use_needles = &needles;
334 vector<Needle> recompiled_needles;
335 if (i != 0 && patterns_are_regex) {
336 recompiled_needles = needles;
337 for (Needle &needle : recompiled_needles) {
338 needle.re = compile_regex(needle.str);
340 use_needles = &recompiled_needles;
343 WorkerThreadReceiver receiver(&threads[i]);
345 uint32_t io_docid, last_docid;
349 unique_lock<mutex> lock(mu);
350 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
351 if (done && work_queue.empty()) {
354 tie(io_docid, last_docid, compressed) = move(work_queue.front());
355 work_queue.pop_front();
356 queue_removed.notify_all();
359 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
360 size_t relative_offset = offsets[docid] - offsets[io_docid];
361 size_t len = offsets[docid + 1] - offsets[docid];
362 scan_file_block(*use_needles, { &compressed[relative_offset], len }, &access_rx_cache, docid, &receiver, &matched);
369 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
370 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
371 size_t io_len = offsets[last_docid] - offsets[io_docid];
372 if (compressed.size() < io_len) {
373 compressed.resize(io_len);
375 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
378 unique_lock<mutex> lock(mu);
379 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
380 work_queue.emplace_back(io_docid, last_docid, move(compressed));
381 queue_added.notify_one(); // Avoid the thundering herd.
384 // Pick up some results, so that we are sure that we won't just overload.
385 // (Seemingly, going through all of these causes slowness with many threads,
386 // but taking only one is OK.)
387 unsigned i = io_docid / 32;
388 deliver_results(&threads[i % num_threads], &serializer);
391 lock_guard<mutex> lock(mu);
393 queue_added.notify_all();
395 for (unsigned i = 0; i < num_threads; ++i) {
397 deliver_results(&threads[i], &serializer);
402 // Takes the given posting list, unions it into the parts of the trigram disjunction
403 // already read; if the list is complete, intersects with “cur_candidates”.
405 // Returns true if the search should be aborted (we are done).
406 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
408 if (td->docids.empty()) {
409 td->docids = move(decoded);
412 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
413 swap(*tmp, td->docids);
415 if (--td->remaining_trigrams_to_read > 0) {
416 // Need to wait for more.
418 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
419 td->remaining_trigrams_to_read, td->index, td->docids.size());
423 if (cur_candidates->empty()) {
425 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
426 td->index, td->docids.size());
428 *cur_candidates = move(td->docids);
431 set_intersection(cur_candidates->begin(), cur_candidates->end(),
432 td->docids.begin(), td->docids.end(),
433 back_inserter(*tmp));
434 swap(*cur_candidates, *tmp);
436 if (cur_candidates->empty()) {
437 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
438 td->index, td->docids.size());
441 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
442 td->index, td->docids.size(), cur_candidates->size());
449 uint64_t do_search_file(const vector<Needle> &needles, const std::string &filename)
451 int fd = open(filename.c_str(), O_RDONLY);
453 perror(filename.c_str());
458 if (setgid(getgid()) != 0) {
463 start = steady_clock::now();
464 if (access("/", R_OK | X_OK)) {
465 // We can't find anything, no need to bother...
469 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
470 Corpus corpus(fd, &engine);
471 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
473 vector<TrigramDisjunction> trigram_groups;
474 if (patterns_are_regex) {
475 // We could parse the regex to find trigrams that have to be there
476 // (there are actually known algorithms to deal with disjunctions
477 // and such, too), but for now, we just go brute force.
478 // Using locate with regexes is pretty niche.
480 for (const Needle &needle : needles) {
481 parse_trigrams(needle.str, ignore_case, &trigram_groups);
487 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
488 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
490 // Give them names for debugging.
491 unsigned td_index = 0;
492 for (TrigramDisjunction &td : trigram_groups) {
493 td.index = td_index++;
496 // Collect which trigrams we need to look up in the hash table.
497 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
498 for (TrigramDisjunction &td : trigram_groups) {
499 for (uint32_t trgm : td.trigram_alternatives) {
500 trigrams_to_lookup[trgm].push_back(&td);
503 if (trigrams_to_lookup.empty()) {
504 // Too short for trigram matching. Apply brute force.
505 // (We could have searched through all trigrams that matched
506 // the pattern and done a union of them, but that's a lot of
507 // work for fairly unclear gain.)
508 uint64_t matched = scan_all_docids(needles, fd, corpus);
509 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
510 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
514 // Sneak in fetching the dictionary, if present. It's not necessarily clear
515 // exactly where it would be cheapest to get it, but it needs to be present
516 // before we can decode any of the posting lists. Most likely, it's
517 // in the same filesystem block as the header anyway, so it should be
518 // present in the cache.
520 const Header &hdr = corpus.get_hdr();
521 if (hdr.zstd_dictionary_length_bytes > 0) {
522 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
523 ddict = ZSTD_createDDict(s.data(), s.size());
524 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
529 // Look them all up on disk.
530 bool should_early_exit = false;
531 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
532 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }, &should_early_exit](const Trigram *trgmptr, size_t len) {
533 if (trgmptr == nullptr) {
534 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
535 for (TrigramDisjunction *td : *trigram_groups) {
536 --td->remaining_trigrams_to_read;
538 // If we now know this trigram group doesn't match anything at all,
539 // we can do early exit; however, if we're in a forked child,
540 // that would confuse the parent process (since we don't write
541 // our count to the pipe), so we wait until we're back in to the
542 // regular (non-async) context. This is a fairly rare case anyway,
543 // and the gains from dropping the remaining trigram reads are limited.
544 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
545 if (in_forked_child) {
546 should_early_exit = true;
548 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
558 for (TrigramDisjunction *td : *trigram_groups) {
559 --td->remaining_trigrams_to_read;
560 td->max_num_docids += trgmptr->num_docids;
561 td->read_trigrams.emplace_back(*trgmptr, len);
566 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
568 if (should_early_exit) {
572 for (TrigramDisjunction &td : trigram_groups) {
574 td.remaining_trigrams_to_read = td.read_trigrams.size();
576 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
577 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
581 // TODO: For case-insensitive (ie. more than one alternative in each),
582 // prioritize the ones with fewer seeks?
583 sort(trigram_groups.begin(), trigram_groups.end(),
584 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
585 return a.max_num_docids < b.max_num_docids;
588 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
589 for (TrigramDisjunction &td : trigram_groups) {
590 for (uint32_t trgm : td.trigram_alternatives) {
591 uses_trigram[trgm].push_back(&td);
595 unordered_set<uint32_t> trigrams_submitted_read;
596 vector<uint32_t> cur_candidates, tmp, decoded;
598 for (TrigramDisjunction &td : trigram_groups) {
599 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
600 dprintf("%s has up to %u entries, ignoring the rest (will "
601 "weed out false positives later)\n",
602 print_td(td).c_str(), td.max_num_docids);
606 for (auto &[trgmptr, len] : td.read_trigrams) {
607 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
610 trigrams_submitted_read.insert(trgmptr.trgm);
611 // Only stay a certain amount ahead, so that we don't spend I/O
612 // on reading the latter, large posting lists. We are unlikely
613 // to need them anyway, even if they should come in first.
614 if (engine.get_waiting_reads() >= 5) {
619 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
623 uint32_t trgm = trgmptr.trgm;
624 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
625 size_t num = trgmptr.num_docids;
627 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
629 assert(uses_trigram.count(trgm) != 0);
630 bool was_empty = cur_candidates.empty();
632 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
635 for (TrigramDisjunction *td : uses_trigram[trgm]) {
636 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
642 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
643 } else if (cur_candidates.empty()) {
644 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
646 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
656 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
657 1e3 * duration<float>(steady_clock::now() - start).count());
659 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
660 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
661 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
665 // Run do_search_file() in a child process.
667 // The reason for this is that we're not robust against malicious input, so we need
668 // to drop privileges after opening the file. (Otherwise, we could fall prey to an attack
669 // where a user does locate -d badfile.db:/var/lib/plocate/plocate.db, badfile.db contains
670 // a buffer overflow that takes over the process, and then uses the elevated privileges
671 // to print out otherwise inaccessible paths.) We solve this by forking and treating the
672 // child process as untrusted after it has dropped its privileges (which it does before
673 // reading any data from the file); it returns a single 64-bit number over a pipe,
674 // and that's it. The parent keeps its privileges, and can then fork out new children
675 // without fear of being taken over. (The child keeps stdout for outputting results.)
677 // The count is returned over the pipe, because it's needed both for --limit and --count.
678 uint64_t do_search_file_in_child(const vector<Needle> &needles, const std::string &filename)
681 if (pipe(pipefd) == -1) {
686 pid_t child_pid = fork();
691 in_forked_child = true;
692 uint64_t matched = do_search_file(needles, filename);
695 ret = write(pipefd[1], &matched, sizeof(matched));
696 } while (ret == -1 && errno == EINTR);
697 if (ret != sizeof(matched)) {
713 // Wait for the child to finish.
717 err = waitpid(child_pid, &wstatus, 0);
718 } while (err == -1 && errno == EINTR);
723 if (WIFEXITED(wstatus)) {
724 if (WEXITSTATUS(wstatus) != 0) {
725 // The child has probably already printed out its error, so just propagate the exit status.
726 exit(WEXITSTATUS(wstatus));
729 } else if (!WIFEXITED(wstatus)) {
730 fprintf(stderr, "FATAL: Child died unexpectedly while processing %s\n", filename.c_str());
734 // Now get the number of matches from the child.
738 ret = read(pipefd[0], &matched, sizeof(matched));
739 } while (ret == -1 && errno == EINTR);
743 } else if (ret != sizeof(matched)) {
744 fprintf(stderr, "FATAL: Short read through pipe (got %d bytes)\n", ret);
751 // Parses a colon-separated list of strings and appends them onto the given vector.
752 // Backslash escapes whatever comes after it.
753 void parse_dbpaths(const char *ptr, vector<string> *output)
756 while (*ptr != '\0') {
758 if (ptr[1] == '\0') {
759 fprintf(stderr, "ERROR: Escape character at the end of string\n");
763 str.push_back(ptr[1]);
769 output->push_back(move(str));
773 str.push_back(*ptr++);
775 output->push_back(move(str));
781 "Usage: plocate [OPTION]... PATTERN...\n"
783 " -b, --basename search only the file name portion of path names\n"
784 " -c, --count print number of matches instead of the matches\n"
785 " -d, --database DBPATH search for files in DBPATH\n"
786 " (default is " DBFILE ")\n"
787 " -i, --ignore-case search case-insensitively\n"
788 " -l, --limit LIMIT stop after LIMIT matches\n"
789 " -0, --null delimit matches by NUL instead of newline\n"
790 " -r, --regexp interpret patterns as basic regexps (slow)\n"
791 " --regex interpret patterns as extended regexps (slow)\n"
792 " -w, --wholename search the entire path name (default; see -b)\n"
793 " --help print this help\n"
794 " --version print version information\n");
799 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
800 printf("Copyright 2020 Steinar H. Gunderson\n");
801 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
802 printf("This is free software: you are free to change and redistribute it.\n");
803 printf("There is NO WARRANTY, to the extent permitted by law.\n");
807 int main(int argc, char **argv)
809 vector<string> dbpaths;
811 constexpr int EXTENDED_REGEX = 1000;
812 constexpr int FLUSH_CACHE = 1001;
813 static const struct option long_options[] = {
814 { "help", no_argument, 0, 'h' },
815 { "count", no_argument, 0, 'c' },
816 { "basename", no_argument, 0, 'b' },
817 { "database", required_argument, 0, 'd' },
818 { "ignore-case", no_argument, 0, 'i' },
819 { "limit", required_argument, 0, 'l' },
820 { "null", no_argument, 0, '0' },
821 { "version", no_argument, 0, 'V' },
822 { "regexp", no_argument, 0, 'r' },
823 { "regex", no_argument, 0, EXTENDED_REGEX },
824 { "wholename", no_argument, 0, 'w' },
825 { "debug", no_argument, 0, 'D' }, // Not documented.
826 // Enable to test cold-cache behavior (except for access()). Not documented.
827 { "flush-cache", no_argument, 0, FLUSH_CACHE },
831 setlocale(LC_ALL, "");
833 int option_index = 0;
834 int c = getopt_long(argc, argv, "bcd:hil:n:0rwVD", long_options, &option_index);
840 match_basename = true;
846 parse_dbpaths(optarg, &dbpaths);
856 limit_matches = limit_left = atoll(optarg);
857 if (limit_matches <= 0) {
858 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
866 patterns_are_regex = true;
869 patterns_are_regex = true;
870 use_extended_regex = true;
873 match_basename = false; // No-op unless -b is given first.
889 if (use_debug || flush_cache) {
890 // Debug information would leak information about which files exist,
891 // so drop setgid before we open the file; one would either need to run
892 // as root, or use a locally-built file. Doing the same thing for
893 // flush_cache is mostly paranoia, in an attempt to prevent random users
894 // from making plocate slow for everyone else.
895 if (setgid(getgid()) != 0) {
902 stdout_is_tty = isatty(1);
905 vector<Needle> needles;
906 for (int i = optind; i < argc; ++i) {
908 needle.str = argv[i];
910 // See if there are any wildcard characters, which indicates we should treat it
911 // as an (anchored) glob.
912 bool any_wildcard = false;
913 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
914 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
920 if (patterns_are_regex) {
921 needle.type = Needle::REGEX;
922 needle.re = compile_regex(needle.str);
923 } else if (any_wildcard) {
924 needle.type = Needle::GLOB;
925 } else if (ignore_case) {
926 // strcasestr() doesn't handle locales correctly (even though LSB
927 // claims it should), but somehow, fnmatch() does, and it's about
928 // the same speed as using a regex.
929 needle.type = Needle::GLOB;
930 needle.str = "*" + needle.str + "*";
932 needle.type = Needle::STRSTR;
933 needle.str = unescape_glob_to_plain_string(needle.str);
935 needles.push_back(move(needle));
937 if (needles.empty()) {
938 fprintf(stderr, "plocate: no pattern to search for specified\n");
942 if (dbpaths.empty()) {
943 // No -d given, so use our default. Note that this happens
944 // even if LOCATE_PATH exists, to match mlocate behavior.
945 dbpaths.push_back(DBFILE);
948 const char *locate_path = getenv("LOCATE_PATH");
949 if (locate_path != nullptr) {
950 parse_dbpaths(locate_path, &dbpaths);
953 uint64_t matched = 0;
954 for (size_t i = 0; i < dbpaths.size(); ++i) {
955 uint64_t this_matched;
956 if (i != dbpaths.size() - 1) {
957 this_matched = do_search_file_in_child(needles, dbpaths[i]);
959 this_matched = do_search_file(needles, dbpaths[i]);
961 matched += this_matched;
962 limit_left -= this_matched;
965 printf("%" PRId64 "\n", matched);