Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
Module.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include <cstdio>
7
8#if qStroika_Platform_Linux
9#include <link.h>
10#endif
11#if qStroika_Platform_MacOS
12#include <crt_externs.h>
13#include <libproc.h>
14#include <mach-o/dyld.h>
15#include <mach-o/loader.h>
16#endif
17#if qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
18#include <unistd.h>
19#endif
20#if qStroika_Platform_Windows
21#include <windows.h>
22#endif
23
25#include "Stroika/Foundation/Containers/Sequence.h"
27#include "Stroika/Foundation/Execution/Exceptions.h"
29#include "Stroika/Foundation/Execution/Throw.h"
31
32#include "Module.h"
33
34using namespace Stroika::Foundation;
37using namespace Stroika::Foundation::Execution;
38
39// Comment this in to turn on aggressive noisy DbgTrace in this module
40//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
41
42/*
43 ********************************************************************************
44 ***************************** Execution::GetEXEDir *****************************
45 ********************************************************************************
46 */
47filesystem::path Execution::GetEXEDir ()
48{
49 return GetEXEPath ().parent_path ();
50}
51
52/*
53 ********************************************************************************
54 **************************** Execution::GetEXEPath *****************************
55 ********************************************************************************
56 */
57filesystem::path Execution::GetEXEPath ()
58{
59// See also http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
60// Mac OS X: _NSGetExecutablePath() (man 3 dyld)
61// Linux: readlink /proc/self/exe
62// Solaris: getexecname()
63// FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
64// BSD with procfs: readlink /proc/curproc/file
65// Windows: GetModuleFileName() with hModule = nullptr
66//
67#if qStroika_Platform_MacOS
68 uint32_t bufSize = 0;
69 Verify (_NSGetExecutablePath (nullptr, &bufSize) == -1);
70 Assert (bufSize > 0);
71 Memory::StackBuffer<char> buf{Memory::eUninitialized, bufSize};
72 Verify (_NSGetExecutablePath (buf.begin (), &bufSize) == 0);
73 Assert (buf[bufSize - 1] == '\0');
74 return buf.begin ();
75#elif qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
76 // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is
77 // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that -
78 // double buf size and try again
79 Memory::StackBuffer<SDKChar> buf{Memory::eUninitialized, 1024};
80 ssize_t n;
81 while ((n = ::readlink ("/proc/self/exe", buf.data (), buf.GetSize ())) == buf.GetSize ()) {
82 buf.GrowToSize_uninitialized (buf.GetSize () * 2);
83 }
84 if (n < 0) {
85 ThrowPOSIXErrNo (errno);
86 }
87 Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed
88 return SDKString{buf.begin (), buf.begin () + n};
89#elif qStroika_Platform_Windows
90 SDKChar buf[MAX_PATH];
91 Verify (::GetModuleFileName (nullptr, buf, static_cast<DWORD> (std::size (buf))));
92 buf[std::size (buf) - 1] = '\0'; // cheaper and just as safe as memset() - more even. Buffer always nul-terminated, and if GetModuleFileName succeeds will be nul-terminated
93 return buf;
94#else
96 return filesystem::path{};
97#endif
98}
99
100/*
101 ********************************************************************************
102 ***************************** Execution::GetEXEPath ****************************
103 ********************************************************************************
104 */
105filesystem::path Execution::GetEXEPath ([[maybe_unused]] pid_t processID)
106{
107#if qStroika_Platform_MacOS
108 char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
109 int ret = ::proc_pidpath (processID, pathbuf, sizeof (pathbuf));
110 if (ret <= 0) {
111 Throw (Exception{"proc_pidpath failed"sv}); // @todo - horrible reporting, but not obvious what this API is? proc_pidpath?
112 }
113 else {
114 return pathbuf;
115 }
116#elif qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
117 // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is
118 // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that -
119 // double buf size and try again
120 Memory::StackBuffer<SDKChar> buf{Memory::eUninitialized, 1024};
121 ssize_t n;
122 char linkNameBuf[1024];
123 (void)std::snprintf (linkNameBuf, sizeof (linkNameBuf), "/proc/%ld/exe", static_cast<long> (processID));
124 while ((n = ::readlink (linkNameBuf, buf.data (), buf.GetSize ())) == buf.GetSize ()) {
125 buf.GrowToSize_uninitialized (buf.GetSize () * 2);
126 }
127 if (n < 0) {
128 ThrowPOSIXErrNo (errno);
129 }
130 Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed
131 return SDKString{buf.begin (), buf.begin () + n};
132#elif qStroika_Platform_Windows
133 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682621(v=vs.85).aspx but a bit of work
134 // not needed yet
136 return filesystem::path{};
137#else
139 return filesystem::path{};
140#endif
141}
142
143/*
144 ********************************************************************************
145 ****************** Execution::IsAddressReadOnlyAppLifetime *********************
146 ********************************************************************************
147 */
148namespace {
149 void AddRange_ (Execution::Private_::ReadOnlyImage_& r, uintptr_t start, uintptr_t end)
150 {
151 if (start < end and r.fCount < r.kMaxRanges) {
152 r.fRanges[r.fCount++] = {start, end};
153 }
154 }
155}
156
157const Execution::Private_::ReadOnlyImage_& Execution::Private_::GetReadOnlyImage_ ()
158{
159 static const ReadOnlyImage_ sImage_ = [] () {
160 ReadOnlyImage_ result;
161#if qStroika_Platform_Linux
162 // the first object dl_iterate_phdr reports is the main program: its loadable segments without write permission
163 ::dl_iterate_phdr (
164 [] (::dl_phdr_info* info, [[maybe_unused]] size_t size, void* data) -> int {
165 ReadOnlyImage_& r = *static_cast<ReadOnlyImage_*> (data);
166 for (size_t i = 0; i < info->dlpi_phnum; ++i) {
167 const ElfW (Phdr) & ph = info->dlpi_phdr[i];
168 if (ph.p_type == PT_LOAD and (ph.p_flags & PF_W) == 0) {
169 uintptr_t start = info->dlpi_addr + ph.p_vaddr;
170 AddRange_ (r, start, start + ph.p_memsz);
171 }
172 }
173 r.fKnown = true;
174 return 1; // stop after the first
175 },
176 &result);
177#elif qStroika_Platform_MacOS
178 // image 0 is the main executable: its segments readable but not writable from the start (__TEXT, with the literals)
179 const mach_header_64* header = reinterpret_cast<const mach_header_64*> (::_dyld_get_image_header (0));
180 if (header == nullptr or header->magic != MH_MAGIC_64) {
181 return result;
182 }
183 uintptr_t slide = static_cast<uintptr_t> (::_dyld_get_image_vmaddr_slide (0));
184 const load_command* lc = reinterpret_cast<const load_command*> (header + 1);
185 for (uint32_t i = 0; i < header->ncmds; ++i) {
186 if (lc->cmd == LC_SEGMENT_64) {
187 const segment_command_64* seg = reinterpret_cast<const segment_command_64*> (lc);
188 if ((seg->initprot & VM_PROT_READ) != 0 and (seg->initprot & VM_PROT_WRITE) == 0) {
189 AddRange_ (result, seg->vmaddr + slide, seg->vmaddr + slide + seg->vmsize);
190 }
191 }
192 lc = reinterpret_cast<const load_command*> (reinterpret_cast<const byte*> (lc) + lc->cmdsize);
193 }
194 result.fKnown = true;
195#elif qStroika_Platform_Windows
196 // the main executable's image: its sections readable but not writable (.rdata, with the literals, and .text) - nor
197 // discardable, which promises nothing about lasting
198 const byte* base = reinterpret_cast<const byte*> (::GetModuleHandleW (nullptr));
199 const IMAGE_DOS_HEADER* dos = reinterpret_cast<const IMAGE_DOS_HEADER*> (base);
200 if (base == nullptr or dos->e_magic != IMAGE_DOS_SIGNATURE) {
201 return result;
202 }
203 const IMAGE_NT_HEADERS* nt = reinterpret_cast<const IMAGE_NT_HEADERS*> (base + dos->e_lfanew);
204 if (nt->Signature != IMAGE_NT_SIGNATURE) {
205 return result;
206 }
207 const IMAGE_SECTION_HEADER* sections = IMAGE_FIRST_SECTION (nt);
208 for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
209 DWORD c = sections[i].Characteristics;
210 if ((c & IMAGE_SCN_MEM_READ) != 0 and (c & (IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_DISCARDABLE)) == 0) {
211 uintptr_t start = reinterpret_cast<uintptr_t> (base) + sections[i].VirtualAddress;
212 AddRange_ (result, start, start + sections[i].Misc.VirtualSize);
213 }
214 }
215 result.fKnown = true;
216#endif
217 // first the range a literal is in - and so the others, as a rule - so checking one takes one comparison
218 uintptr_t literal = reinterpret_cast<uintptr_t> ("a literal");
219 for (size_t i = 1; i < result.fCount; ++i) {
220 if (result.fRanges[i].first <= literal and literal < result.fRanges[i].second) {
221 swap (result.fRanges[0], result.fRanges[i]);
222 break;
223 }
224 }
225 return result;
226 }();
227 return sImage_;
228}
229
230/*
231 ********************************************************************************
232 ******************************** Execution::kPath ******************************
233 ********************************************************************************
234 */
237 if (const char* env_p = std::getenv ("PATH")) {
238 String pathVar = String::FromNarrowSDKString (env_p);
239#if qStroika_Platform_POSIX
240 return pathVar.Tokenize ({':'}).Map<Sequence<filesystem::path>> ([] (auto i) { return i.template As<filesystem::path> (); });
241#elif qStroika_Platform_Windows
242 return pathVar.Tokenize ({';'}).Map<Sequence<filesystem::path>> ([] (auto i) { return i.template As<filesystem::path> (); });
243#endif
244 }
245 DISABLE_COMPILER_MSC_WARNING_END (4996)
246 return {};
247}};
248
249#if qStroika_Platform_Windows
250/*
251 ********************************************************************************
252 ***************************** Execution::kPathEXT ******************************
253 ********************************************************************************
254 */
257 if (const char* env_p = std::getenv ("PATHEXT")) {
258 String pathVar = String::FromNarrowSDKString (env_p);
259 return pathVar.Tokenize ({';'}).Map<Sequence<filesystem::path>> ([] (auto i) { return i.template As<filesystem::path> (); });
260 }
261 DISABLE_COMPILER_MSC_WARNING_END (4996)
262 return {};
263}};
264#endif
265
266/*
267 ********************************************************************************
268 ************************ Execution::kRawEnvironment ****************************
269 ********************************************************************************
270 */
273 const SDKChar* const* envHead = nullptr;
274#if qStroika_Platform_Windows
275 // documented in https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getenv-wgetenv?view=msvc-170 can happen, and how to workaround
277 if constexpr (same_as<SDKChar, wchar_t>) {
278 if (_wenviron == nullptr) {
279 [[maybe_unused]] auto ignored = ::_wgetenv (L"PATH");
280 }
281 }
282 else {
283 if (environ == nullptr) {
284 [[maybe_unused]] auto ignored = ::getenv ("PATH");
285 }
286 }
287 DISABLE_COMPILER_MSC_WARNING_END (4996)
288#endif
289#if qStroika_Platform_Windows
290 if constexpr (same_as<SDKChar, wchar_t>) {
291 envHead = _wenviron;
292 }
293 else
294#endif
295 {
296#if qStroika_Platform_MacOS
297 envHead = (*_NSGetEnviron ());
298#else
299 envHead = environ;
300#endif
301 }
302 // NULL-terminated array of NUL-terminated strings
303 AssertNotNull (envHead);
304 for (const SDKChar* const* p = envHead; *p; ++p) {
305 SDKString eltStr = *p;
306 size_t i = eltStr.find ('=');
307 if (i == SDKString::npos) {
308 DbgTrace ("bad env elt: {}"_f, String::FromSDKString (eltStr));
310 }
311 else {
312 r.Add (eltStr.substr (0, i), eltStr.substr (i + 1));
313 }
314 }
315 return r;
316}};
317
318/*
319 ********************************************************************************
320 *************************** Execution::kEnvironment ****************************
321 ********************************************************************************
322 */
325 for (auto i : kRawEnvironment ()) {
326 r.Add (String::FromSDKString (i.fKey), String::FromSDKString (i.fValue));
327 }
328 return r;
329}};
330
331/*
332 ********************************************************************************
333 ********************** Execution::FindExecutableInPath *************************
334 ********************************************************************************
335 */
336optional<filesystem::path> Execution::FindExecutableInPath (const filesystem::path& fn)
337{
338 auto checkExists = [] (const filesystem::path& exe) {
339 // better to use 'access' api?
340 return filesystem::exists (exe) and filesystem::is_regular_file (exe) and
341 static_cast<bool> (filesystem::status (exe).permissions () & filesystem::perms::owner_exec);
342 };
343 if (fn.is_absolute ()) {
344 if (checkExists (fn)) {
345 return fn;
346 }
347#if qStroika_Platform_Windows
348 if (fn.extension ().empty ()) {
349 filesystem::path exe = fn;
350 for (auto exeExt : kPathEXT ()) {
351 exe.replace_extension (exeExt);
352 if (checkExists (exe)) {
353 return exe;
354 }
355 }
356 }
357#endif
358 }
359 else {
360 // if not absolute, try relative to each element of the path (and CWD? not for now??)
361 for (filesystem::path d : kPath ()) {
362 filesystem::path exe = d / fn;
363 if (checkExists (exe)) {
364 return exe;
365 }
366#if qStroika_Platform_Windows
367 if (fn.extension ().empty ()) {
368 for (auto exeExt : kPathEXT ()) {
369 exe.replace_extension (exeExt);
370 if (checkExists (exe)) {
371 return exe;
372 }
373 }
374 }
375#endif
376 }
377 }
378 return nullopt;
379}
#define AssertNotNull(p)
Definition Assertions.h:336
#define WeakAssertNotReached()
Definition Assertions.h:470
#define AssertNotImplemented()
Definition Assertions.h:404
#define Verify(c)
Definition Assertions.h:422
#define DbgTrace
Definition Trace.h:327
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
nonvirtual Containers::Sequence< String > Tokenize() const
Definition String.cpp:1293
A Mapping uniquely associates two elements: a key and a value (use Assocation to allow multiple value...
nonvirtual bool Add(ArgByValueType< key_type > key, ArgByValueType< mapped_type > newElt, AddReplaceMode addReplaceMode=AddReplaceMode::eAddReplaces)
Definition Mapping.inl:186
A generalization of a vector: a container whose elements are keyed by the natural numbers.
Exception<> is a replacement (subclass) for any std c++ exception class (e.g. the default 'std::excep...
Definition Exceptions.h:219
value-object, where the value construction is delayed until first needed (can be handy to avoid c++ i...
Logically halfway between std::array and std::vector; Smart 'direct memory array' - which when needed...
nonvirtual void GrowToSize_uninitialized(size_t nElements)
same as GrowToSize (), except leaves newly created elements uninitialized (requires is_trivially_copy...
basic_string< SDKChar > SDKString
Definition SDKString.h:38
conditional_t< qStroika_Foundation_Characters_SDKUseswchar_t, wchar_t, char > SDKChar
Definition SDKChar.h:77
void Throw(T &&e2Throw)
like the builtin C++ 'throw', but stamps in the current Activity context and does helpful,...
Definition Throw.inl:54
const LazyInitialized< Containers::Sequence< filesystem::path > > kPath
Definition Module.cpp:235
void ThrowPOSIXErrNo(errno_t errNo=errno)
treats argument errNo as a POSIX errno value, and calls ThrowError () with an error_code constructed ...
const LazyInitialized< Containers::Mapping< Characters::SDKString, Characters::SDKString > > kRawEnvironment
convert getenv() to a Mapping of SDKString (in case some issue with charactor set conversion)
Definition Module.cpp:271
filesystem::path GetEXEPath()
Definition Module.cpp:57
STL namespace.