diff --git a/Makefile b/Makefile index b663cc8..48d789e 100644 --- a/Makefile +++ b/Makefile @@ -43,6 +43,12 @@ ifdef DEBUG CXXFLAGS += -g -ggdb -gdwarf-4 endif +# Optional Clang -fbounds-safety (OFF by default). Requires a toolchain with +# ptrcheck.h / -fbounds-safety. Default builds leave NSJAIL_* macros inert. +ifdef ENABLE_FBOUNDS_SAFETY + CXXFLAGS += -DNSJAIL_SUPPORT_FBOUNDS_SAFETY -fbounds-safety +endif + BIN = nsjail LIBS = kafel/libkafel.a TEST_BINS = tests/nstun_buffer_budget_test tests/nstun_policy_test tests/nstun_ip_test diff --git a/bounds_safety.h b/bounds_safety.h new file mode 100644 index 0000000..4464735 --- /dev/null +++ b/bounds_safety.h @@ -0,0 +1,44 @@ +/* + * bounds_safety.h — portability macros for optional -fbounds-safety + * + * Copyright 2026 Jeff Bindel + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * When NSJAIL_SUPPORT_FBOUNDS_SAFETY is defined (typically via + * -DNSJAIL_SUPPORT_FBOUNDS_SAFETY and a Clang toolchain that implements + * -fbounds-safety), these macros expand to Clang bounds annotations. + * Otherwise they expand to nothing so default builds are unchanged. + * + * Pattern matches libwebp / libpng / lz4 inert-macro -fbounds-safety + * adoption: annotations are inert unless explicitly enabled. + */ +#ifndef NSJAIL_BOUNDS_SAFETY_H_ +#define NSJAIL_BOUNDS_SAFETY_H_ + +#ifdef NSJAIL_SUPPORT_FBOUNDS_SAFETY + +#include +/* Non-ABI-breaking sized-by annotations for buffer pointer parameters. + * Prefer NSJAIL_SIZED_BY when the companion argument is a byte capacity. + * Use *_OR_NULL when the pointer may be NULL while the size is zero. + */ +#define NSJAIL_SIZED_BY(n) __sized_by(n) +#define NSJAIL_SIZED_BY_OR_NULL(n) __sized_by_or_null(n) +#define NSJAIL_COUNTED_BY(n) __counted_by(n) +#define NSJAIL_COUNTED_BY_OR_NULL(n) __counted_by_or_null(n) + +#else /* !NSJAIL_SUPPORT_FBOUNDS_SAFETY */ + +#define NSJAIL_SIZED_BY(n) +#define NSJAIL_SIZED_BY_OR_NULL(n) +#define NSJAIL_COUNTED_BY(n) +#define NSJAIL_COUNTED_BY_OR_NULL(n) + +#endif /* NSJAIL_SUPPORT_FBOUNDS_SAFETY */ + +#endif /* NSJAIL_BOUNDS_SAFETY_H_ */ diff --git a/util.h b/util.h index 0bc39de..f9c0205 100644 --- a/util.h +++ b/util.h @@ -34,6 +34,7 @@ #include #include +#include "bounds_safety.h" #include "nsjail.h" #define RETURN_ON_FAILURE(expr) \ @@ -47,7 +48,7 @@ namespace util { -ssize_t readFromFd(int fd, void* buf, size_t len); +ssize_t readFromFd(int fd, void* NSJAIL_SIZED_BY(len) buf, size_t len); ssize_t readFromFile(const char* fname, void* buf, size_t len); bool readFromFileToStr(const char* fname, std::string* str); bool writeToFd(int fd, const void* buf, size_t len);