|
| 1 | +/* |
| 2 | + * Copyright (C) 2019 Waldemar Kozaczuk |
| 3 | + * |
| 4 | + * This work is open source software, licensed under the terms of the |
| 5 | + * BSD license as described in the LICENSE file in the top-level directory. |
| 6 | + */ |
| 7 | + |
| 8 | +#ifndef GETOPT_HH_ |
| 9 | +#define GETOPT_HH_ |
| 10 | + |
| 11 | +#include <osv/app.hh> |
| 12 | + |
| 13 | +// As explained in http://www.shrubbery.net/solaris9ab/SUNWdev/LLM/p22.html#CHAPTER4-84604 |
| 14 | +// newer versions of gcc produce position independent executables with copies of |
| 15 | +// some global variables like those used by getopt() and getopt_long() for optimizations reason. |
| 16 | +// In those circumstances the caller of these functions uses different copies of |
| 17 | +// global variables (like optind) than the getopt() code that is part of OSv kernel. |
| 18 | +// For that reason in the beginning of these functions we need to copy values of the caller |
| 19 | +// copies of those variables to the kernel placeholders. Likewise on every return from the function |
| 20 | +// we need to copy the values of kernel copies of global variables to the caller ones. |
| 21 | +// |
| 22 | +// See http://man7.org/linux/man-pages/man3/getopt.3.html |
| 23 | +// |
| 24 | +// This is a simple RAII class for retrieving the caller's copy of the global opt* variables |
| 25 | +// on initialization, and returning them back to the caller on destruction. |
| 26 | +class getopt_caller_vars_copier { |
| 27 | + std::shared_ptr<osv::application_runtime> _runtime; |
| 28 | + int *other_optind; |
| 29 | + |
| 30 | +public: |
| 31 | + getopt_caller_vars_copier() : _runtime(sched::thread::current()->app_runtime()) { |
| 32 | + if (_runtime) { |
| 33 | + auto obj = _runtime->app.lib(); |
| 34 | + other_optind = reinterpret_cast<int*>(obj->cached_lookup("optind")); |
| 35 | + if (other_optind) { |
| 36 | + optind = *other_optind; |
| 37 | + } |
| 38 | + |
| 39 | + auto other_opterr = reinterpret_cast<int*>(obj->cached_lookup("opterr")); |
| 40 | + if (other_opterr) { |
| 41 | + opterr = *other_opterr; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + ~getopt_caller_vars_copier() { |
| 47 | + if (_runtime) { |
| 48 | + auto obj = _runtime->app.lib(); |
| 49 | + if (other_optind) { |
| 50 | + *other_optind = optind; |
| 51 | + } |
| 52 | + auto other_optopt = reinterpret_cast<int*>(obj->cached_lookup("optopt")); |
| 53 | + if (other_optopt) { |
| 54 | + *other_optopt = optopt; |
| 55 | + } |
| 56 | + auto other_optarg = reinterpret_cast<char**>(obj->cached_lookup("optarg")); |
| 57 | + if (other_optarg) { |
| 58 | + *other_optarg = optarg; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +extern "C" int __getopt(int argc, char * const argv[], const char *optstring); |
| 65 | + |
| 66 | +#endif |
0 commit comments