]> git.sesse.net Git - plocate/blob - plocate.cpp
Write new --help text from scratch, so that we have nothing from mlocate except some...
[plocate] / plocate.cpp
1 #include "db.h"
2 #include "io_uring_engine.h"
3 #include "parse_trigrams.h"
4 #include "turbopfor.h"
5 #include "unique_sort.h"
6
7 #include <algorithm>
8 #include <assert.h>
9 #include <chrono>
10 #include <fcntl.h>
11 #include <fnmatch.h>
12 #include <functional>
13 #include <getopt.h>
14 #include <iosfwd>
15 #include <iterator>
16 #include <limits>
17 #include <memory>
18 #include <queue>
19 #include <regex.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <string>
25 #include <string_view>
26 #include <unistd.h>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <utility>
30 #include <vector>
31 #include <zstd.h>
32
33 using namespace std;
34 using namespace std::chrono;
35
36 #define dprintf(...) \
37         do { \
38                 if (use_debug) { \
39                         fprintf(stderr, __VA_ARGS__); \
40                 } \
41         } while (false)
42
43 #define DEFAULT_DBPATH "/var/lib/mlocate/plocate.db"
44
45 const char *dbpath = DEFAULT_DBPATH;
46 bool ignore_case = false;
47 bool only_count = false;
48 bool print_nul = false;
49 bool use_debug = false;
50 int64_t limit_matches = numeric_limits<int64_t>::max();
51
52 class Serializer {
53 public:
54         bool ready_to_print(int seq) { return next_seq == seq; }
55         void print_delayed(int seq, const vector<string> msg);
56         void release_current();
57
58 private:
59         int next_seq = 0;
60         struct Element {
61                 int seq;
62                 vector<string> msg;
63
64                 bool operator<(const Element &other) const
65                 {
66                         return seq > other.seq;
67                 }
68         };
69         priority_queue<Element> pending;
70 };
71
72 void Serializer::print_delayed(int seq, const vector<string> msg)
73 {
74         pending.push(Element{ seq, move(msg) });
75 }
76
77 void Serializer::release_current()
78 {
79         ++next_seq;
80
81         // See if any delayed prints can now be dealt with.
82         while (!pending.empty() && pending.top().seq == next_seq) {
83                 if (limit_matches-- <= 0)
84                         return;
85                 for (const string &msg : pending.top().msg) {
86                         if (print_nul) {
87                                 printf("%s%c", msg.c_str(), 0);
88                         } else {
89                                 printf("%s\n", msg.c_str());
90                         }
91                 }
92                 pending.pop();
93                 ++next_seq;
94         }
95 }
96
97 struct Needle {
98         enum { STRSTR,
99                REGEX,  // Not currently used.
100                GLOB } type;
101         string str;  // Filled in no matter what.
102         regex_t re;  // For REGEX.
103 };
104
105 bool matches(const Needle &needle, const char *haystack)
106 {
107         if (needle.type == Needle::STRSTR) {
108                 return strstr(haystack, needle.str.c_str()) != nullptr;
109         } else if (needle.type == Needle::GLOB) {
110                 int flags = ignore_case ? FNM_CASEFOLD : 0;
111                 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
112         } else {
113                 assert(needle.type == Needle::REGEX);
114                 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
115         }
116 }
117
118 bool has_access(const char *filename,
119                 unordered_map<string, bool> *access_rx_cache)
120 {
121         const char *end = strchr(filename + 1, '/');
122         while (end != nullptr) {
123                 string parent_path(filename, end);
124                 auto it = access_rx_cache->find(parent_path);
125                 bool ok;
126                 if (it == access_rx_cache->end()) {
127                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
128                         access_rx_cache->emplace(move(parent_path), ok);
129                 } else {
130                         ok = it->second;
131                 }
132                 if (!ok) {
133                         return false;
134                 }
135                 end = strchr(end + 1, '/');
136         }
137
138         return true;
139 }
140
141 class Corpus {
142 public:
143         Corpus(int fd, IOUringEngine *engine);
144         ~Corpus();
145         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
146         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
147         size_t get_num_filename_blocks() const;
148         off_t offset_for_block(uint32_t docid) const
149         {
150                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
151         }
152
153 public:
154         const int fd;
155         IOUringEngine *const engine;
156
157         Header hdr;
158 };
159
160 Corpus::Corpus(int fd, IOUringEngine *engine)
161         : fd(fd), engine(engine)
162 {
163         // Enable to test cold-cache behavior (except for access()).
164         if (false) {
165                 off_t len = lseek(fd, 0, SEEK_END);
166                 if (len == -1) {
167                         perror("lseek");
168                         exit(1);
169                 }
170                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
171         }
172
173         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
174         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
175                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
176                 exit(1);
177         }
178         if (hdr.version != 0) {
179                 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
180                 exit(1);
181         }
182 }
183
184 Corpus::~Corpus()
185 {
186         close(fd);
187 }
188
189 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
190 {
191         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
192         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) {
193                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
194                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
195                         if (trgmptr[i].trgm == trgm) {
196                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
197                                 return;
198                         }
199                 }
200
201                 // Not found.
202                 cb(nullptr, 0);
203         });
204 }
205
206 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
207 {
208         // Read the file offset from this docid and the next one.
209         // This is always allowed, since we have a sentinel block at the end.
210         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
211                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
212                 off_t offset = ptr[0];
213                 size_t len = ptr[1] - ptr[0];
214                 engine->submit_read(fd, len, offset, cb);
215         });
216 }
217
218 size_t Corpus::get_num_filename_blocks() const
219 {
220         return hdr.num_docids;
221 }
222
223 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
224                          unordered_map<string, bool> *access_rx_cache, int seq,
225                          Serializer *serializer)
226 {
227         uint64_t matched = 0;
228
229         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
230         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
231                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
232                 exit(1);
233         }
234
235         string block;
236         block.resize(uncompressed_len + 1);
237
238         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
239                                      compressed.size());
240         if (ZSTD_isError(err)) {
241                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
242                 exit(1);
243         }
244         block[block.size() - 1] = '\0';
245
246         bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
247         vector<string> delayed;
248
249         for (const char *filename = block.data();
250              filename != block.data() + block.size();
251              filename += strlen(filename) + 1) {
252                 bool found = true;
253                 for (const Needle &needle : needles) {
254                         if (!matches(needle, filename)) {
255                                 found = false;
256                                 break;
257                         }
258                 }
259                 if (found && has_access(filename, access_rx_cache)) {
260                         if (limit_matches-- <= 0)
261                                 break;
262                         ++matched;
263                         if (only_count)
264                                 continue;
265                         if (immediate_print) {
266                                 if (print_nul) {
267                                         printf("%s%c", filename, 0);
268                                 } else {
269                                         printf("%s\n", filename);
270                                 }
271                         } else {
272                                 delayed.push_back(filename);
273                         }
274                 }
275         }
276         if (serializer != nullptr && !only_count) {
277                 if (immediate_print) {
278                         serializer->release_current();
279                 } else {
280                         serializer->print_delayed(seq, move(delayed));
281                 }
282         }
283         return matched;
284 }
285
286 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
287 {
288         Serializer docids_in_order;
289         unordered_map<string, bool> access_rx_cache;
290         uint64_t matched = 0;
291         for (size_t i = 0; i < docids.size(); ++i) {
292                 uint32_t docid = docids[i];
293                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
294                         matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
295                 });
296         }
297         engine->finish();
298         return matched;
299 }
300
301 // We do this sequentially, as it's faster than scattering
302 // a lot of I/O through io_uring and hoping the kernel will
303 // coalesce it plus readahead for us.
304 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
305 {
306         unordered_map<string, bool> access_rx_cache;
307         uint32_t num_blocks = corpus.get_num_filename_blocks();
308         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
309         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
310         string compressed;
311         uint64_t matched = 0;
312         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
313                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
314                 size_t io_len = offsets[last_docid] - offsets[io_docid];
315                 if (compressed.size() < io_len) {
316                         compressed.resize(io_len);
317                 }
318                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
319
320                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
321                         size_t relative_offset = offsets[docid] - offsets[io_docid];
322                         size_t len = offsets[docid + 1] - offsets[docid];
323                         matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
324                         if (limit_matches <= 0)
325                                 return matched;
326                 }
327         }
328         return matched;
329 }
330
331 // Takes the given posting list, unions it into the parts of the trigram disjunction
332 // already read; if the list is complete, intersects with “cur_candidates”.
333 //
334 // Returns true if the search should be aborted (we are done).
335 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
336 {
337         if (td->docids.empty()) {
338                 td->docids = move(decoded);
339         } else {
340                 tmp->clear();
341                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
342                 swap(*tmp, td->docids);
343         }
344         if (--td->remaining_trigrams_to_read > 0) {
345                 // Need to wait for more.
346                 if (ignore_case) {
347                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
348                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
349                 }
350                 return false;
351         }
352         if (cur_candidates->empty()) {
353                 if (ignore_case) {
354                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
355                                 td->index, td->docids.size());
356                 }
357                 *cur_candidates = move(td->docids);
358         } else {
359                 tmp->clear();
360                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
361                                  td->docids.begin(), td->docids.end(),
362                                  back_inserter(*tmp));
363                 swap(*cur_candidates, *tmp);
364                 if (ignore_case) {
365                         if (cur_candidates->empty()) {
366                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
367                                         td->index, td->docids.size());
368                                 return true;
369                         } else {
370                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
371                                         td->index, td->docids.size(), cur_candidates->size());
372                         }
373                 }
374         }
375         return false;
376 }
377
378 void do_search_file(const vector<Needle> &needles, const char *filename)
379 {
380         int fd = open(filename, O_RDONLY);
381         if (fd == -1) {
382                 perror(filename);
383                 exit(1);
384         }
385
386         // Drop privileges.
387         if (setgid(getgid()) != 0) {
388                 perror("setgid");
389                 exit(EXIT_FAILURE);
390         }
391
392         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
393         if (access("/", R_OK | X_OK)) {
394                 // We can't find anything, no need to bother...
395                 return;
396         }
397
398         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
399         Corpus corpus(fd, &engine);
400         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
401
402         vector<TrigramDisjunction> trigram_groups;
403         for (const Needle &needle : needles) {
404                 if (needle.str.size() < 3)
405                         continue;
406                 parse_trigrams(needle.str, ignore_case, &trigram_groups);
407         }
408         unique_sort(
409                 &trigram_groups,
410                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
411                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
412
413         // Give them names for debugging.
414         unsigned td_index = 0;
415         for (TrigramDisjunction &td : trigram_groups) {
416                 td.index = td_index++;
417         }
418
419         // Collect which trigrams we need to look up in the hash table.
420         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
421         for (TrigramDisjunction &td : trigram_groups) {
422                 for (uint32_t trgm : td.trigram_alternatives) {
423                         trigrams_to_lookup[trgm].push_back(&td);
424                 }
425         }
426         if (trigrams_to_lookup.empty()) {
427                 // Too short for trigram matching. Apply brute force.
428                 // (We could have searched through all trigrams that matched
429                 // the pattern and done a union of them, but that's a lot of
430                 // work for fairly unclear gain.)
431                 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
432                 if (only_count) {
433                         printf("%zu\n", matched);
434                 }
435                 return;
436         }
437
438         // Look them all up on disk.
439         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
440                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
441                         if (trgmptr == nullptr) {
442                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
443                                 for (TrigramDisjunction *td : *trigram_groups) {
444                                         --td->remaining_trigrams_to_read;
445                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
446                                                 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
447                                                 if (only_count) {
448                                                         printf("0\n");
449                                                 }
450                                                 exit(0);
451                                         }
452                                 }
453                                 return;
454                         }
455                         for (TrigramDisjunction *td : *trigram_groups) {
456                                 --td->remaining_trigrams_to_read;
457                                 td->max_num_docids += trgmptr->num_docids;
458                                 td->read_trigrams.emplace_back(*trgmptr, len);
459                         }
460                 });
461         }
462         engine.finish();
463         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
464
465         for (TrigramDisjunction &td : trigram_groups) {
466                 // Reset for reads.
467                 td.remaining_trigrams_to_read = td.read_trigrams.size();
468
469                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
470                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
471                 }
472         }
473
474         // TODO: For case-insensitive (ie. more than one alternative in each),
475         // prioritize the ones with fewer seeks?
476         sort(trigram_groups.begin(), trigram_groups.end(),
477              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
478                      return a.max_num_docids < b.max_num_docids;
479              });
480
481         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
482         for (TrigramDisjunction &td : trigram_groups) {
483                 for (uint32_t trgm : td.trigram_alternatives) {
484                         uses_trigram[trgm].push_back(&td);
485                 }
486         }
487
488         unordered_set<uint32_t> trigrams_submitted_read;
489         vector<uint32_t> cur_candidates, tmp, decoded;
490         bool done = false;
491         for (TrigramDisjunction &td : trigram_groups) {
492                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
493                         dprintf("%s has up to %u entries, ignoring the rest (will "
494                                 "weed out false positives later)\n",
495                                 print_td(td).c_str(), td.max_num_docids);
496                         break;
497                 }
498
499                 for (auto &[trgmptr, len] : td.read_trigrams) {
500                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
501                                 continue;
502                         }
503                         trigrams_submitted_read.insert(trgmptr.trgm);
504                         // Only stay a certain amount ahead, so that we don't spend I/O
505                         // on reading the latter, large posting lists. We are unlikely
506                         // to need them anyway, even if they should come in first.
507                         if (engine.get_waiting_reads() >= 5) {
508                                 engine.finish();
509                                 if (done)
510                                         break;
511                         }
512                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
513                                 if (done)
514                                         return;
515
516                                 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
517                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
518                                 size_t num = trgmptr.num_docids;
519                                 decoded.resize(num);
520                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
521
522                                 assert(uses_trigram.count(trgm) != 0);
523                                 bool was_empty = cur_candidates.empty();
524                                 if (ignore_case) {
525                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
526                                 }
527
528                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
529                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
530                                         if (done)
531                                                 break;
532                                 }
533                                 if (!ignore_case) {
534                                         if (was_empty) {
535                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
536                                         } else if (cur_candidates.empty()) {
537                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
538                                         } else {
539                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
540                                         }
541                                 }
542                         });
543                 }
544         }
545         engine.finish();
546         if (done) {
547                 return;
548         }
549         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
550                 1e3 * duration<float>(steady_clock::now() - start).count());
551
552         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
553         dprintf("Done in %.1f ms, found %zu matches.\n",
554                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
555
556         if (only_count) {
557                 printf("%zu\n", matched);
558         }
559 }
560
561 string unescape_glob_to_plain_string(const string &needle)
562 {
563         string unescaped;
564         for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
565                 uint32_t ch = read_unigram(needle, i).first;
566                 assert(ch != WILDCARD_UNIGRAM);
567                 if (ch == PREMATURE_END_UNIGRAM) {
568                         fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
569                         exit(1);
570                 }
571                 unescaped.push_back(ch);
572         }
573         return unescaped;
574 }
575
576 void usage()
577 {
578         printf(
579                 "Usage: plocate [OPTION]... PATTERN...\n"
580                 "\n"
581                 "  -c, --count            print number of matches instead of the matches\n"
582                 "  -d, --database DBPATH  search for files in DBPATH\n"
583                 "                         (default is " DEFAULT_DBPATH ")\n"
584                 "  -i, --ignore-case      search case-insensitively\n"
585                 "  -l, --limit LIMIT      stop after LIMIT matches\n"
586                 "  -0, --null             delimit matches by NUL instead of newline\n"
587                 "      --help             print this help\n"
588                 "      --version          print version information\n");
589 }
590
591 void version()
592 {
593         printf("plocate %s\n", PLOCATE_VERSION);
594         printf("Copyright 2020 Steinar H. Gunderson\n");
595         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
596         printf("This is free software: you are free to change and redistribute it.\n");
597         printf("There is NO WARRANTY, to the extent permitted by law.\n");
598         exit(0);
599 }
600
601 int main(int argc, char **argv)
602 {
603         static const struct option long_options[] = {
604                 { "help", no_argument, 0, 'h' },
605                 { "count", no_argument, 0, 'c' },
606                 { "database", required_argument, 0, 'd' },
607                 { "ignore-case", no_argument, 0, 'i' },
608                 { "limit", required_argument, 0, 'l' },
609                 { "null", no_argument, 0, '0' },
610                 { "version", no_argument, 0, 'V' },
611                 { "debug", no_argument, 0, 'D' },  // Not documented.
612                 { 0, 0, 0, 0 }
613         };
614
615         setlocale(LC_ALL, "");
616         for (;;) {
617                 int option_index = 0;
618                 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
619                 if (c == -1) {
620                         break;
621                 }
622                 switch (c) {
623                 case 'c':
624                         only_count = true;
625                         break;
626                 case 'd':
627                         dbpath = strdup(optarg);
628                         break;
629                 case 'h':
630                         usage();
631                         exit(0);
632                 case 'i':
633                         ignore_case = true;
634                         break;
635                 case 'l':
636                 case 'n':
637                         limit_matches = atoll(optarg);
638                         break;
639                 case '0':
640                         print_nul = true;
641                         break;
642                 case 'D':
643                         use_debug = true;
644                         break;
645                 case 'V':
646                         version();
647                         break;
648                 default:
649                         exit(1);
650                 }
651         }
652
653         if (use_debug) {
654                 // Debug information would leak information about which files exist,
655                 // so drop setgid before we open the file; one would either need to run
656                 // as root, or use a locally-built file.
657                 if (setgid(getgid()) != 0) {
658                         perror("setgid");
659                         exit(EXIT_FAILURE);
660                 }
661         }
662
663         vector<Needle> needles;
664         for (int i = optind; i < argc; ++i) {
665                 Needle needle;
666                 needle.str = argv[i];
667
668                 // See if there are any wildcard characters, which indicates we should treat it
669                 // as an (anchored) glob.
670                 bool any_wildcard = false;
671                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
672                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
673                                 any_wildcard = true;
674                                 break;
675                         }
676                 }
677
678                 if (any_wildcard) {
679                         needle.type = Needle::GLOB;
680                 } else if (ignore_case) {
681                         // strcasestr() doesn't handle locales correctly (even though LSB
682                         // claims it should), but somehow, fnmatch() does, and it's about
683                         // the same speed as using a regex.
684                         needle.type = Needle::GLOB;
685                         needle.str = "*" + needle.str + "*";
686                 } else {
687                         needle.type = Needle::STRSTR;
688                         needle.str = unescape_glob_to_plain_string(needle.str);
689                 }
690                 needles.push_back(move(needle));
691         }
692         if (needles.empty()) {
693                 fprintf(stderr, "plocate: no pattern to search for specified\n");
694                 exit(0);
695         }
696         do_search_file(needles, dbpath);
697 }