libcruft-util/exe_linux.cpp

44 lines
1.2 KiB
C++
Raw Normal View History

2016-10-10 16:23:07 +11:00
/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
2016-10-10 16:23:07 +11:00
*
* Copyright 2010-2016 Danny Robson <danny@nerdcruft.net>
*/
#include "exe.hpp"
2016-10-10 16:23:07 +11:00
#include "cast.hpp"
#include "posix/except.hpp"
2016-10-10 16:23:07 +11:00
#include <vector>
#include <filesystem>
2016-10-10 16:23:07 +11:00
#include <unistd.h>
///////////////////////////////////////////////////////////////////////////////
std::filesystem::path
cruft::image_path (void)
2016-10-10 16:23:07 +11:00
{
static const char PROC_SELF[] = "/proc/self/exe";
// We can't use lstat to check the size of the link in proc, as Linux
// will return 0 for most entries under proc. Instead we've got to
// iterate for a correct size.
std::vector<char> resolved (256);
retry:
const auto written = readlink (PROC_SELF, resolved.data (), resolved.size ());
if (written < 0)
posix::error::throw_code ();
2016-10-10 16:23:07 +11:00
if (cruft::cast::sign <size_t> (written) == resolved.size ()) {
2016-10-10 16:23:07 +11:00
resolved.resize (resolved.size () * 2);
goto retry;
}
return std::filesystem::path (resolved.data (), resolved.data () + written);
2016-10-10 16:23:07 +11:00
}