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 bool literal_printing = false;
62 static bool in_forked_child = false;
64 steady_clock::time_point start;
65 ZSTD_DDict *ddict = nullptr;
69 Corpus(int fd, const char *filename_for_errors, IOUringEngine *engine);
71 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
72 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
73 size_t get_num_filename_blocks() const;
74 off_t offset_for_block(uint32_t docid) const
76 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
78 const Header &get_hdr() const { return hdr; }
82 IOUringEngine *const engine;
87 Corpus::Corpus(int fd, const char *filename_for_errors, IOUringEngine *engine)
88 : fd(fd), engine(engine)
91 off_t len = lseek(fd, 0, SEEK_END);
96 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
99 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
100 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
101 fprintf(stderr, "%s: database is corrupt or not a plocate database; please rebuild it.\n", filename_for_errors);
104 if (hdr.version != 0 && hdr.version != 1) {
105 fprintf(stderr, "%s: has version %u, expected 0 or 1; please rebuild it.\n", filename_for_errors, hdr.version);
108 if (hdr.version == 0) {
109 // These will be junk data.
110 hdr.zstd_dictionary_offset_bytes = 0;
111 hdr.zstd_dictionary_length_bytes = 0;
113 if (hdr.max_version < 2) {
114 // This too. (We ignore the other max_version 2 fields.)
115 hdr.check_visibility = true;
124 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
126 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
127 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) {
128 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
129 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
130 if (trgmptr[i].trgm == trgm) {
131 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
141 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
143 // Read the file offset from this docid and the next one.
144 // This is always allowed, since we have a sentinel block at the end.
145 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
146 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
147 off_t offset = ptr[0];
148 size_t len = ptr[1] - ptr[0];
149 engine->submit_read(fd, len, offset, cb);
153 size_t Corpus::get_num_filename_blocks() const
155 return hdr.num_docids;
159 void stat_if_needed(const char *filename, bool access_ok, IOUringEngine *engine, T cb)
161 if (!access_ok || !check_existence) {
162 // Doesn't have access or doesn't care about existence, so no need to stat.
164 } else if (engine == nullptr || !engine->get_supports_stat()) {
165 // Do a synchronous stat.
167 bool ok = lstat(filename, &buf) == 0;
170 engine->submit_stat(filename, cb);
174 void scan_file_block(const vector<Needle> &needles, string_view compressed,
175 IOUringEngine *engine, AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
176 atomic<uint64_t> *matched)
178 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
179 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
180 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
185 block.resize(uncompressed_len + 1);
187 static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx(); // Reused across calls.
190 if (ddict != nullptr) {
191 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
192 compressed.size(), ddict);
194 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
197 if (ZSTD_isError(err)) {
198 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
201 block[block.size() - 1] = '\0';
203 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
204 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, engine, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
205 stat_if_needed(filename, ok, engine, [matched, serializer, local_seq, next_seq, filename](bool ok) {
208 serializer->print(local_seq, next_seq - local_seq, filename);
210 serializer->print(local_seq, next_seq - local_seq, "");
217 // We need to know the next sequence number before inserting into Serializer,
218 // so always buffer one candidate.
219 const char *pending_candidate = nullptr;
221 uint64_t local_seq = seq << 32;
222 for (const char *filename = block.data();
223 filename != block.data() + block.size();
224 filename += strlen(filename) + 1) {
225 const char *haystack = filename;
226 if (match_basename) {
227 haystack = strrchr(filename, '/');
228 if (haystack == nullptr) {
236 for (const Needle &needle : needles) {
237 if (!matches(needle, haystack)) {
243 if (pending_candidate != nullptr) {
244 test_candidate(pending_candidate, local_seq, local_seq + 1);
247 pending_candidate = filename;
250 if (pending_candidate == nullptr) {
251 serializer->print(seq << 32, 1ULL << 32, "");
253 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
257 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
259 Serializer docids_in_order;
260 AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
261 atomic<uint64_t> matched{ 0 };
262 for (size_t i = 0; i < docids.size(); ++i) {
263 uint32_t docid = docids[i];
264 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, engine, &docids_in_order](string_view compressed) {
265 scan_file_block(needles, compressed, engine, &access_rx_cache, i, &docids_in_order, &matched);
272 struct WorkerThread {
275 // We use a result queue instead of synchronizing Serializer,
276 // since a lock on it becomes a huge choke point if there are
284 vector<Result> results;
287 class WorkerThreadReceiver : public ResultReceiver {
289 WorkerThreadReceiver(WorkerThread *wt)
292 void print(uint64_t seq, uint64_t skip, const string msg) override
294 lock_guard<mutex> lock(wt->result_mu);
295 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
296 wt->results.back().skip += skip;
298 wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
306 void deliver_results(WorkerThread *wt, Serializer *serializer)
308 vector<WorkerThread::Result> results;
310 lock_guard<mutex> lock(wt->result_mu);
311 results = move(wt->results);
313 for (const WorkerThread::Result &result : results) {
314 serializer->print(result.seq, result.skip, move(result.msg));
318 // We do this sequentially, as it's faster than scattering
319 // a lot of I/O through io_uring and hoping the kernel will
320 // coalesce it plus readahead for us. Since we assume that
321 // we will primarily be CPU-bound, we'll be firing up one
322 // worker thread for each spare core (the last one will
323 // only be doing I/O). access() is still synchronous.
324 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
327 const Header &hdr = corpus.get_hdr();
328 if (hdr.zstd_dictionary_length_bytes > 0) {
330 dictionary.resize(hdr.zstd_dictionary_length_bytes);
331 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
332 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
336 AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
337 Serializer serializer;
338 uint32_t num_blocks = corpus.get_num_filename_blocks();
339 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
340 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
341 atomic<uint64_t> matched{ 0 };
344 condition_variable queue_added, queue_removed;
345 deque<tuple<int, int, string>> work_queue; // Under mu.
346 bool done = false; // Under mu.
348 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
349 dprintf("Using %u worker threads for linear scan.\n", num_threads);
350 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
351 for (unsigned i = 0; i < num_threads; ++i) {
352 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, &matched, i] {
353 // regcomp() takes a lock on the regex, so each thread will need its own.
354 const vector<Needle> *use_needles = &needles;
355 vector<Needle> recompiled_needles;
356 if (i != 0 && patterns_are_regex) {
357 recompiled_needles = needles;
358 for (Needle &needle : recompiled_needles) {
359 needle.re = compile_regex(needle.str);
361 use_needles = &recompiled_needles;
364 WorkerThreadReceiver receiver(&threads[i]);
366 uint32_t io_docid, last_docid;
370 unique_lock<mutex> lock(mu);
371 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
372 if (done && work_queue.empty()) {
375 tie(io_docid, last_docid, compressed) = move(work_queue.front());
376 work_queue.pop_front();
377 queue_removed.notify_all();
380 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
381 size_t relative_offset = offsets[docid] - offsets[io_docid];
382 size_t len = offsets[docid + 1] - offsets[docid];
383 // IOUringEngine isn't thread-safe, so we do any needed stat()s synchronously (nullptr engine).
384 scan_file_block(*use_needles, { &compressed[relative_offset], len }, /*engine=*/nullptr, &access_rx_cache, docid, &receiver, &matched);
391 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
392 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
393 size_t io_len = offsets[last_docid] - offsets[io_docid];
394 if (compressed.size() < io_len) {
395 compressed.resize(io_len);
397 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
400 unique_lock<mutex> lock(mu);
401 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
402 work_queue.emplace_back(io_docid, last_docid, move(compressed));
403 queue_added.notify_one(); // Avoid the thundering herd.
406 // Pick up some results, so that we are sure that we won't just overload.
407 // (Seemingly, going through all of these causes slowness with many threads,
408 // but taking only one is OK.)
409 unsigned i = io_docid / 32;
410 deliver_results(&threads[i % num_threads], &serializer);
413 lock_guard<mutex> lock(mu);
415 queue_added.notify_all();
417 for (unsigned i = 0; i < num_threads; ++i) {
419 deliver_results(&threads[i], &serializer);
424 // Takes the given posting list, unions it into the parts of the trigram disjunction
425 // already read; if the list is complete, intersects with “cur_candidates”.
427 // Returns true if the search should be aborted (we are done).
428 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
430 if (td->docids.empty()) {
431 td->docids = move(decoded);
434 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
435 swap(*tmp, td->docids);
437 if (--td->remaining_trigrams_to_read > 0) {
438 // Need to wait for more.
440 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
441 td->remaining_trigrams_to_read, td->index, td->docids.size());
445 if (cur_candidates->empty()) {
447 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
448 td->index, td->docids.size());
450 *cur_candidates = move(td->docids);
453 set_intersection(cur_candidates->begin(), cur_candidates->end(),
454 td->docids.begin(), td->docids.end(),
455 back_inserter(*tmp));
456 swap(*cur_candidates, *tmp);
458 if (cur_candidates->empty()) {
459 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
460 td->index, td->docids.size());
463 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
464 td->index, td->docids.size(), cur_candidates->size());
471 uint64_t do_search_file(const vector<Needle> &needles, const std::string &filename)
473 int fd = open(filename.c_str(), O_RDONLY);
475 perror(filename.c_str());
480 if (setgid(getgid()) != 0) {
485 start = steady_clock::now();
486 if (access("/", R_OK | X_OK)) {
487 // We can't find anything, no need to bother...
491 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
492 Corpus corpus(fd, filename.c_str(), &engine);
493 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
495 vector<TrigramDisjunction> trigram_groups;
496 if (patterns_are_regex) {
497 // We could parse the regex to find trigrams that have to be there
498 // (there are actually known algorithms to deal with disjunctions
499 // and such, too), but for now, we just go brute force.
500 // Using locate with regexes is pretty niche.
502 for (const Needle &needle : needles) {
503 parse_trigrams(needle.str, ignore_case, &trigram_groups);
509 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
510 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
512 // Give them names for debugging.
513 unsigned td_index = 0;
514 for (TrigramDisjunction &td : trigram_groups) {
515 td.index = td_index++;
518 // Collect which trigrams we need to look up in the hash table.
519 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
520 for (TrigramDisjunction &td : trigram_groups) {
521 for (uint32_t trgm : td.trigram_alternatives) {
522 trigrams_to_lookup[trgm].push_back(&td);
525 if (trigrams_to_lookup.empty()) {
526 // Too short for trigram matching. Apply brute force.
527 // (We could have searched through all trigrams that matched
528 // the pattern and done a union of them, but that's a lot of
529 // work for fairly unclear gain.)
530 uint64_t matched = scan_all_docids(needles, fd, corpus);
531 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
532 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
536 // Sneak in fetching the dictionary, if present. It's not necessarily clear
537 // exactly where it would be cheapest to get it, but it needs to be present
538 // before we can decode any of the posting lists. Most likely, it's
539 // in the same filesystem block as the header anyway, so it should be
540 // present in the cache.
542 const Header &hdr = corpus.get_hdr();
543 if (hdr.zstd_dictionary_length_bytes > 0) {
544 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
545 ddict = ZSTD_createDDict(s.data(), s.size());
546 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
551 // Look them all up on disk.
552 bool should_early_exit = false;
553 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
554 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }, &should_early_exit](const Trigram *trgmptr, size_t len) {
555 if (trgmptr == nullptr) {
556 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
557 for (TrigramDisjunction *td : *trigram_groups) {
558 --td->remaining_trigrams_to_read;
560 // If we now know this trigram group doesn't match anything at all,
561 // we can do early exit; however, if we're in a forked child,
562 // that would confuse the parent process (since we don't write
563 // our count to the pipe), so we wait until we're back in to the
564 // regular (non-async) context. This is a fairly rare case anyway,
565 // and the gains from dropping the remaining trigram reads are limited.
566 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
567 if (in_forked_child) {
568 should_early_exit = true;
570 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
580 for (TrigramDisjunction *td : *trigram_groups) {
581 --td->remaining_trigrams_to_read;
582 td->max_num_docids += trgmptr->num_docids;
583 td->read_trigrams.emplace_back(*trgmptr, len);
588 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
590 if (should_early_exit) {
594 for (TrigramDisjunction &td : trigram_groups) {
596 td.remaining_trigrams_to_read = td.read_trigrams.size();
598 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
599 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
603 // TODO: For case-insensitive (ie. more than one alternative in each),
604 // prioritize the ones with fewer seeks?
605 sort(trigram_groups.begin(), trigram_groups.end(),
606 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
607 return a.max_num_docids < b.max_num_docids;
610 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
611 for (TrigramDisjunction &td : trigram_groups) {
612 for (uint32_t trgm : td.trigram_alternatives) {
613 uses_trigram[trgm].push_back(&td);
617 unordered_set<uint32_t> trigrams_submitted_read;
618 vector<uint32_t> cur_candidates, tmp, decoded;
620 for (TrigramDisjunction &td : trigram_groups) {
621 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
622 dprintf("%s has up to %u entries, ignoring the rest (will "
623 "weed out false positives later)\n",
624 print_td(td).c_str(), td.max_num_docids);
628 for (auto &[trgmptr, len] : td.read_trigrams) {
629 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
632 trigrams_submitted_read.insert(trgmptr.trgm);
633 // Only stay a certain amount ahead, so that we don't spend I/O
634 // on reading the latter, large posting lists. We are unlikely
635 // to need them anyway, even if they should come in first.
636 if (engine.get_waiting_reads() >= 5) {
641 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
645 uint32_t trgm = trgmptr.trgm;
646 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
647 size_t num = trgmptr.num_docids;
649 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
651 assert(uses_trigram.count(trgm) != 0);
652 bool was_empty = cur_candidates.empty();
654 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
657 for (TrigramDisjunction *td : uses_trigram[trgm]) {
658 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
664 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
665 } else if (cur_candidates.empty()) {
666 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
668 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
678 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
679 1e3 * duration<float>(steady_clock::now() - start).count());
681 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
682 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
683 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
687 // Run do_search_file() in a child process.
689 // The reason for this is that we're not robust against malicious input, so we need
690 // to drop privileges after opening the file. (Otherwise, we could fall prey to an attack
691 // where a user does locate -d badfile.db:/var/lib/plocate/plocate.db, badfile.db contains
692 // a buffer overflow that takes over the process, and then uses the elevated privileges
693 // to print out otherwise inaccessible paths.) We solve this by forking and treating the
694 // child process as untrusted after it has dropped its privileges (which it does before
695 // reading any data from the file); it returns a single 64-bit number over a pipe,
696 // and that's it. The parent keeps its privileges, and can then fork out new children
697 // without fear of being taken over. (The child keeps stdout for outputting results.)
699 // The count is returned over the pipe, because it's needed both for --limit and --count.
700 uint64_t do_search_file_in_child(const vector<Needle> &needles, const std::string &filename)
703 if (pipe(pipefd) == -1) {
708 pid_t child_pid = fork();
713 in_forked_child = true;
714 uint64_t matched = do_search_file(needles, filename);
717 ret = write(pipefd[1], &matched, sizeof(matched));
718 } while (ret == -1 && errno == EINTR);
719 if (ret != sizeof(matched)) {
736 // Wait for the child to finish.
740 err = waitpid(child_pid, &wstatus, 0);
741 } while (err == -1 && errno == EINTR);
746 if (WIFEXITED(wstatus)) {
747 if (WEXITSTATUS(wstatus) != 0) {
748 // The child has probably already printed out its error, so just propagate the exit status.
749 exit(WEXITSTATUS(wstatus));
752 } else if (!WIFEXITED(wstatus)) {
753 fprintf(stderr, "FATAL: Child died unexpectedly while processing %s\n", filename.c_str());
757 // Now get the number of matches from the child.
761 ret = read(pipefd[0], &matched, sizeof(matched));
762 } while (ret == -1 && errno == EINTR);
766 } else if (ret != sizeof(matched)) {
767 fprintf(stderr, "FATAL: Short read through pipe (got %d bytes)\n", ret);
774 // Parses a colon-separated list of strings and appends them onto the given vector.
775 // Backslash escapes whatever comes after it.
776 void parse_dbpaths(const char *ptr, vector<string> *output)
779 while (*ptr != '\0') {
781 if (ptr[1] == '\0') {
782 fprintf(stderr, "ERROR: Escape character at the end of string\n");
786 str.push_back(ptr[1]);
792 output->push_back(move(str));
796 str.push_back(*ptr++);
798 output->push_back(move(str));
804 "Usage: plocate [OPTION]... PATTERN...\n"
806 " -b, --basename search only the file name portion of path names\n"
807 " -c, --count print number of matches instead of the matches\n"
808 " -d, --database DBPATH search for files in DBPATH\n"
809 " (default is " DBFILE ")\n"
810 " -i, --ignore-case search case-insensitively\n"
811 " -l, --limit LIMIT stop after LIMIT matches\n"
812 " -0, --null delimit matches by NUL instead of newline\n"
813 " -N, --literal do not quote filenames, even if printing to a tty\n"
814 " -r, --regexp interpret patterns as basic regexps (slow)\n"
815 " --regex interpret patterns as extended regexps (slow)\n"
816 " -w, --wholename search the entire path name (default; see -b)\n"
817 " --help print this help\n"
818 " --version print version information\n");
823 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
824 printf("Copyright 2020 Steinar H. Gunderson\n");
825 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
826 printf("This is free software: you are free to change and redistribute it.\n");
827 printf("There is NO WARRANTY, to the extent permitted by law.\n");
831 int main(int argc, char **argv)
833 vector<string> dbpaths;
835 constexpr int EXTENDED_REGEX = 1000;
836 constexpr int FLUSH_CACHE = 1001;
837 static const struct option long_options[] = {
838 { "help", no_argument, 0, 'h' },
839 { "count", no_argument, 0, 'c' },
840 { "all", no_argument, 0, 'A' },
841 { "basename", no_argument, 0, 'b' },
842 { "database", required_argument, 0, 'd' },
843 { "existing", no_argument, 0, 'e' },
844 { "ignore-case", no_argument, 0, 'i' },
845 { "limit", required_argument, 0, 'l' },
846 { "literal", no_argument, 0, 'N' },
847 { "null", no_argument, 0, '0' },
848 { "version", no_argument, 0, 'V' },
849 { "regexp", no_argument, 0, 'r' },
850 { "regex", no_argument, 0, EXTENDED_REGEX },
851 { "wholename", no_argument, 0, 'w' },
852 { "debug", no_argument, 0, 'D' }, // Not documented.
853 // Enable to test cold-cache behavior (except for access()). Not documented.
854 { "flush-cache", no_argument, 0, FLUSH_CACHE },
858 setlocale(LC_ALL, "");
860 int option_index = 0;
861 int c = getopt_long(argc, argv, "Abcd:ehil:n:N0rwVD", long_options, &option_index);
870 match_basename = true;
876 parse_dbpaths(optarg, &dbpaths);
879 check_existence = true;
889 limit_matches = limit_left = atoll(optarg);
890 if (limit_matches <= 0) {
891 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
896 literal_printing = true;
902 patterns_are_regex = true;
905 patterns_are_regex = true;
906 use_extended_regex = true;
909 match_basename = false; // No-op unless -b is given first.
925 if (use_debug || flush_cache) {
926 // Debug information would leak information about which files exist,
927 // so drop setgid before we open the file; one would either need to run
928 // as root, or use a locally-built file. Doing the same thing for
929 // flush_cache is mostly paranoia, in an attempt to prevent random users
930 // from making plocate slow for everyone else.
931 if (setgid(getgid()) != 0) {
938 stdout_is_tty = isatty(1);
941 vector<Needle> needles;
942 for (int i = optind; i < argc; ++i) {
944 needle.str = argv[i];
946 // See if there are any wildcard characters, which indicates we should treat it
947 // as an (anchored) glob.
948 bool any_wildcard = false;
949 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
950 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
956 if (patterns_are_regex) {
957 needle.type = Needle::REGEX;
958 needle.re = compile_regex(needle.str);
959 } else if (any_wildcard) {
960 needle.type = Needle::GLOB;
961 } else if (ignore_case && false) {
962 // strcasestr() doesn't handle locales correctly (even though LSB
963 // claims it should), but somehow, fnmatch() does, and it's about
964 // the same speed as using a regex.
965 needle.type = Needle::GLOB;
966 needle.str = "*" + needle.str + "*";
968 needle.type = Needle::STRSTR;
969 needle.str = unescape_glob_to_plain_string(needle.str);
971 needles.push_back(move(needle));
973 if (needles.empty()) {
974 fprintf(stderr, "plocate: no pattern to search for specified\n");
978 if (dbpaths.empty()) {
979 // No -d given, so use our default. Note that this happens
980 // even if LOCATE_PATH exists, to match mlocate behavior.
981 dbpaths.push_back(DBFILE);
984 const char *locate_path = getenv("LOCATE_PATH");
985 if (locate_path != nullptr) {
986 parse_dbpaths(locate_path, &dbpaths);
989 uint64_t matched = 0;
990 for (size_t i = 0; i < dbpaths.size(); ++i) {
991 uint64_t this_matched;
992 if (i != dbpaths.size() - 1) {
993 this_matched = do_search_file_in_child(needles, dbpaths[i]);
995 this_matched = do_search_file(needles, dbpaths[i]);
997 matched += this_matched;
998 limit_left -= this_matched;
1001 printf("%" PRId64 "\n", matched);