1 /*****************************************************************************
2  *   Copyright 2012 - 2015 Yichao Yu <yyc1992@gmail.com>                     *
3  *                                                                           *
4  *   This program is free software; you can redistribute it and/or modify    *
5  *   it under the terms of the GNU Lesser General Public License as          *
6  *   published by the Free Software Foundation; either version 2.1 of the    *
7  *   License, or (at your option) version 3, or any later version accepted   *
8  *   by the membership of KDE e.V. (or its successor approved by the         *
9  *   membership of KDE e.V.), which shall act as a proxy defined in          *
10  *   Section 6 of version 3 of the license.                                  *
11  *                                                                           *
12  *   This program is distributed in the hope that it will be useful,         *
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of          *
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *
15  *   Lesser General Public License for more details.                         *
16  *                                                                           *
17  *   You should have received a copy of the GNU Lesser General Public        *
18  *   License along with this library. If not,                                *
19  *   see <http://www.gnu.org/licenses/>.                                     *
20  *****************************************************************************/
21 
22 #include "utils.h"
23 #include "strs.h"
24 
25 #include <config.h>
26 
27 #include <dlfcn.h>
28 
29 namespace QtCurve {
30 
31 QTC_EXPORT const char*
getProgName()32 getProgName()
33 {
34     static uniqueStr name = [] {
35         void *hdl = dlopen(nullptr, RTLD_NOW);
36         // I do not use the procfs here since any system that has procfs
37         // (Linux) should support one of these variables/functions.
38         if (!hdl) {
39             return strdup("");
40         }
41         void *progname_p = nullptr;
42         const char *name = nullptr;
43         if ((progname_p = dlsym(hdl, "program_invocation_short_name")) ||
44             (progname_p = dlsym(hdl, "program_invocation_name")) ||
45             (progname_p = dlsym(hdl, "__progname"))) {
46             name = *(char *const*)progname_p;
47         } else if ((progname_p = dlsym(hdl, "getprogname"))) {
48             name = ((const char *(*)())progname_p)();
49         }
50         if (!name) {
51             return strdup("");
52         }
53         const char *sub_name;
54         if ((sub_name = strrchr(name, '/')) && sub_name[1]) {
55             return strdup(sub_name + 1);
56         }
57         return strdup(name);
58     };
59     return name.get();
60 }
61 
62 }
63