[SIGAR-72] Fix possible crash parsing /proc/stat:btime

This commit is contained in:
Doug MacEachern 2007-11-09 17:31:31 +00:00
parent 29f25f22b7
commit 0883efd92c
1 changed files with 33 additions and 15 deletions

View File

@ -121,32 +121,50 @@ sigar_pid_t sigar_pid_get(sigar_t *sigar)
return sigar->pid; return sigar->pid;
} }
static int sigar_boot_time_get(sigar_t *sigar)
{
FILE *fp;
char buffer[BUFSIZ], *ptr;
int found = 0;
if (!(fp = fopen(PROC_STAT, "r"))) {
return errno;
}
while ((ptr = fgets(buffer, sizeof(buffer), fp))) {
if (strnEQ(ptr, "btime", 5)) {
if ((ptr = sigar_skip_token(ptr))) {
sigar->boot_time = sigar_strtoul(ptr);
found = 1;
}
break;
}
}
if (!found) {
/* should never happen */
sigar->boot_time = time(NULL);
}
return SIGAR_OK;
}
int sigar_os_open(sigar_t **sigar) int sigar_os_open(sigar_t **sigar)
{ {
char buffer[BUFSIZ], *ptr; int i, status;
int i;
int status = sigar_file2str(PROC_STAT, buffer, sizeof(buffer));
struct stat sb; struct stat sb;
*sigar = malloc(sizeof(**sigar)); *sigar = malloc(sizeof(**sigar));
if (status != SIGAR_OK) {
return status;
}
(*sigar)->pagesize = 0; (*sigar)->pagesize = 0;
i = getpagesize(); i = getpagesize();
while ((i >>= 1) > 0) { while ((i >>= 1) > 0) {
(*sigar)->pagesize++; (*sigar)->pagesize++;
} }
if ((ptr = strstr(buffer, "\nbtime"))) { status = sigar_boot_time_get(*sigar);
ptr = sigar_skip_token(ptr); if (status != SIGAR_OK) {
(*sigar)->boot_time = sigar_strtoul(ptr); return status;
}
else {
/* should never happen */
(*sigar)->boot_time = time(NULL);
} }
(*sigar)->ticks = sysconf(_SC_CLK_TCK); (*sigar)->ticks = sysconf(_SC_CLK_TCK);