File: process_name.cpp

package info (click to toggle)
apitrace 11.1%2Brepack-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 13,648 kB
  • sloc: cpp: 183,110; python: 33,685; ansic: 25,073; sh: 143; makefile: 88
file content (259 lines) | stat: -rw-r--r-- 8,196 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**************************************************************************
 *
 * Copyright 2017 VMware, Inc
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 **************************************************************************/

#include "process_name.hpp"

#include <assert.h>

#if defined(__linux__)
#include <features.h>  // __GLIBC__
#endif

#include <iostream>

#include "os.hpp"
#include "os_symbols.hpp"

#if defined(__GLIBC__)

#include <dlfcn.h>
#include <string.h>
#include <unistd.h>


// Must not use std::string to prevent it being destroyed.
static char g_processName[4097];

extern "C"  {


PUBLIC ssize_t
readlink(const char *pathname, char *buf, size_t bufsiz)
{
    /*
     * NOTE: Best to avoid std::cerr/cout as this fuction might be called
     * before libstdc++ has initialized.
     */
    unsigned long pid = 0;
    if (strcmp(pathname, "/proc/self/exe") == 0 ||
        (sscanf(pathname, "/proc/%lu/exe", &pid) == 1 &&
         pid == getpid())) {
        if (0) {
            std::string callerModule(getModuleFromAddress(ReturnAddress()));
            fprintf(stderr, "readlink(\"%s\") from %s\n", pathname, callerModule.c_str());
        }
        size_t len = strlen(g_processName);
        if (len) {
            if (len < bufsiz) {
                memcpy(buf, g_processName, len + 1);
                return len;
            } else {
                memcpy(buf, g_processName, bufsiz);
                return bufsiz;
            }
        } else {
            // FIXME: We need to defer retrace::setUp() until after the first trace is loaded.
            fprintf(stderr, "warning: process name not yet set\n");
            return -1;
        }
    }

    typedef ssize_t (*p_readlink)(const char *pathname, char *buf, size_t bufsiz);
    p_readlink p = (p_readlink)dlsym(RTLD_NEXT, "readlink");
    assert(p != nullptr);
    return p(pathname, buf, bufsiz);
}


} /* extern C */


void
setProcessName(const char *processName)
{
    strncpy(g_processName, processName, sizeof g_processName - 1);
    g_processName[sizeof g_processName - 1] = '\0';

    char **p__progname_full = (char **)dlsym(RTLD_DEFAULT, "__progname_full");
    if (p__progname_full == nullptr) {
        std::cerr << "error: failed to get address of __progname_full symbol" << std::endl;
        return;
    }

    char *progname_full = strdup(processName);
    assert(progname_full != nullptr);

    *p__progname_full = progname_full;

    char **p__progname = (char **)dlsym(RTLD_DEFAULT, "__progname");
    if (p__progname == nullptr) {
        std::cerr << "error: failed to get address of __progname symbol" << std::endl;
        return;
    }

    char *progname = strrchr(progname_full, '/');
    if (progname == nullptr) {
        progname = progname_full;
    } else {
        progname += 1;
    }

    *p__progname = progname;
}


#elif defined(_WIN32)

#include <windows.h>
#include "mhook.h"

typedef DWORD (WINAPI *PFNGETMODULEFILENAMEA)(HMODULE hModule, LPSTR lpFilename, DWORD nSize);
static PFNGETMODULEFILENAMEA pfnGetModuleFileNameA = &GetModuleFileNameA;

typedef DWORD (WINAPI *PFNGETMODULEFILENAMEW)(HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
static PFNGETMODULEFILENAMEW pfnGetModuleFileNameW = &GetModuleFileNameW;

static inline HMODULE
GetModuleFromAddress(PVOID pAddress)
{
    HMODULE hModule = nullptr;
    BOOL bRet = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                                  GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                  (LPCTSTR)pAddress,
                                  &hModule);
    return bRet ? hModule : nullptr;
}

static std::string g_processName;


static DWORD WINAPI
MyGetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize)
{
    if (hModule == nullptr) {
        if (0) {
            void *pCallerAddr = ReturnAddress();
            HMODULE hCallerModule = GetModuleFromAddress(pCallerAddr);
            char szCaller[MAX_PATH];
            DWORD dwRet = pfnGetModuleFileNameA(hCallerModule, szCaller, sizeof szCaller);
            assert(dwRet > 0);

            std::cerr << "GetModuleFileNameA(" << hModule << ") from " << szCaller << "\n";
        }

        assert(!g_processName.empty());
        assert(nSize != 0);

        size_t len = g_processName.length();
        if (len < nSize) {
            memcpy(lpFilename, g_processName.data(), len);
            lpFilename[len] = 0;
            SetLastError(ERROR_SUCCESS);
            return len;
        } else {
            memcpy(lpFilename, g_processName.data(), nSize - 1);
            lpFilename[nSize - 1] = 0;
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            return nSize;
        }
    }

    return pfnGetModuleFileNameA(hModule, lpFilename, nSize);
}

static DWORD WINAPI
MyGetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize)
{
    if (hModule == nullptr) {
        if (0) {
            void *pCallerAddr = ReturnAddress();
            HMODULE hCallerModule = GetModuleFromAddress(pCallerAddr);
            WCHAR szCaller[MAX_PATH];
            DWORD dwRet = pfnGetModuleFileNameW(hCallerModule, szCaller, sizeof szCaller);
            assert(dwRet > 0);

            std::cerr << "GetModuleFileNameW(" << hModule << ") from " << szCaller << "\n";
        }

        assert(!g_processName.empty());
        assert(nSize != 0);

        size_t len = g_processName.length();
        if (len < nSize) {
            ::MultiByteToWideChar(CP_UTF8, 0, g_processName.data(), -1, lpFilename, len);
            lpFilename[len] = 0;
            SetLastError(ERROR_SUCCESS);
            return len;
        } else {
            ::MultiByteToWideChar(CP_UTF8, 0, g_processName.data(), -1, lpFilename, nSize - 1);
            lpFilename[nSize - 1] = L'\0';
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            return nSize;
        }
    }

    return pfnGetModuleFileNameW(hModule, lpFilename, nSize);
}

void
setProcessName(const char *processName)
{
    g_processName = processName;

    static BOOL bHooked = FALSE;
    if (!bHooked) {
        bHooked = TRUE;

        LPVOID lpOrigAddress = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32"), "GetModuleFileNameA");
        if (lpOrigAddress) {
            LPVOID lpHookAddress = (LPVOID)&MyGetModuleFileNameA;
            LPVOID lpRealAddress = lpOrigAddress;
            if (!Mhook_SetHook(&lpRealAddress, lpHookAddress)) {
                std::cerr << "error: failed to GetModuleFileNameA\n";
            }
            pfnGetModuleFileNameA = (PFNGETMODULEFILENAMEA)lpRealAddress;
        }

        lpOrigAddress = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32"), "GetModuleFileNameW");
        if (lpOrigAddress) {
            LPVOID lpHookAddress = (LPVOID)&MyGetModuleFileNameW;
            LPVOID lpRealAddress = lpOrigAddress;
            if (!Mhook_SetHook(&lpRealAddress, lpHookAddress)) {
                std::cerr << "error: failed to GetModuleFileNameW\n";
            }
            pfnGetModuleFileNameW = (PFNGETMODULEFILENAMEW)lpRealAddress;
        }
    }
}


#else

void
setProcessName(const char *processName)
{
}

#endif