Fix kernelinfo(1) reallocation loop never terminating.

This commit is contained in:
Jonas 'Sortie' Termansen 2016-10-02 13:50:26 +02:00
parent e400e3578e
commit 07b89e600d
1 changed files with 27 additions and 22 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012 Jonas 'Sortie' Termansen. * Copyright (c) 2012, 2016 Jonas 'Sortie' Termansen.
* *
* Permission to use, copy, modify, and distribute this software for any * Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above * purpose with or without fee is hereby granted, provided that the above
@ -21,7 +21,7 @@
#include <err.h> #include <err.h>
#include <errno.h> #include <errno.h>
#include <error.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -48,32 +48,37 @@ int main(int argc, char* argv[])
else else
errx(1, "unknown option: %s\n", arg); errx(1, "unknown option: %s\n", arg);
} }
size_t bufsize = 32; size_t size = 32;
char* buf = (char*) malloc(bufsize); char* buffer = (char*) malloc(size);
if ( !buf ) if ( !buffer )
error(1, errno, "malloc"); err(1, "malloc");
for ( int i = 1; i < argc; i++ ) for ( int i = 1; i < argc; i++ )
{ {
ssize_t ret; while ( true )
retry: {
ret = kernelinfo(argv[i], buf, bufsize); ssize_t needed = kernelinfo(argv[i], buffer, size);
if ( ret < 0 ) if ( needed < 0 )
{ {
if ( errno == EINVAL ) if ( errno == EINVAL )
{ {
error(1, 0, "%s: No such kernel string", argv[i]); warn("%s: No such kernel information", argv[i]);
break;
} }
error(1, errno, "kernelinfo(\"%s\")", argv[i]); err(1, "kernelinfo: %s", argv[i]);
} }
if ( ret ) if ( 0 < needed )
{ {
buf = (char*) realloc(buf, ret); size = needed + 1;
if ( !buf ) buffer = (char*) realloc(buffer, size);
error(1, errno, "realloc"); if ( !buffer )
bufsize = ret; err(1, "malloc");
goto retry; continue;
} }
printf("%s\n", buf); printf("%s\n", buffer);
break;
} }
}
if ( ferror(stdout) || fflush(stdout) == EOF )
err(1, "stdout");
return 0; return 0;
} }