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 bool check_existence = false;
57 int64_t limit_matches = numeric_limits<int64_t>::max();
58 int64_t limit_left = numeric_limits<int64_t>::max();
59 bool stdout_is_tty = false;
60 static bool in_forked_child = false;
62 steady_clock::time_point start;
63 ZSTD_DDict *ddict = nullptr;
67 Corpus(int fd, IOUringEngine *engine);
69 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
70 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
71 size_t get_num_filename_blocks() const;
72 off_t offset_for_block(uint32_t docid) const
74 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
76 const Header &get_hdr() const { return hdr; }
80 IOUringEngine *const engine;
85 Corpus::Corpus(int fd, IOUringEngine *engine)
86 : fd(fd), engine(engine)
89 off_t len = lseek(fd, 0, SEEK_END);
94 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
97 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
98 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
99 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
102 if (hdr.version != 0 && hdr.version != 1) {
103 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
106 if (hdr.version == 0) {
107 // These will be junk data.
108 hdr.zstd_dictionary_offset_bytes = 0;
109 hdr.zstd_dictionary_length_bytes = 0;
111 if (hdr.max_version < 2) {
112 // This too. (We ignore the other max_version 2 fields.)
113 hdr.check_visibility = true;
122 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
124 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
125 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) {
126 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
127 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
128 if (trgmptr[i].trgm == trgm) {
129 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
139 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
141 // Read the file offset from this docid and the next one.
142 // This is always allowed, since we have a sentinel block at the end.
143 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
144 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
145 off_t offset = ptr[0];
146 size_t len = ptr[1] - ptr[0];
147 engine->submit_read(fd, len, offset, cb);
151 size_t Corpus::get_num_filename_blocks() const
153 return hdr.num_docids;
157 void stat_if_needed(const char *filename, bool access_ok, IOUringEngine *engine, T cb)
159 if (!access_ok || !check_existence) {
160 // Doesn't have access or doesn't care about existence, so no need to stat.
162 } else if (engine == nullptr || !engine->get_supports_stat()) {
163 // Do a synchronous stat.
165 bool ok = lstat(filename, &buf) == 0;
168 engine->submit_stat(filename, cb);
172 void scan_file_block(const vector<Needle> &needles, string_view compressed,
173 IOUringEngine *engine, AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
174 atomic<uint64_t> *matched)
176 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
177 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
178 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
183 block.resize(uncompressed_len + 1);
185 static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx(); // Reused across calls.
188 if (ddict != nullptr) {
189 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
190 compressed.size(), ddict);
192 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
195 if (ZSTD_isError(err)) {
196 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
199 block[block.size() - 1] = '\0';
201 auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
202 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, engine, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
203 stat_if_needed(filename, ok, engine, [matched, serializer, local_seq, next_seq, filename](bool ok) {
206 serializer->print(local_seq, next_seq - local_seq, filename);
208 serializer->print(local_seq, next_seq - local_seq, "");
215 // We need to know the next sequence number before inserting into Serializer,
216 // so always buffer one candidate.
217 const char *pending_candidate = nullptr;
219 uint64_t local_seq = seq << 32;
220 for (const char *filename = block.data();
221 filename != block.data() + block.size();
222 filename += strlen(filename) + 1) {
223 const char *haystack = filename;
224 if (match_basename) {
225 haystack = strrchr(filename, '/');
226 if (haystack == nullptr) {
234 for (const Needle &needle : needles) {
235 if (!matches(needle, haystack)) {
241 if (pending_candidate != nullptr) {
242 test_candidate(pending_candidate, local_seq, local_seq + 1);
245 pending_candidate = filename;
248 if (pending_candidate == nullptr) {
249 serializer->print(seq << 32, 1ULL << 32, "");
251 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
255 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
257 Serializer docids_in_order;
258 AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
259 atomic<uint64_t> matched{ 0 };
260 for (size_t i = 0; i < docids.size(); ++i) {
261 uint32_t docid = docids[i];
262 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, engine, &docids_in_order](string_view compressed) {
263 scan_file_block(needles, compressed, engine, &access_rx_cache, i, &docids_in_order, &matched);
270 struct WorkerThread {
273 // We use a result queue instead of synchronizing Serializer,
274 // since a lock on it becomes a huge choke point if there are
282 vector<Result> results;
285 class WorkerThreadReceiver : public ResultReceiver {
287 WorkerThreadReceiver(WorkerThread *wt)
290 void print(uint64_t seq, uint64_t skip, const string msg) override
292 lock_guard<mutex> lock(wt->result_mu);
293 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
294 wt->results.back().skip += skip;
296 wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
304 void deliver_results(WorkerThread *wt, Serializer *serializer)
306 vector<WorkerThread::Result> results;
308 lock_guard<mutex> lock(wt->result_mu);
309 results = move(wt->results);
311 for (const WorkerThread::Result &result : results) {
312 serializer->print(result.seq, result.skip, move(result.msg));
316 // We do this sequentially, as it's faster than scattering
317 // a lot of I/O through io_uring and hoping the kernel will
318 // coalesce it plus readahead for us. Since we assume that
319 // we will primarily be CPU-bound, we'll be firing up one
320 // worker thread for each spare core (the last one will
321 // only be doing I/O). access() is still synchronous.
322 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
325 const Header &hdr = corpus.get_hdr();
326 if (hdr.zstd_dictionary_length_bytes > 0) {
328 dictionary.resize(hdr.zstd_dictionary_length_bytes);
329 complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
330 ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
334 AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
335 Serializer serializer;
336 uint32_t num_blocks = corpus.get_num_filename_blocks();
337 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
338 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
339 atomic<uint64_t> matched{ 0 };
342 condition_variable queue_added, queue_removed;
343 deque<tuple<int, int, string>> work_queue; // Under mu.
344 bool done = false; // Under mu.
346 unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
347 dprintf("Using %u worker threads for linear scan.\n", num_threads);
348 unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
349 for (unsigned i = 0; i < num_threads; ++i) {
350 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, engine{ corpus.engine }, &matched, i] {
351 // regcomp() takes a lock on the regex, so each thread will need its own.
352 const vector<Needle> *use_needles = &needles;
353 vector<Needle> recompiled_needles;
354 if (i != 0 && patterns_are_regex) {
355 recompiled_needles = needles;
356 for (Needle &needle : recompiled_needles) {
357 needle.re = compile_regex(needle.str);
359 use_needles = &recompiled_needles;
362 WorkerThreadReceiver receiver(&threads[i]);
364 uint32_t io_docid, last_docid;
368 unique_lock<mutex> lock(mu);
369 queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
370 if (done && work_queue.empty()) {
373 tie(io_docid, last_docid, compressed) = move(work_queue.front());
374 work_queue.pop_front();
375 queue_removed.notify_all();
378 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
379 size_t relative_offset = offsets[docid] - offsets[io_docid];
380 size_t len = offsets[docid + 1] - offsets[docid];
381 scan_file_block(*use_needles, { &compressed[relative_offset], len }, engine, &access_rx_cache, docid, &receiver, &matched);
388 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
389 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
390 size_t io_len = offsets[last_docid] - offsets[io_docid];
391 if (compressed.size() < io_len) {
392 compressed.resize(io_len);
394 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
397 unique_lock<mutex> lock(mu);
398 queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; }); // Allow ~2MB of data queued up.
399 work_queue.emplace_back(io_docid, last_docid, move(compressed));
400 queue_added.notify_one(); // Avoid the thundering herd.
403 // Pick up some results, so that we are sure that we won't just overload.
404 // (Seemingly, going through all of these causes slowness with many threads,
405 // but taking only one is OK.)
406 unsigned i = io_docid / 32;
407 deliver_results(&threads[i % num_threads], &serializer);
410 lock_guard<mutex> lock(mu);
412 queue_added.notify_all();
414 for (unsigned i = 0; i < num_threads; ++i) {
416 deliver_results(&threads[i], &serializer);
421 // Takes the given posting list, unions it into the parts of the trigram disjunction
422 // already read; if the list is complete, intersects with “cur_candidates”.
424 // Returns true if the search should be aborted (we are done).
425 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
427 if (td->docids.empty()) {
428 td->docids = move(decoded);
431 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
432 swap(*tmp, td->docids);
434 if (--td->remaining_trigrams_to_read > 0) {
435 // Need to wait for more.
437 dprintf(" ... %u reads left in OR group %u (%zu docids in list)\n",
438 td->remaining_trigrams_to_read, td->index, td->docids.size());
442 if (cur_candidates->empty()) {
444 dprintf(" ... all reads done for OR group %u (%zu docids)\n",
445 td->index, td->docids.size());
447 *cur_candidates = move(td->docids);
450 set_intersection(cur_candidates->begin(), cur_candidates->end(),
451 td->docids.begin(), td->docids.end(),
452 back_inserter(*tmp));
453 swap(*cur_candidates, *tmp);
455 if (cur_candidates->empty()) {
456 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
457 td->index, td->docids.size());
460 dprintf(" ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
461 td->index, td->docids.size(), cur_candidates->size());
468 uint64_t do_search_file(const vector<Needle> &needles, const std::string &filename)
470 int fd = open(filename.c_str(), O_RDONLY);
472 perror(filename.c_str());
477 if (setgid(getgid()) != 0) {
482 start = steady_clock::now();
483 if (access("/", R_OK | X_OK)) {
484 // We can't find anything, no need to bother...
488 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
489 Corpus corpus(fd, &engine);
490 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
492 vector<TrigramDisjunction> trigram_groups;
493 if (patterns_are_regex) {
494 // We could parse the regex to find trigrams that have to be there
495 // (there are actually known algorithms to deal with disjunctions
496 // and such, too), but for now, we just go brute force.
497 // Using locate with regexes is pretty niche.
499 for (const Needle &needle : needles) {
500 parse_trigrams(needle.str, ignore_case, &trigram_groups);
506 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
507 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
509 // Give them names for debugging.
510 unsigned td_index = 0;
511 for (TrigramDisjunction &td : trigram_groups) {
512 td.index = td_index++;
515 // Collect which trigrams we need to look up in the hash table.
516 unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
517 for (TrigramDisjunction &td : trigram_groups) {
518 for (uint32_t trgm : td.trigram_alternatives) {
519 trigrams_to_lookup[trgm].push_back(&td);
522 if (trigrams_to_lookup.empty()) {
523 // Too short for trigram matching. Apply brute force.
524 // (We could have searched through all trigrams that matched
525 // the pattern and done a union of them, but that's a lot of
526 // work for fairly unclear gain.)
527 uint64_t matched = scan_all_docids(needles, fd, corpus);
528 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
529 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
533 // Sneak in fetching the dictionary, if present. It's not necessarily clear
534 // exactly where it would be cheapest to get it, but it needs to be present
535 // before we can decode any of the posting lists. Most likely, it's
536 // in the same filesystem block as the header anyway, so it should be
537 // present in the cache.
539 const Header &hdr = corpus.get_hdr();
540 if (hdr.zstd_dictionary_length_bytes > 0) {
541 engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
542 ddict = ZSTD_createDDict(s.data(), s.size());
543 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
548 // Look them all up on disk.
549 bool should_early_exit = false;
550 for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
551 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }, &should_early_exit](const Trigram *trgmptr, size_t len) {
552 if (trgmptr == nullptr) {
553 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
554 for (TrigramDisjunction *td : *trigram_groups) {
555 --td->remaining_trigrams_to_read;
557 // If we now know this trigram group doesn't match anything at all,
558 // we can do early exit; however, if we're in a forked child,
559 // that would confuse the parent process (since we don't write
560 // our count to the pipe), so we wait until we're back in to the
561 // regular (non-async) context. This is a fairly rare case anyway,
562 // and the gains from dropping the remaining trigram reads are limited.
563 if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
564 if (in_forked_child) {
565 should_early_exit = true;
567 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
577 for (TrigramDisjunction *td : *trigram_groups) {
578 --td->remaining_trigrams_to_read;
579 td->max_num_docids += trgmptr->num_docids;
580 td->read_trigrams.emplace_back(*trgmptr, len);
585 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
587 if (should_early_exit) {
591 for (TrigramDisjunction &td : trigram_groups) {
593 td.remaining_trigrams_to_read = td.read_trigrams.size();
595 if (ignore_case) { // If case-sensitive, they'll all be pretty obvious single-entry groups.
596 dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
600 // TODO: For case-insensitive (ie. more than one alternative in each),
601 // prioritize the ones with fewer seeks?
602 sort(trigram_groups.begin(), trigram_groups.end(),
603 [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
604 return a.max_num_docids < b.max_num_docids;
607 unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
608 for (TrigramDisjunction &td : trigram_groups) {
609 for (uint32_t trgm : td.trigram_alternatives) {
610 uses_trigram[trgm].push_back(&td);
614 unordered_set<uint32_t> trigrams_submitted_read;
615 vector<uint32_t> cur_candidates, tmp, decoded;
617 for (TrigramDisjunction &td : trigram_groups) {
618 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
619 dprintf("%s has up to %u entries, ignoring the rest (will "
620 "weed out false positives later)\n",
621 print_td(td).c_str(), td.max_num_docids);
625 for (auto &[trgmptr, len] : td.read_trigrams) {
626 if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
629 trigrams_submitted_read.insert(trgmptr.trgm);
630 // Only stay a certain amount ahead, so that we don't spend I/O
631 // on reading the latter, large posting lists. We are unlikely
632 // to need them anyway, even if they should come in first.
633 if (engine.get_waiting_reads() >= 5) {
638 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
642 uint32_t trgm = trgmptr.trgm;
643 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
644 size_t num = trgmptr.num_docids;
646 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
648 assert(uses_trigram.count(trgm) != 0);
649 bool was_empty = cur_candidates.empty();
651 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
654 for (TrigramDisjunction *td : uses_trigram[trgm]) {
655 done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
661 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
662 } else if (cur_candidates.empty()) {
663 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
665 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
675 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
676 1e3 * duration<float>(steady_clock::now() - start).count());
678 uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
679 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
680 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
684 // Run do_search_file() in a child process.
686 // The reason for this is that we're not robust against malicious input, so we need
687 // to drop privileges after opening the file. (Otherwise, we could fall prey to an attack
688 // where a user does locate -d badfile.db:/var/lib/plocate/plocate.db, badfile.db contains
689 // a buffer overflow that takes over the process, and then uses the elevated privileges
690 // to print out otherwise inaccessible paths.) We solve this by forking and treating the
691 // child process as untrusted after it has dropped its privileges (which it does before
692 // reading any data from the file); it returns a single 64-bit number over a pipe,
693 // and that's it. The parent keeps its privileges, and can then fork out new children
694 // without fear of being taken over. (The child keeps stdout for outputting results.)
696 // The count is returned over the pipe, because it's needed both for --limit and --count.
697 uint64_t do_search_file_in_child(const vector<Needle> &needles, const std::string &filename)
700 if (pipe(pipefd) == -1) {
705 pid_t child_pid = fork();
710 in_forked_child = true;
711 uint64_t matched = do_search_file(needles, filename);
714 ret = write(pipefd[1], &matched, sizeof(matched));
715 } while (ret == -1 && errno == EINTR);
716 if (ret != sizeof(matched)) {
733 // Wait for the child to finish.
737 err = waitpid(child_pid, &wstatus, 0);
738 } while (err == -1 && errno == EINTR);
743 if (WIFEXITED(wstatus)) {
744 if (WEXITSTATUS(wstatus) != 0) {
745 // The child has probably already printed out its error, so just propagate the exit status.
746 exit(WEXITSTATUS(wstatus));
749 } else if (!WIFEXITED(wstatus)) {
750 fprintf(stderr, "FATAL: Child died unexpectedly while processing %s\n", filename.c_str());
754 // Now get the number of matches from the child.
758 ret = read(pipefd[0], &matched, sizeof(matched));
759 } while (ret == -1 && errno == EINTR);
763 } else if (ret != sizeof(matched)) {
764 fprintf(stderr, "FATAL: Short read through pipe (got %d bytes)\n", ret);
771 // Parses a colon-separated list of strings and appends them onto the given vector.
772 // Backslash escapes whatever comes after it.
773 void parse_dbpaths(const char *ptr, vector<string> *output)
776 while (*ptr != '\0') {
778 if (ptr[1] == '\0') {
779 fprintf(stderr, "ERROR: Escape character at the end of string\n");
783 str.push_back(ptr[1]);
789 output->push_back(move(str));
793 str.push_back(*ptr++);
795 output->push_back(move(str));
801 "Usage: plocate [OPTION]... PATTERN...\n"
803 " -b, --basename search only the file name portion of path names\n"
804 " -c, --count print number of matches instead of the matches\n"
805 " -d, --database DBPATH search for files in DBPATH\n"
806 " (default is " DBFILE ")\n"
807 " -i, --ignore-case search case-insensitively\n"
808 " -l, --limit LIMIT stop after LIMIT matches\n"
809 " -0, --null delimit matches by NUL instead of newline\n"
810 " -r, --regexp interpret patterns as basic regexps (slow)\n"
811 " --regex interpret patterns as extended regexps (slow)\n"
812 " -w, --wholename search the entire path name (default; see -b)\n"
813 " --help print this help\n"
814 " --version print version information\n");
819 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
820 printf("Copyright 2020 Steinar H. Gunderson\n");
821 printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
822 printf("This is free software: you are free to change and redistribute it.\n");
823 printf("There is NO WARRANTY, to the extent permitted by law.\n");
827 int main(int argc, char **argv)
829 vector<string> dbpaths;
831 constexpr int EXTENDED_REGEX = 1000;
832 constexpr int FLUSH_CACHE = 1001;
833 static const struct option long_options[] = {
834 { "help", no_argument, 0, 'h' },
835 { "count", no_argument, 0, 'c' },
836 { "basename", no_argument, 0, 'b' },
837 { "database", required_argument, 0, 'd' },
838 { "existing", no_argument, 0, 'e' },
839 { "ignore-case", no_argument, 0, 'i' },
840 { "limit", required_argument, 0, 'l' },
841 { "null", no_argument, 0, '0' },
842 { "version", no_argument, 0, 'V' },
843 { "regexp", no_argument, 0, 'r' },
844 { "regex", no_argument, 0, EXTENDED_REGEX },
845 { "wholename", no_argument, 0, 'w' },
846 { "debug", no_argument, 0, 'D' }, // Not documented.
847 // Enable to test cold-cache behavior (except for access()). Not documented.
848 { "flush-cache", no_argument, 0, FLUSH_CACHE },
852 setlocale(LC_ALL, "");
854 int option_index = 0;
855 int c = getopt_long(argc, argv, "bcd:ehil:n:0rwVD", long_options, &option_index);
861 match_basename = true;
867 parse_dbpaths(optarg, &dbpaths);
870 check_existence = true;
880 limit_matches = limit_left = atoll(optarg);
881 if (limit_matches <= 0) {
882 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
890 patterns_are_regex = true;
893 patterns_are_regex = true;
894 use_extended_regex = true;
897 match_basename = false; // No-op unless -b is given first.
913 if (use_debug || flush_cache) {
914 // Debug information would leak information about which files exist,
915 // so drop setgid before we open the file; one would either need to run
916 // as root, or use a locally-built file. Doing the same thing for
917 // flush_cache is mostly paranoia, in an attempt to prevent random users
918 // from making plocate slow for everyone else.
919 if (setgid(getgid()) != 0) {
926 stdout_is_tty = isatty(1);
929 vector<Needle> needles;
930 for (int i = optind; i < argc; ++i) {
932 needle.str = argv[i];
934 // See if there are any wildcard characters, which indicates we should treat it
935 // as an (anchored) glob.
936 bool any_wildcard = false;
937 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
938 if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
944 if (patterns_are_regex) {
945 needle.type = Needle::REGEX;
946 needle.re = compile_regex(needle.str);
947 } else if (any_wildcard) {
948 needle.type = Needle::GLOB;
949 } else if (ignore_case) {
950 // strcasestr() doesn't handle locales correctly (even though LSB
951 // claims it should), but somehow, fnmatch() does, and it's about
952 // the same speed as using a regex.
953 needle.type = Needle::GLOB;
954 needle.str = "*" + needle.str + "*";
956 needle.type = Needle::STRSTR;
957 needle.str = unescape_glob_to_plain_string(needle.str);
959 needles.push_back(move(needle));
961 if (needles.empty()) {
962 fprintf(stderr, "plocate: no pattern to search for specified\n");
966 if (dbpaths.empty()) {
967 // No -d given, so use our default. Note that this happens
968 // even if LOCATE_PATH exists, to match mlocate behavior.
969 dbpaths.push_back(DBFILE);
972 const char *locate_path = getenv("LOCATE_PATH");
973 if (locate_path != nullptr) {
974 parse_dbpaths(locate_path, &dbpaths);
977 uint64_t matched = 0;
978 for (size_t i = 0; i < dbpaths.size(); ++i) {
979 uint64_t this_matched;
980 if (i != dbpaths.size() - 1) {
981 this_matched = do_search_file_in_child(needles, dbpaths[i]);
983 this_matched = do_search_file(needles, dbpaths[i]);
985 matched += this_matched;
986 limit_left -= this_matched;
989 printf("%" PRId64 "\n", matched);