4#include "Stroika/Foundation/StroikaPreComp.h"
8#if qStroika_Platform_Linux
11#if qStroika_Platform_MacOS
12#include <crt_externs.h>
14#include <mach-o/dyld.h>
15#include <mach-o/loader.h>
17#if qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
20#if qStroika_Platform_Windows
25#include "Stroika/Foundation/Containers/Sequence.h"
27#include "Stroika/Foundation/Execution/Exceptions.h"
29#include "Stroika/Foundation/Execution/Throw.h"
47filesystem::path Execution::GetEXEDir ()
57filesystem::path Execution::GetEXEPath ()
67#if qStroika_Platform_MacOS
69 Verify (_NSGetExecutablePath (
nullptr, &bufSize) == -1);
72 Verify (_NSGetExecutablePath (buf.begin (), &bufSize) == 0);
73 Assert (buf[bufSize - 1] ==
'\0');
75#elif qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
81 while ((n = ::readlink (
"/proc/self/exe", buf.data (), buf.GetSize ())) == buf.GetSize ()) {
87 Assert (n <= buf.GetSize ());
88 return SDKString{buf.begin (), buf.begin () + n};
89#elif qStroika_Platform_Windows
91 Verify (::GetModuleFileName (
nullptr, buf,
static_cast<DWORD
> (std::size (buf))));
92 buf[std::size (buf) - 1] =
'\0';
96 return filesystem::path{};
105filesystem::path Execution::GetEXEPath ([[maybe_unused]] pid_t processID)
107#if qStroika_Platform_MacOS
108 char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
109 int ret = ::proc_pidpath (processID, pathbuf,
sizeof (pathbuf));
116#elif qStroika_Platform_POSIX && qStroika_FeatureSupported_ProcFilesystem
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 ()) {
130 Assert (n <= buf.GetSize ());
131 return SDKString{buf.begin (), buf.begin () + n};
132#elif qStroika_Platform_Windows
136 return filesystem::path{};
139 return filesystem::path{};
149 void AddRange_ (Execution::Private_::ReadOnlyImage_& r, uintptr_t start, uintptr_t end)
151 if (start < end and r.fCount < r.kMaxRanges) {
152 r.fRanges[r.fCount++] = {start, end};
157const Execution::Private_::ReadOnlyImage_& Execution::Private_::GetReadOnlyImage_ ()
159 static const ReadOnlyImage_ sImage_ = [] () {
160 ReadOnlyImage_ result;
161#if qStroika_Platform_Linux
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);
177#elif qStroika_Platform_MacOS
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) {
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);
192 lc =
reinterpret_cast<const load_command*
> (
reinterpret_cast<const byte*
> (lc) + lc->cmdsize);
194 result.fKnown =
true;
195#elif qStroika_Platform_Windows
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) {
203 const IMAGE_NT_HEADERS* nt =
reinterpret_cast<const IMAGE_NT_HEADERS*
> (base + dos->e_lfanew);
204 if (nt->Signature != IMAGE_NT_SIGNATURE) {
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);
215 result.fKnown =
true;
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]);
237 if (
const char* env_p = std::getenv (
"PATH")) {
238 String pathVar = String::FromNarrowSDKString (env_p);
239#if qStroika_Platform_POSIX
241#elif qStroika_Platform_Windows
245 DISABLE_COMPILER_MSC_WARNING_END (4996)
249#if qStroika_Platform_Windows
257 if (const
char* env_p =
std::getenv ("PATHEXT")) {
258 String pathVar = String::FromNarrowSDKString (env_p);
261 DISABLE_COMPILER_MSC_WARNING_END (4996)
273 const SDKChar*
const* envHead =
nullptr;
274#if qStroika_Platform_Windows
277 if constexpr (same_as<SDKChar, wchar_t>) {
278 if (_wenviron ==
nullptr) {
279 [[maybe_unused]]
auto ignored = ::_wgetenv (L
"PATH");
283 if (environ ==
nullptr) {
284 [[maybe_unused]]
auto ignored = ::getenv (
"PATH");
287 DISABLE_COMPILER_MSC_WARNING_END (4996)
289#if qStroika_Platform_Windows
290 if constexpr (same_as<SDKChar, wchar_t>) {
296#if qStroika_Platform_MacOS
297 envHead = (*_NSGetEnviron ());
304 for (
const SDKChar*
const* p = envHead; *p; ++p) {
306 size_t i = eltStr.find (
'=');
307 if (i == SDKString::npos) {
308 DbgTrace (
"bad env elt: {}"_f, String::FromSDKString (eltStr));
312 r.
Add (eltStr.substr (0, i), eltStr.substr (i + 1));
326 r.
Add (String::FromSDKString (i.fKey), String::FromSDKString (i.fValue));
336optional<filesystem::path> Execution::FindExecutableInPath (
const filesystem::path& fn)
338 auto checkExists = [] (
const filesystem::path& exe) {
340 return filesystem::exists (exe) and filesystem::is_regular_file (exe) and
341 static_cast<bool> (filesystem::status (exe).permissions () & filesystem::perms::owner_exec);
343 if (fn.is_absolute ()) {
344 if (checkExists (fn)) {
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)) {
361 for (filesystem::path d :
kPath ()) {
362 filesystem::path exe = d / fn;
363 if (checkExists (exe)) {
366#if qStroika_Platform_Windows
367 if (fn.extension ().empty ()) {
368 for (
auto exeExt : kPathEXT ()) {
369 exe.replace_extension (exeExt);
370 if (checkExists (exe)) {
#define WeakAssertNotReached()
#define AssertNotImplemented()
String is like std::u32string, except it is much easier to use, often much more space efficient,...
nonvirtual Containers::Sequence< String > Tokenize() const
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)
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...
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
DISABLE_COMPILER_MSC_WARNING_START(4996)
conditional_t< qStroika_Foundation_Characters_SDKUseswchar_t, wchar_t, char > SDKChar
void Throw(T &&e2Throw)
like the builtin C++ 'throw', but stamps in the current Activity context and does helpful,...
const LazyInitialized< Containers::Sequence< filesystem::path > > kPath
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)
filesystem::path GetEXEPath()