For example, here is my safety diff for cat.
The intrinsic beauty of it's memory handling is beyond words.
You just can't trust a virtual system to do it right; you always
need to check the underlying subsystem isn't messin' with ya.
Index: cat.c
===================================================================
RCS file: /cvs/src/bin/cat/cat.c,v
retrieving revision 1.26
diff -u -p -u -r1.26 cat.c
--- cat.c 19 Oct 2016 18:20:25 -0000 1.26
+++ cat.c 10 Dec 2017 19:24:21 -0000
@@ -35,6 +35,7 @@
#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/sysctl.h>
#include <ctype.h>
#include <err.h>
@@ -46,6 +47,7 @@
#include <unistd.h>
#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
+#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
extern char *__progname;
@@ -63,7 +65,7 @@ main(int argc, char *argv[])
{
int ch;
- if (pledge("stdio rpath", NULL) == -1)
+ if (pledge("stdio rpath ps", NULL) == -1)
err(1, "pledge");
while ((ch = getopt(argc, argv, "benstuv")) != -1)
@@ -228,12 +230,27 @@ raw_cat(int rfd)
static size_t bsize;
static char *buf = NULL;
struct stat sbuf;
+ int64_t physmem;
+ size_t siz = sizeof(physmem);
+ int mib[2];
+
+ /*
+ * Ensure a fuse filesystem + uncooperative kernel cannot
+ * force us to allocate a buffer which gets slow because it
+ * gets pushed into swap
+ */
+ mib[0] = CTL_HW;
+ mib[1] = HW_PHYSMEM64;
+ if (sysctl(mib, 2, &physmem, &siz, NULL, 0) < 0) {
+ warnx("physmem: failed to get hw.physmem");
+ physmem = 0x4*1024*1024;
+ }
wfd = fileno(stdout);
if (buf == NULL) {
if (fstat(wfd, &sbuf))
err(1, "stdout");
- bsize = MAXIMUM(sbuf.st_blksize, BUFSIZ);
+ bsize = MINIMUM(MAXIMUM(sbuf.st_blksize, BUFSIZ), physmem);
if ((buf = malloc(bsize)) == NULL)
err(1, "malloc");
}