If we ever were to eliminate the procps.h header file,
as discussed in the thread referenced below, then that
would impair the current XTRA_PROCPS_DEBUG provisions.
The only remaining way to verify result types would be
to explicitly include that <proc/xtra-procps-debug.h>.
So, this commit will once again enable the ./configure
provision for defining the -DXTRA_PROCPS_DEBUG option.
Reference(s):
https://www.freelists.org/post/procps/newlib-Qualys-patches,6
Signed-off-by: Jim Warner <james.warner@comcast.net>
This patch is the first of three implementing a newlib
branch version of that Jan Rybar master merge request.
With this series we'll ultimately extend 'EXE' support
to both ps and top (plus, everyone else who wants it).
Reference(s):
. master branch merge request
https://gitlab.com/procps-ng/procps/merge_requests/66
Signed-off-by: Jim Warner <james.warner@comcast.net>
Following that patch referenced below, the top SUPGRPS
field would produce a segmentation fault and ps SUPGRP
would often show "(null)". Such problems resulted from
some faulty logic in the status2proc() routine dealing
with 'Groups' (supgid) which served as a source field.
For many processes the original code produced an empty
string which prevented conversion to the expected "-".
Moreover, prior to release 3.3.15 such an empty string
will become 0 after strtol() which pwcache_get_group()
translates to 'root' yielding very misleading results.
So, now we'll check for empty '/proc/#/status/Groups:'
fields & consistently provide a "-" value for callers.
[ we'll also protect against future problems in that ]
[ new qualys logic by always ensuring valid 'supgrp' ]
[ pointers - logic which revealed our original flaw! ]
Reference(s):
. original qualys patch
0071-proc-readproc.c-Harden-supgrps_from_supgids.patch
Signed-off-by: Jim Warner <james.warner@comcast.net>
This refactor was done in response to the Qualys patch
referenced below, which deals with some 'readeither()'
flaws under the master branch. Under our newlib branch
those flaws mostly disappear since the function is now
private. But without a redesign the #define is broken.
When the #define FALSE_THREADS is active, some special
strings showing "[ duplicate ENUM ]" will appear under
each child thread. Note that the real reason for those
appearing isn't being exercised, only their mechanics.
In reality, they only show when a user duplicates such
enums in a results stack & only 1 instance can own it.
Reference(s):
. original qualys patch
0084-proc-readproc.c-Work-around-a-design-flaw-in-readeit.patch
. QUICK_THREADS became FALSE_THREADS
commit c546d9dd44
Signed-off-by: Jim Warner <james.warner@comcast.net>
In the new library 'cmd' is dynamically allocated just
like 'cmdline'. This will align us with the ref below.
Reference(s):
. master branch increase to 64
commit 2cfdbbe897
Signed-off-by: Jim Warner <james.warner@comcast.net>
readeither() caches (in new_p) a pointer to the proc_t of a task-group
leader, but readeither()'s callers can do pretty much anything with the
proc_t structure passed to and/or returned by this function. For
example, they can 1/ free it or 2/ recycle it (by passing it to
readeither() as x).
1/ leads to a use-after-free, and 2/ leads to unexpected behavior when
taskreader()/simple_readtask() is called with new_p equal to x (this is
not a theoretical flaw: 2/ happens in readproctab3() when want_task()
returns false and p is a group leader).
As a workaround, we keep a copy of new_p's first member (tid) in static
storage, and the next times we enter readeither() we check this "canary"
against the tid in new_p: if they differ, we reset new_p to NULL, which
forces the allocation of a new proc_t (the new "leader", or reference).
This always detects 2/ (because free_acquired(x,1) memsets x and hence
new_p); always detects 1/ if freed via free_acquired() and/or freeproc()
(very likely, otherwise memory may be leaked); probably detects 1/ even
if freed directly via free() (because the canary is the first member of
proc_t, likely to be overwritten by free()); but can not detect 1/ if
free() does not write to new_p's chunk at all.
Moreover, accessing new_p->tid to check the canary in case 1/ is itself
a use-after-free, so a better long-term solution should be implemented
at some point (we wanted to avoid intrusive and backward-incompatible
changes in this library function, hence this imperfect workaround).
---------------------------- adapted for newlib branch
. adapted via 'patch' (rejected due to 'xcalloc' ref)
. with loss of both readproctab functions, most no longer true
Signed-off-by: Jim Warner <james.warner@comcast.net>
If QUICK_THREADS is not defined (it is not by default, but most
distributions enable it) and task_dir_missing is true (only on very old
kernels), then readtask() forgets to reset some of the struct proc_t t's
members, which later results in double-free()s in free_acquired().
For now, we simply synchronized the list of members to be reset with the
list of members freed in free_acquired().
---------------------------- adapted for newlib branch
. now 'cmd' is also dynamic
. just synchronized with those freed in free_acquired
. QUICK_THREADS is now FALSE_THREADS, serving different purpose
. entire patch will be effectively reverted with upcoming refactor
Signed-off-by: Jim Warner <james.warner@comcast.net>
Replace xmalloc() with xcalloc().
---------------------------- adapted for newlib branch
. trade xcalloc() for calloc()
. thus we must account for potential ENOMEM
Signed-off-by: Jim Warner <james.warner@comcast.net>
Replace memcpy+strcpy with snprintf.
---------------------------- adapted for newlib branch
. adapted via 'patch' (without rejections)
Signed-off-by: Jim Warner <james.warner@comcast.net>
Check the return value of snprintf(), otherwise dst may point
out-of-bounds when it reaches the end of the dst_buffer (the snprintf()
always returns 1 in that case, even if there is not enough space left),
and vMAX becomes negative and is passed to snprintf() as a size_t.
---------------------------- adapted for newlib branch
. adapted via 'patch (without rejections)
Signed-off-by: Jim Warner <james.warner@comcast.net>
This detects an integer overflow of "strlen + 1", prevents an integer
overflow of "tot + adj + (2 * pSZ)", and avoids calling snprintf with a
string longer than INT_MAX. Truncate rather than fail, since the callers
do not expect a failure of this function.
---------------------------- adapted for newlib branch
. logic is now in pids.c
. former 'vectorize_this_str' is now 'pids_vectorize_this'
Signed-off-by: Jim Warner <james.warner@comcast.net>
1/ Prevent an out-of-bounds write if sz is 0.
2/ Limit sz to INT_MAX, because the return value is an int, not an
unsigned int (and because if INT_MAX is equal to SSIZE_MAX, man 2 read
says "If count is greater than SSIZE_MAX, the result is unspecified.")
3/ Always null-terminate dst (unless sz is 0), because a return value of
0 because of an open() error (for example) is indistinguishable from a
return value of 0 because of an empty file.
4/ Use an unsigned int for i (just like n), not an int.
5/ Check for snprintf() truncation.
---------------------------- adapted for newlib branch
. adapted via 'patch (without rejections)
Signed-off-by: Jim Warner <james.warner@comcast.net>
Note: this is by far the most important and complex patch of the whole
series, please review it carefully; thank you very much!
For this patch, we decided to keep the original function's design and
skeleton, to avoid regressions and behavior changes, while fixing the
various bugs and overflows. And like the "Harden file2str()" patch, this
patch does not fail when about to overflow, but truncates instead: there
is information available about this process, so return it to the caller;
also, we used INT_MAX as a limit, but a lower limit could be used.
The easy changes:
- Replace sprintf() with snprintf() (and check for truncation).
- Replace "if (n == 0 && rbuf == 0)" with "if (n <= 0 && tot <= 0)" and
do break instead of return: it simplifies the code (only one place to
handle errors), and also guarantees that in the while loop either n or
tot is > 0 (or both), even if n is reset to 0 when about to overflow.
- Remove the "if (n < 0)" block in the while loop: it is (and was) dead
code, since we enter the while loop only if n >= 0.
- Rewrite the missing-null-terminator detection: in the original
function, if the size of the file is a multiple of 2047, a null-
terminator is appended even if the file is already null-terminated.
- Replace "if (n <= 0 && !end_of_file)" with "if (n < 0 || tot <= 0)":
originally, it was equivalent to "if (n < 0)", but we added "tot <= 0"
to handle the first break of the while loop, and to guarantee that in
the rest of the function tot is > 0.
- Double-force ("belt and suspenders") the null-termination of rbuf:
this is (and was) essential to the correctness of the function.
- Replace the final "while" loop with a "for" loop that behaves just
like the preceding "for" loop: in the original function, this would
lead to unexpected results (for example, if rbuf is |\0|A|\0|, this
would return the array {"",NULL} but should return {"","A",NULL}; and
if rbuf is |A|\0|B| (should never happen because rbuf should be null-
terminated), this would make room for two pointers in ret, but would
write three pointers to ret).
The hard changes:
- Prevent the integer overflow of tot in the while loop, but unlike
file2str(), file2strvec() cannot let tot grow until it almost reaches
INT_MAX, because it needs more space for the pointers: this is why we
introduced ARG_LEN, which also guarantees that we can add "align" and
a few sizeof(char*)s to tot without overflowing.
- Prevent the integer overflow of "tot + c + align": when INT_MAX is
(almost) reached, we write the maximal safe amount of pointers to ret
(ARG_LEN guarantees that there is always space for *ret = rbuf and the
NULL terminator).
---------------------------- adapted for newlib branch
. there were many formatting differences
. i introduced several myself (especially comments)
. stdlib 'realloc' used, not that home grown xrealloc
. stdlib 'realloc' required extra 'return NULL' statement
Signed-off-by: Jim Warner <james.warner@comcast.net>
1/ Replace sprintf() with snprintf() (and check for truncation).
2/ Prevent an integer overflow of ub->siz. The "tot_read--" is needed to
avoid an off-by-one overflow in "ub->buf[tot_read] = '\0'". It is safe
to decrement tot_read here, because we know that tot_read is equal to
ub->siz (and ub->siz is very large).
We believe that truncation is a better option than failure (implementing
failure instead should be as easy as replacing the "tot_read--" with
"tot_read = 0").
---------------------------- adapted for newlib branch
. no real changes, patch refused due to mem alloc & failure return
Signed-off-by: Jim Warner <james.warner@comcast.net>
1/ Use a "size_t num" instead of an "unsigned num" (also, do not store
the return value of sscanf() into num, it was unused anyway).
2/ Check the return value of strchr() and strrchr().
3/ Never jump over the terminating null byte with "S = tmp + 2".
---------------------------- adapted for newlib branch
. newlib doesn't use that 'unlikely' crap
. the cmd field is now also dynamic (like cmdline)
. thus we must account for potential ENOMEM
Signed-off-by: Jim Warner <james.warner@comcast.net>
1/ Prevent an integer overflow of t.
2/ Avoid an infinite loop if s contains characters other than comma,
spaces, +, -, and digits.
3/ Handle all possible return values of snprintf().
---------------------------- adapted for newlib branch
. we can't use xrealloc(), so we use realloc() instead
. and must account for a mem failure via a return of 1
Signed-off-by: Jim Warner <james.warner@comcast.net>
1/ Do not read past the terminating null byte when hashing the name.
2/ S[x] is used as an index, but S is "char *S" (signed) and hence may
index the array out-of-bounds. Bit-mask S[x] with 127 (the array has 128
entries).
3/ Use a size_t for j, not an int (strlen() returns a size_t).
Notes:
- These are (mostly) theoretical problems, because the contents of
/proc/PID/status are (mostly) trusted.
- The "name" member of the status_table_struct has 8 bytes, and
"RssShmem" occupies exactly 8 bytes, which means that "name" is not
null-terminated. This is fine right now, because status2proc() uses
memcmp(), not strcmp(), but it is worth mentioning.
---------------------------- adapted for newlib branch
. newlib doesn't use that 'unlikely' crap
. newlib also had a '#ifdef FALSE_THREADS'
Signed-off-by: Jim Warner <james.warner@comcast.net>
This function is unused (SIGNAL_STRING is defined by default, and if it
is not, procps does not compile -- for example, there is no "outbuf" in
help_pr_sig()) but fix it anyway. There are two bugs:
- it accepts non-hexadecimal characters (anything >= 0x30);
- "(c - (c>0x57) ? 0x57 : 0x30)" is always equal to 0x57.
---------------------------- adapted for newlib branch
. newlib doesn't use that 'unlikely' crap
Signed-off-by: Jim Warner <james.warner@comcast.net>
This solves several problems:
1/ outbuf[1] was written to, but not outbuf[0], which was left
uninitialized (well, SECURE_ESCAPE_ARGS() already fixes this, but do it
explicitly as well); we know it is safe to write one byte to outbuf,
because SECURE_ESCAPE_ARGS() guarantees it.
2/ If bytes was 1, the write to outbuf[1] was an off-by-one overflow.
3/ Do not call escape_str() with a 0 bufsize if bytes == overhead.
4/ Prevent various buffer overflows if bytes <= overhead.
Simply rearrange the old comparisons. The new comparisons are safe,
because we know from previous checks that:
1/ wlen > 0
2/ my_cells < *maxcells (also: my_cells >= 0 and *maxcells > 0)
3/ len > 1
4/ my_bytes+1 < bufsize (also: my_bytes >= 0 and bufsize > 0)
This should never happen, because wcwidth() is called only if iswprint()
returns nonzero. But belt-and-suspenders, and make it visually clear
(very important for the next patch).
The SECURE_ESCAPE_ARGS() macro solves several potential problems
(although we found no problematic calls to the escape*() functions in
procps's code-base, but had to thoroughly review every call; and this is
library code):
1/ off-by-one overflows if the size of the destination buffer is 0;
2/ buffer overflows if this size (or "maxroom") is negative;
3/ integer overflows (for example, "*maxcells+1");
4/ always null-terminate the destination buffer (unless its size is 0).
---------------------------- adapted for newlib branch
. the escape.c now has just a single exported function
. thus SECURE_ESCAPE_ARGS() is needed in only 2 places
. unlike that original patch, macro is executed 1 time
( not like 'escape_command' calling 'escape_strlist' )
( which might then call 'escape_str' multiple times! )
Signed-off-by: Jim Warner <james.warner@comcast.net>
In the human_readable case; otherwise the strcat() that follows may
append bytes to the previous contents of buf.
Also, slightly enlarge buf, as it was a bit too tight.
Could also replace all sprintf()s with snprintf()s, but all the calls
here output a limited number of characters, so they should be safe.
---------------------------- adapted for newlib branch
. the source file is now proc/uptime.c
. function is now named 'procps_uptime_sprint()'
. new human readable function 'procps_uptime_sprint_short()'
. both were already initialized, so just raised size of 2 buffers
Signed-off-by: Jim Warner <james.warner@comcast.net>
In proc/slab.c, functions parse_slabinfo20() and parse_slabinfo11(),
sscanf() might overflow curr->name, because "String input conversions
store a terminating null byte ('\0') to mark the end of the input; the
maximum field width does not include this terminator."
Add one byte to name[] for this terminator.
---------------------------- adapted for newlib branch
. file is now proc/slabinfo.c (not .h)
. manifest constant renamed SLABINFO_NAME_LEN
. older parse_slabinfo11() function no longer present
Signed-off-by: Jim Warner <james.warner@comcast.net>
When 'newlib' was introduced, in the commit referenced
below, the use of that glibc '__BEGIN_DECLS' macro was
standardized. However, as issue #88 revealed, this may
result in a fatal build error with other environments.
So, this patch just trades that macro for the standard
'#ifdef __cplusplus' conventions (thus avoiding use of
all those '#include <features.h>' directives as well).
Reference(s):
. newlib introduced
commit a410e236ab
. procps-ng-3.3.13 issue
https://gitlab.com/procps-ng/procps/issues/88
. some additional discussion
https://www.freelists.org/post/procps/PATCH-Replace-glibcspecific-macros-in-procnumah,1
. musl wiki (see: sys/cdefs.h error messages)
https://wiki.musl-libc.org/faq.html
Signed-off-by: Jim Warner <james.warner@comcast.net>
This patch simply eliminates that glibc specific macro
from all header files which contain no public callable
functions. After all, if user code can't link to them,
then protection from C++ name mangling is unnecessary.
[ we also remove any related '#include <features.h>' ]
Signed-off-by: Jim Warner <james.warner@comcast.net>
Now that the procio logic was removed from the library
we must move the header file, lest we break make dist.
In the process, we will relocate that source file too.
[ we'll take a slightly different approach than that ]
[ used under the master branch by exploiting those 2 ]
[ non-library directories 'include' and 'lib', while ]
[ avoiding any sysctl hard coded function prototype. ]
Signed-off-by: Jim Warner <james.warner@comcast.net>
The procio functions that were in the library have been
moved into sysctl. sysctl is not linked to libprocps in
newlib and none of the other procps binaries would need
to read/write large data to the procfs.
References:
be6b048a41
to be able to read and write large buffers below /proc.
The buffers and file offsets are handled dynamically
on the required buffer size at read, that is lseek(2)
is used to determine this size. Large buffers at
write are split at a delimeter into pieces and also
lseek(2) is used to write each of them.
Signed-off-by: Werner Fink <werner@suse.de>
With the documentation update in the commit referenced
below, we should also account for such threads as they
will already be represented in the task/thread totals.
[ and do it in a way that might avoid future changes ]
Reference(s):
commit 91df65b9e7
Signed-off-by: Jim Warner <james.warner@comcast.net>
This removes the following error by stating the task ID can only be 10
characters wide, as it is an integer.
proc/readproc.c: In function ‘simple_nexttid’:
proc/readproc.c:1185:46: warning: ‘%s’ directive output may be truncated writing up to 255 bytes into a region of size between 41 and 51 [-Wformat-truncation=]
snprintf(path, PROCPATHLEN, "/proc/%d/task/%s", p->tgid, ent->d_name);
^~
proc/readproc.c:1185:3: note: ‘snprintf’ output between 14 and 279 bytes into a destination of size 64
snprintf(path, PROCPATHLEN, "/proc/%d/task/%s", p->tgid, ent->d_name);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This commit removes some obsolete parameter validation
code which was needed back when certain functions were
public, called directly by users (1st/2nd generation).
Now that they're static they can be safely eliminated.
Signed-off-by: Jim Warner <james.warner@comcast.net>
With older library logic having been modified to avoid
using those potentially deadly alloc.h routines, while
improving 'errno' handling, we're ready to standardize
and enhance newlib's approach to any potential errors.
In so doing, we'll establish the following objectives:
. . . . . . . . . . . . . functions returning an 'int'
. an error will be indicated by a negative number that
is always the inverse of some well known errno.h value
. . . . . . . . . . . functions returning an 'address'
. any error will be indicated by a NULL return pointer
with the actual reason found in the formal errno value
And, when errno is manipulated directly we will strive
to do so whenever possible within those routines which
have been declared with PROCPS_EXPORT. In other words,
in the user callable functions defined in source last.
[ But, that won't always be possible. In particular, ]
[ all the 'read_failed' functions will sometimes set ]
[ 'errno' so that they can serve callers returning a ]
[ NULL or an int without duplicating a lot of logic. ]
[ Also, that includes one subordinate function which ]
[ was called by 'read_failed' in the <slabinfo> API. ]
------------------------------------------------------
Along the way, several additional miscellaneous issues
were addressed. They're listed here now for posterity.
. the '-1' return value passed outside the library was
eliminated since it would erroneously equate to -EPERM
. the stacks_fetch functions in <diskstats> and <stat>
weren't checked for their possible minus return values
. hash create was not checked in <meminfo> or <vmstat>
. fixed 'new' function faulty parm check in <slabinfo>
Signed-off-by: Jim Warner <james.warner@comcast.net>
While that old master branch library may utilize those
memory allocation functions found in the alloc module,
it was inappropriate for this newlib branch to subject
callers to a stderr message followed by an early exit.
Of course, the old libprocps offered a message handler
override provision (xalloc_err_handler) but that, too,
would seem to be inappropriate for our modern library.
[ remember the battles fought with that damn libnuma ]
So, this commit will tweak those old inherited sources
setting the stage for standardized return values/errno
settings in connection with a memory allocation error.
------------------------------------------------------
Along the way, we'll address the following miscellany:
. Completely eliminate usage of anything from alloc.h.
This, of course, entails our own error checking of the
alternative allocation calls from stdlib.h & string.h.
. Eliminate use of the strdup function where possible,
as with 'procps_uptime' and 'procps_loadavg' routines.
. Whack some obsolete code (getslabinfo) in sysinfo.c.
Signed-off-by: Jim Warner <james.warner@comcast.net>
. ensure whitespace exists between the code & comments
[ changing txt slightly keeps right margin alignment ]
. strive for more consistency with some comment styles
[ don't use C '/*' style where C++ '//' style exists ]
. removed the instance of double space in 1 assignment
[ still striving for consistency in whitespace usage ]
. fixed comment relating to number of 'derived fields'
[ the <meminfo> api recently added one new such enum ]
Signed-off-by: Jim Warner <james.warner@comcast.net>
This patch just rearranges 1 item in the stacks_extent
struct to make it equivalent to all the other modules.
Signed-off-by: Jim Warner <james.warner@comcast.net>
As an oversight, delta values for SWAP amounts weren't
included in the <meminfo> API. Since any runtime costs
of including them only amount to slightly more storage
this commit will simply correct the earlier oversight.
Signed-off-by: Jim Warner <james.warner@comcast.net>
When supplying the -p command to uptime, it does not display any
sections where the value is less than 1; however, after a reboot, this
causes the command to just output "up". Showing 0 minutes when the
system has been up for less than a minute makes it clear a reboot just
occurred.
References:
commit 325d68b7c3
Signed-off-by: Craig Small <csmall@enc.com.au>
Awhile back, that former QUICK_THREADS #define evolved
into the development (only) FALSE_THREADS which can be
used to ensure a 'duplicate ENUM' convention is output
when certain string fields can't be easily duplicated.
Unfortunately, that original implementation was marred
with zeros being displayed for /proc/$$/meminfo fields
in all the child threads for a multi-threaded process.
So this commit corrects that zero memory field buglet.
Reference(s):
. QUICK_THREADS becomes FALSE_THREADS
commit c546d9dd44
Signed-off-by: Jim Warner <james.warner@comcast.net>