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>
35 #include <sys/types.h>
40 #include <unordered_map>
41 #include <unordered_set>
47 using namespace std::chrono;
49 bool ignore_case = false;
50 bool only_count = false;
51 bool print_nul = false;
52 bool use_debug = false;
53 bool flush_cache = false;
54 bool patterns_are_regex = false;
55 bool use_extended_regex = false;
56 bool match_basename = false;
57 bool check_existence = false;
58 int64_t limit_matches = numeric_limits<int64_t>::max();
59 int64_t limit_left = numeric_limits<int64_t>::max();
60 bool stdout_is_tty = false;
61 static bool in_forked_child = false;
63 steady_clock::time_point start;
64 ZSTD_DDict *ddict = nullptr;
68 Corpus(int fd, IOUringEngine *engine);
70 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
71 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
72 size_t get_num_filename_blocks() const;
73 off_t offset_for_block(uint32_t docid) const
75 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
77 const Header &get_hdr() const { return hdr; }
81 IOUringEngine *const engine;
86 Corpus::Corpus(int fd, IOUringEngine *engine)
87 : fd(fd), engine(engine)
90 off_t len = lseek(fd, 0, SEEK_END);
95 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
98 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
99 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
100 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
103 if (hdr.version != 0 && hdr.version != 1) {
104 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
107 if (hdr.version == 0) {
108 // These will be junk data.
109 hdr.zstd_dictionary_offset_bytes = 0;
110 hdr.zstd_dictionary_length_bytes = 0;
112 if (hdr.max_version < 2) {
113 // This too. (We ignore the other max_version 2 fields.)
114 hdr.check_visibility = true;
123 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
125 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
126 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) {
127 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
128 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
129 if (trgmptr[i].trgm == trgm) {
130 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
140 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
142 // Read the file offset from this docid and the next one.
143 // This is always allowed, since we have a sentinel block at the end.
144 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
145 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
146 off_t offset = ptr[0];
147 size_t len = ptr[1] - ptr[0];
148 engine->submit_read(fd, len, offset, cb);
152 size_t Corpus::get_num_filename_blocks() const
154 return hdr.num_docids;
158 void stat_if_needed(const char *filename, bool access_ok, IOUringEngine *engine, T cb)
160 if (!access_ok || !check_existence) {
161 // Doesn't have access or doesn't care about existence, so no need to stat.
163 } else if (engine == nullptr || !engine->get_supports_stat()) {
164 // Do a synchronous stat.
166 bool ok = lstat(filename, &buf) == 0;
169 engine->submit_stat(filename, cb);
173 void scan_file_block(const vector<Needle> &needles, string_view compressed,
174 IOUringEngine *engine, AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
175 atomic<uint64_t> *matched)
177 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
178 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
179 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
184 block.resize(uncompressed_len + 1);
186 static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx(); // Reused across calls.
189 if (ddict != nullptr) {
190 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
191 compressed.size(), ddict);
193 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
196 if (ZSTD_isError(err)) {
197 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
200 block[block.size() - 1] = '\0';
202 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
203 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, engine, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
204 stat_if_needed(filename, ok, engine, [matched, serializer, local_seq, next_seq, filename](bool ok) {
207 serializer->print(local_seq, next_seq - local_seq, filename);
209 serializer->print(local_seq, next_seq - local_seq, "");
216 // We need to know the next sequence number before inserting into Serializer,
217 // so always buffer one candidate.
218 const char *pending_candidate = nullptr;
220 uint64_t local_seq = seq << 32;
221 for (const char *filename = block.data();
222 filename != block.data() + block.size();
223 filename += strlen(filename) + 1) {
224 const char *haystack = filename;
225 if (match_basename) {
226 haystack = strrchr(filename, '/');
227 if (haystack == nullptr) {
235 for (const Needle &needle : needles) {
236 if (!matches(needle, haystack)) {
242 if (pending_candidate != nullptr) {
243 test_candidate(pending_candidate, local_seq, local_seq + 1);
246 pending_candidate = filename;
249 if (pending_candidate == nullptr) {
250 serializer->print(seq << 32, 1ULL << 32, "");
252 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
256 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
258 Serializer docids_in_order;
259 AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
260 atomic<uint64_t> matched{ 0 };
261 for (size_t i = 0; i < docids.size(); ++i) {
262 uint32_t docid = docids[i];
263 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, engine, &docids_in_order](string_view compressed) {
264 scan_file_block(needles, compressed, engine, &access_rx_cache, i, &docids_in_order, &matched);
271 struct WorkerThread {
274 // We use a result queue instead of synchronizing Serializer,
275 // since a lock on it becomes a huge choke point if there are
283 vector<Result> results;
286 class WorkerThreadReceiver : public ResultReceiver {
288 WorkerThreadReceiver(WorkerThread *wt)
291 void print(uint64_t seq, uint64_t skip, const string msg) override
293 lock_guard<mutex> lock(wt->result_mu);
294 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
295 wt->results.back().skip += skip;
297 wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
305 void deliver_results(WorkerThread *wt, Serializer *serializer)
307 vector<WorkerThread::Result> results;
309 lock_guard<mutex> lock(wt->result_mu);
310 results = move(wt->results);
312 for (const WorkerThread::Result &result : results) {
313 serializer->print(result.seq, result.skip, move(result.msg));
317 // We do this sequentially, as it's faster than scattering
318 // a lot of I/O through io_uring and hoping the kernel will
319 // coalesce it plus readahead for us. Since we assume that
320 // we will primarily be CPU-bound, we'll be firing up one
321 // worker thread for each spare core (the last one will
322 // only be doing I/O). access() is still synchronous.
323 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
326 const Header &hdr = corpus.get_hdr();
327 if (hdr.zstd_dictionary_length_bytes > 0) {
329 dictionary.resize(hdr.zstd_dictionary_length_bytes);
330 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
331 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
335 AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
336 Serializer serializer;
337 uint32_t num_blocks = corpus.get_num_filename_blocks();
338 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
339 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
340 atomic<uint64_t> matched{ 0 };
343 condition_variable queue_added, queue_removed;
344 deque<tuple<int, int, string>> work_queue; // Under mu.
345 bool done = false; // Under mu.
347 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
348 dprintf("Using %u worker threads for linear scan.\n", num_threads);
349 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
350 for (unsigned i = 0; i < num_threads; ++i) {
351 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
352 // regcomp() takes a lock on the regex, so each thread will need its own.
353 const vector<Needle> *use_needles = &needles;
354 vector<Needle> recompiled_needles;
355 if (i != 0 && patterns_are_regex) {
356 recompiled_needles = needles;
357 for (Needle &needle : recompiled_needles) {
358 needle.re = compile_regex(needle.str);
360 use_needles = &recompiled_needles;
363 WorkerThreadReceiver receiver(&threads[i]);
365 uint32_t io_docid, last_docid;
369 unique_lock<mutex> lock(mu);
370 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
371 if (done && work_queue.empty()) {
374 tie(io_docid, last_docid, compressed) = move(work_queue.front());
375 work_queue.pop_front();
376 queue_removed.notify_all();
379 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
380 size_t relative_offset = offsets[docid] - offsets[io_docid];
381 size_t len = offsets[docid + 1] - offsets[docid];
382 // IOUringEngine isn't thread-safe, so we do any needed stat()s synchronously (nullptr engine).
383 scan_file_block(*use_needles, { &compressed[relative_offset], len }, /*engine=*/nullptr, &access_rx_cache, docid, &receiver, &matched);
390 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
391 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
392 size_t io_len = offsets[last_docid] - offsets[io_docid];
393 if (compressed.size() < io_len) {
394 compressed.resize(io_len);
396 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
399 unique_lock<mutex> lock(mu);
400 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
401 work_queue.emplace_back(io_docid, last_docid, move(compressed));
402 queue_added.notify_one(); // Avoid the thundering herd.
405 // Pick up some results, so that we are sure that we won't just overload.
406 // (Seemingly, going through all of these causes slowness with many threads,
407 // but taking only one is OK.)
408 unsigned i = io_docid / 32;
409 deliver_results(&threads[i % num_threads], &serializer);
412 lock_guard<mutex> lock(mu);
414 queue_added.notify_all();
416 for (unsigned i = 0; i < num_threads; ++i) {
418 deliver_results(&threads[i], &serializer);
423 // Takes the given posting list, unions it into the parts of the trigram disjunction
424 // already read; if the list is complete, intersects with “cur_candidates”.
426 // Returns true if the search should be aborted (we are done).
427 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
429 if (td->docids.empty()) {
430 td->docids = move(decoded);
433 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
434 swap(*tmp, td->docids);
436 if (--td->remaining_trigrams_to_read > 0) {
437 // Need to wait for more.
439 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
440 td->remaining_trigrams_to_read, td->index, td->docids.size());
444 if (cur_candidates->empty()) {
446 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
447 td->index, td->docids.size());
449 *cur_candidates = move(td->docids);
452 set_intersection(cur_candidates->begin(), cur_candidates->end(),
453 td->docids.begin(), td->docids.end(),
454 back_inserter(*tmp));
455 swap(*cur_candidates, *tmp);
457 if (cur_candidates->empty()) {
458 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
459 td->index, td->docids.size());
462 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
463 td->index, td->docids.size(), cur_candidates->size());
470 uint64_t do_search_file(const vector<Needle> &needles, const std::string &filename)
472 int fd = open(filename.c_str(), O_RDONLY);
474 perror(filename.c_str());
479 if (setgid(getgid()) != 0) {
484 start = steady_clock::now();
485 if (access("/", R_OK | X_OK)) {
486 // We can't find anything, no need to bother...
490 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
491 Corpus corpus(fd, &engine);
492 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
494 vector<TrigramDisjunction> trigram_groups;
495 if (patterns_are_regex) {
496 // We could parse the regex to find trigrams that have to be there
497 // (there are actually known algorithms to deal with disjunctions
498 // and such, too), but for now, we just go brute force.
499 // Using locate with regexes is pretty niche.
501 for (const Needle &needle : needles) {
502 parse_trigrams(needle.str, ignore_case, &trigram_groups);
508 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
509 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
511 // Give them names for debugging.
512 unsigned td_index = 0;
513 for (TrigramDisjunction &td : trigram_groups) {
514 td.index = td_index++;
517 // Collect which trigrams we need to look up in the hash table.
518 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
519 for (TrigramDisjunction &td : trigram_groups) {
520 for (uint32_t trgm : td.trigram_alternatives) {
521 trigrams_to_lookup[trgm].push_back(&td);
524 if (trigrams_to_lookup.empty()) {
525 // Too short for trigram matching. Apply brute force.
526 // (We could have searched through all trigrams that matched
527 // the pattern and done a union of them, but that's a lot of
528 // work for fairly unclear gain.)
529 uint64_t matched = scan_all_docids(needles, fd, corpus);
530 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
531 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
535 // Sneak in fetching the dictionary, if present. It's not necessarily clear
536 // exactly where it would be cheapest to get it, but it needs to be present
537 // before we can decode any of the posting lists. Most likely, it's
538 // in the same filesystem block as the header anyway, so it should be
539 // present in the cache.
541 const Header &hdr = corpus.get_hdr();
542 if (hdr.zstd_dictionary_length_bytes > 0) {
543 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
544 ddict = ZSTD_createDDict(s.data(), s.size());
545 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
550 // Look them all up on disk.
551 bool should_early_exit = false;
552 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
553 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }, &should_early_exit](const Trigram *trgmptr, size_t len) {
554 if (trgmptr == nullptr) {
555 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
556 for (TrigramDisjunction *td : *trigram_groups) {
557 --td->remaining_trigrams_to_read;
559 // If we now know this trigram group doesn't match anything at all,
560 // we can do early exit; however, if we're in a forked child,
561 // that would confuse the parent process (since we don't write
562 // our count to the pipe), so we wait until we're back in to the
563 // regular (non-async) context. This is a fairly rare case anyway,
564 // and the gains from dropping the remaining trigram reads are limited.
565 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
566 if (in_forked_child) {
567 should_early_exit = true;
569 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
579 for (TrigramDisjunction *td : *trigram_groups) {
580 --td->remaining_trigrams_to_read;
581 td->max_num_docids += trgmptr->num_docids;
582 td->read_trigrams.emplace_back(*trgmptr, len);
587 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
589 if (should_early_exit) {
593 for (TrigramDisjunction &td : trigram_groups) {
595 td.remaining_trigrams_to_read = td.read_trigrams.size();
597 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
598 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
602 // TODO: For case-insensitive (ie. more than one alternative in each),
603 // prioritize the ones with fewer seeks?
604 sort(trigram_groups.begin(), trigram_groups.end(),
605 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
606 return a.max_num_docids < b.max_num_docids;
609 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
610 for (TrigramDisjunction &td : trigram_groups) {
611 for (uint32_t trgm : td.trigram_alternatives) {
612 uses_trigram[trgm].push_back(&td);
616 unordered_set<uint32_t> trigrams_submitted_read;
617 vector<uint32_t> cur_candidates, tmp, decoded;
619 for (TrigramDisjunction &td : trigram_groups) {
620 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
621 dprintf("%s has up to %u entries, ignoring the rest (will "
622 "weed out false positives later)\n",
623 print_td(td).c_str(), td.max_num_docids);
627 for (auto &[trgmptr, len] : td.read_trigrams) {
628 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
631 trigrams_submitted_read.insert(trgmptr.trgm);
632 // Only stay a certain amount ahead, so that we don't spend I/O
633 // on reading the latter, large posting lists. We are unlikely
634 // to need them anyway, even if they should come in first.
635 if (engine.get_waiting_reads() >= 5) {
640 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
644 uint32_t trgm = trgmptr.trgm;
645 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
646 size_t num = trgmptr.num_docids;
648 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
650 assert(uses_trigram.count(trgm) != 0);
651 bool was_empty = cur_candidates.empty();
653 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
656 for (TrigramDisjunction *td : uses_trigram[trgm]) {
657 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
663 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
664 } else if (cur_candidates.empty()) {
665 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
667 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
677 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
678 1e3 * duration<float>(steady_clock::now() - start).count());
680 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
681 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
682 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
686 // Run do_search_file() in a child process.
688 // The reason for this is that we're not robust against malicious input, so we need
689 // to drop privileges after opening the file. (Otherwise, we could fall prey to an attack
690 // where a user does locate -d badfile.db:/var/lib/plocate/plocate.db, badfile.db contains
691 // a buffer overflow that takes over the process, and then uses the elevated privileges
692 // to print out otherwise inaccessible paths.) We solve this by forking and treating the
693 // child process as untrusted after it has dropped its privileges (which it does before
694 // reading any data from the file); it returns a single 64-bit number over a pipe,
695 // and that's it. The parent keeps its privileges, and can then fork out new children
696 // without fear of being taken over. (The child keeps stdout for outputting results.)
698 // The count is returned over the pipe, because it's needed both for --limit and --count.
699 uint64_t do_search_file_in_child(const vector<Needle> &needles, const std::string &filename)
702 if (pipe(pipefd) == -1) {
707 pid_t child_pid = fork();
712 in_forked_child = true;
713 uint64_t matched = do_search_file(needles, filename);
716 ret = write(pipefd[1], &matched, sizeof(matched));
717 } while (ret == -1 && errno == EINTR);
718 if (ret != sizeof(matched)) {
735 // Wait for the child to finish.
739 err = waitpid(child_pid, &wstatus, 0);
740 } while (err == -1 && errno == EINTR);
745 if (WIFEXITED(wstatus)) {
746 if (WEXITSTATUS(wstatus) != 0) {
747 // The child has probably already printed out its error, so just propagate the exit status.
748 exit(WEXITSTATUS(wstatus));
751 } else if (!WIFEXITED(wstatus)) {
752 fprintf(stderr, "FATAL: Child died unexpectedly while processing %s\n", filename.c_str());
756 // Now get the number of matches from the child.
760 ret = read(pipefd[0], &matched, sizeof(matched));
761 } while (ret == -1 && errno == EINTR);
765 } else if (ret != sizeof(matched)) {
766 fprintf(stderr, "FATAL: Short read through pipe (got %d bytes)\n", ret);
773 // Parses a colon-separated list of strings and appends them onto the given vector.
774 // Backslash escapes whatever comes after it.
775 void parse_dbpaths(const char *ptr, vector<string> *output)
778 while (*ptr != '\0') {
780 if (ptr[1] == '\0') {
781 fprintf(stderr, "ERROR: Escape character at the end of string\n");
785 str.push_back(ptr[1]);
791 output->push_back(move(str));
795 str.push_back(*ptr++);
797 output->push_back(move(str));
803 "Usage: plocate [OPTION]... PATTERN...\n"
805 " -b, --basename search only the file name portion of path names\n"
806 " -c, --count print number of matches instead of the matches\n"
807 " -d, --database DBPATH search for files in DBPATH\n"
808 " (default is " DBFILE ")\n"
809 " -i, --ignore-case search case-insensitively\n"
810 " -l, --limit LIMIT stop after LIMIT matches\n"
811 " -0, --null delimit matches by NUL instead of newline\n"
812 " -r, --regexp interpret patterns as basic regexps (slow)\n"
813 " --regex interpret patterns as extended regexps (slow)\n"
814 " -w, --wholename search the entire path name (default; see -b)\n"
815 " --help print this help\n"
816 " --version print version information\n");
821 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
822 printf("Copyright 2020 Steinar H. Gunderson\n");
823 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
824 printf("This is free software: you are free to change and redistribute it.\n");
825 printf("There is NO WARRANTY, to the extent permitted by law.\n");
829 int main(int argc, char **argv)
831 vector<string> dbpaths;
833 constexpr int EXTENDED_REGEX = 1000;
834 constexpr int FLUSH_CACHE = 1001;
835 static const struct option long_options[] = {
836 { "help", no_argument, 0, 'h' },
837 { "count", no_argument, 0, 'c' },
838 { "basename", no_argument, 0, 'b' },
839 { "database", required_argument, 0, 'd' },
840 { "existing", no_argument, 0, 'e' },
841 { "ignore-case", no_argument, 0, 'i' },
842 { "limit", required_argument, 0, 'l' },
843 { "null", no_argument, 0, '0' },
844 { "version", no_argument, 0, 'V' },
845 { "regexp", no_argument, 0, 'r' },
846 { "regex", no_argument, 0, EXTENDED_REGEX },
847 { "wholename", no_argument, 0, 'w' },
848 { "debug", no_argument, 0, 'D' }, // Not documented.
849 // Enable to test cold-cache behavior (except for access()). Not documented.
850 { "flush-cache", no_argument, 0, FLUSH_CACHE },
854 setlocale(LC_ALL, "");
856 int option_index = 0;
857 int c = getopt_long(argc, argv, "bcd:ehil:n:0rwVD", long_options, &option_index);
863 match_basename = true;
869 parse_dbpaths(optarg, &dbpaths);
872 check_existence = true;
882 limit_matches = limit_left = atoll(optarg);
883 if (limit_matches <= 0) {
884 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
892 patterns_are_regex = true;
895 patterns_are_regex = true;
896 use_extended_regex = true;
899 match_basename = false; // No-op unless -b is given first.
915 if (use_debug || flush_cache) {
916 // Debug information would leak information about which files exist,
917 // so drop setgid before we open the file; one would either need to run
918 // as root, or use a locally-built file. Doing the same thing for
919 // flush_cache is mostly paranoia, in an attempt to prevent random users
920 // from making plocate slow for everyone else.
921 if (setgid(getgid()) != 0) {
928 stdout_is_tty = isatty(1);
931 vector<Needle> needles;
932 for (int i = optind; i < argc; ++i) {
934 needle.str = argv[i];
936 // See if there are any wildcard characters, which indicates we should treat it
937 // as an (anchored) glob.
938 bool any_wildcard = false;
939 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
940 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
946 if (patterns_are_regex) {
947 needle.type = Needle::REGEX;
948 needle.re = compile_regex(needle.str);
949 } else if (any_wildcard) {
950 needle.type = Needle::GLOB;
951 } else if (ignore_case) {
952 // strcasestr() doesn't handle locales correctly (even though LSB
953 // claims it should), but somehow, fnmatch() does, and it's about
954 // the same speed as using a regex.
955 needle.type = Needle::GLOB;
956 needle.str = "*" + needle.str + "*";
958 needle.type = Needle::STRSTR;
959 needle.str = unescape_glob_to_plain_string(needle.str);
961 needles.push_back(move(needle));
963 if (needles.empty()) {
964 fprintf(stderr, "plocate: no pattern to search for specified\n");
968 if (dbpaths.empty()) {
969 // No -d given, so use our default. Note that this happens
970 // even if LOCATE_PATH exists, to match mlocate behavior.
971 dbpaths.push_back(DBFILE);
974 const char *locate_path = getenv("LOCATE_PATH");
975 if (locate_path != nullptr) {
976 parse_dbpaths(locate_path, &dbpaths);
979 uint64_t matched = 0;
980 for (size_t i = 0; i < dbpaths.size(); ++i) {
981 uint64_t this_matched;
982 if (i != dbpaths.size() - 1) {
983 this_matched = do_search_file_in_child(needles, dbpaths[i]);
985 this_matched = do_search_file(needles, dbpaths[i]);
987 matched += this_matched;
988 limit_left -= this_matched;
991 printf("%" PRId64 "\n", matched);