summaryrefslogtreecommitdiffstats
path: root/src/monitor-lib/processreader.cpp
blob: b89e9b3cb968ed1e480ad2e9fe12751bd389a3d9 (plain)
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Luxoft Application Manager.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/

#include "processreader.h"

#include "logging.h"

#if defined(Q_OS_MACOS)
#  include <mach/mach.h>
#elif defined(Q_OS_LINUX)
#  include <unistd.h>
#endif

namespace {
    static uint parseValue(const char *pl) {
        while (*pl && (*pl < '0' || *pl > '9'))
            pl++;
        return static_cast<uint>(strtoul(pl, nullptr, 10));
    }
}

QT_USE_NAMESPACE_AM

void ProcessReader::setProcessId(qint64 pid)
{
    m_pid = pid;
    if (pid)
        openCpuLoad();
}

void ProcessReader::update()
{
    // read cpu
    {
        qreal cpuLoadFloat = readCpuLoad();
        quint32 value = ((qreal)std::numeric_limits<quint32>::max()) * cpuLoadFloat;
        cpuLoad.store(value);
    }

    {
        if (!readMemory()) {
            totalVm.store(0);
            totalRss.store(0);
            totalPss.store(0);
            textVm.store(0);
            textRss.store(0);
            textPss.store(0);
            heapVm.store(0);
            heapRss.store(0);
            heapPss.store(0);
        }
    }

    emit updated();
}

#if defined(Q_OS_LINUX)

void ProcessReader::openCpuLoad()
{
    const QByteArray fileName = "/proc/" + QByteArray::number(m_pid) + "/stat";
    m_statReader.reset(new SysFsReader(fileName));
    if (!m_statReader->isOpen())
        qCWarning(LogSystem) << "Cannot read CPU load from" << fileName;
}

qreal ProcessReader::readCpuLoad()
{
    qint64 elapsed;
    if (m_elapsedTime.isValid()) {
        elapsed = m_elapsedTime.restart();
    } else {
        elapsed = 0;
        m_elapsedTime.start();
    }

    if (m_statReader.isNull() || !m_statReader->isOpen()) {
        m_lastCpuUsage = 0.0;
        return 0.0;
    }

    QByteArray str = m_statReader->readValue();
    int pos = 0;
    int blanks = 0;
    while (pos < str.size() && blanks < 13) {
        if (isblank(str.at(pos)))
            ++blanks;
        ++pos;
    }

    char *endPtr = nullptr;
    quint64 utime = strtoull(str.constData() + pos, &endPtr, 10); // check missing for overflow
    pos = int(endPtr - str.constData() + 1);
    quint64 stime = strtoull(str.constData() + pos, nullptr, 10); // check missing for overflow

    qreal load = elapsed != 0 ? (utime + stime - m_lastCpuUsage) * 1000.0 / sysconf(_SC_CLK_TCK) / elapsed : 0.0;
    m_lastCpuUsage = utime + stime;
    return load;
}


bool ProcessReader::readMemory()
{
    QByteArray smapsFile = "/proc/" + QByteArray::number(m_pid) + "/smaps";
    return readSmaps(smapsFile);
}

bool ProcessReader::readSmaps(const QByteArray &smapsFile)
{
    quint32 _totalVm = 0;
    quint32 _totalRss = 0;
    quint32 _totalPss = 0;
    quint32 _textVm = 0;
    quint32 _textRss = 0;
    quint32 _textPss = 0;
    quint32 _heapVm = 0;
    quint32 _heapRss = 0;
    quint32 _heapPss = 0;

    struct ScopedFile {
        ~ScopedFile() { if (file) fclose(file); }
        FILE *file = nullptr;
    };

    ScopedFile sf;
    sf.file = fopen(smapsFile.constData(), "r");

    if (sf.file == nullptr)
        return false;

    const int lineLen = 100;  // we are not interested in full library paths
    char line[lineLen + 5];   // padding for highly unlikely trailing perm flags below
    char *pl;                 // pointer to chars within line
    bool ok = true;

    if (fgets(line, lineLen, sf.file) == nullptr)
        return false;

    // sanity checks
    pl = line;
    for (pl = line; pl < (line + 4) && ok; ++pl)
        ok = ((*pl >= '0' && *pl <= '9') || (*pl >= 'a' && *pl <= 'f'));
    while (strlen(line) == lineLen - 1 && line[lineLen - 2] != '\n') {
        if (Q_UNLIKELY(!fgets(line, lineLen, sf.file)))
            break;
    }
    if (fgets(line, lineLen, sf.file) == nullptr)
        return false;
    static const char strSize[] = "Size: ";
    ok = ok && !qstrncmp(line, strSize, sizeof(strSize) - 1);
    if (!ok)
        return false;

    // Determine block size
    ok = false;
    int blockLen = 0;
    while (fgets(line, lineLen, sf.file) != nullptr && !ok) {
        if (!(line[0] < '0' || line[0] > '9') && (line[0] < 'a' || line[0] > 'f'))
            ok = true;
        ++blockLen;
    }
    if (!ok || blockLen < 12 || blockLen > 32)
        return false;

    fseek(sf.file, 0, SEEK_SET);
    bool wasPrivateOnly = false;
    ok = false;

    while (true) {
        if (Q_UNLIKELY(!(fgets(line, lineLen, sf.file) != nullptr))) {
            ok = feof(sf.file);
            break;
        }

        // Determine permission flags
        pl = line;
        while (*pl && *pl != ' ')
            ++pl;
        char permissions[4];
        memcpy(permissions, ++pl, sizeof(permissions));

        // Determine inode
        int spaceCount = 0;
        while (*pl && spaceCount < 3) {
            if (*pl == ' ')
                ++spaceCount;
            ++pl;
        }
        bool hasInode = (*pl != '0');

        // Determine library name
        while (*pl && *pl != ' ')
            ++pl;
        while (*pl && *pl == ' ')
            ++pl;

        static const char strStack[] = "stack]";
        bool isMainStack = (Q_UNLIKELY(*pl == '['
                            && !qstrncmp(pl + 1, strStack, sizeof(strStack) - 1)));
        // Skip rest of library path
        while (strlen(line) == lineLen - 1 && line[lineLen - 2] != '\n') {
            if (Q_UNLIKELY(!fgets(line, lineLen, sf.file)))
                break;
        }

        int skipLen = blockLen;
        uint vm = 0;
        uint rss = 0;
        uint pss = 0;
        const int sizeTag = 0x01;
        const int rssTag  = 0x02;
        const int pssTag  = 0x04;
        const int allTags = sizeTag | rssTag | pssTag;
        int foundTags = 0;

        while (foundTags < allTags && skipLen > 0) {
            skipLen--;
            if (Q_UNLIKELY(!fgets(line, lineLen, sf.file)))
                break;
            pl = line;

            static const char strSize[] = "ize:";
            static const char strXss[] = "ss:";

            switch (*pl) {
            case 'S':
                if (!qstrncmp(pl + 1, strSize, sizeof(strSize) - 1)) {
                    foundTags |= sizeTag;
                    vm = parseValue(pl + sizeof(strSize));
                }
                break;
            case 'R':
                if (!qstrncmp(pl + 1, strXss, sizeof(strXss) - 1)) {
                    foundTags |= rssTag;
                    rss = parseValue(pl + sizeof(strXss));
                }
                break;
            case 'P':
                if (!qstrncmp(pl + 1, strXss, sizeof(strXss) - 1)) {
                    foundTags |= pssTag;
                    pss = parseValue(pl + sizeof(strXss));
                }
                break;
            }
        }

        if (foundTags < allTags)
            break;

        _totalVm += vm;
        _totalRss += rss;
        _totalPss += pss;

        static const char permRXP[] = { 'r', '-', 'x', 'p' };
        static const char permRWP[] = { 'r', 'w', '-', 'p' };
        if (!memcmp(permissions, permRXP, sizeof(permissions))) {
            _textVm += vm;
            _textRss += rss;
            _textPss += pss;
        } else if (!memcmp(permissions, permRWP, sizeof(permissions))
                   && !isMainStack && (vm != 8192 || hasInode || !wasPrivateOnly) // try to exclude stack
                   && !hasInode) {
            _heapVm += vm;
            _heapRss += rss;
            _heapPss += pss;
        }

        static const char permP[] = { '-', '-', '-', 'p' };
        wasPrivateOnly = !memcmp(permissions, permP, sizeof(permissions));

        for (int skip = skipLen; skip; --skip) {
            if (Q_UNLIKELY(!fgets(line, lineLen, sf.file)))
                break;
        }
    }

    if (ok) {
        // publish the readings
        totalVm.store(_totalVm);
        totalRss.store(_totalRss);
        totalPss.store(_totalPss);
        textVm.store(_textVm);
        textRss.store(_textRss);
        textPss.store(_textPss);
        heapVm.store(_heapVm);
        heapRss.store(_heapRss);
        heapPss.store(_heapPss);
    }

    return ok;
}

#elif defined(Q_OS_MACOS)

void ProcessReader::openCpuLoad()
{
}

qreal ProcessReader::readCpuLoad()
{
    return 0.0;
}

bool ProcessReader::readMemory()
{
    struct task_basic_info t_info;
    mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

    if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count)) {
        qCWarning(LogSystem) << "Could not read memory data";
        return false;
    }

    totalRss.store(t_info.resident_size);
    totalVm.store(t_info.virtual_size);

    return true;
}

#else

void ProcessReader::openCpuLoad()
{
}

qreal ProcessReader::readCpuLoad()
{
    return 0.0;
}

bool ProcessReader::readMemory()
{
    return false;
}

#endif