tests: move memlock helper to shared code

This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2019-11-08 14:58:28 +01:00
parent ee19c80733
commit 77abd02985
3 changed files with 23 additions and 25 deletions

View File

@ -3,6 +3,7 @@
#include <sched.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <util.h>
@ -149,3 +150,21 @@ bool have_namespaces(void) {
assert_not_reached("unexpected exit code");
}
bool can_memlock(void) {
/* Let's see if we can mlock() a larger blob of memory. BPF programs are charged against
* RLIMIT_MEMLOCK, hence let's first make sure we can lock memory at all, and skip the test if we
* cannot. Why not check RLIMIT_MEMLOCK explicitly? Because in container environments the
* RLIMIT_MEMLOCK value we see might not match the RLIMIT_MEMLOCK value actually in effect. */
void *p = mmap(NULL, CAN_MEMLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
return false;
bool b = mlock(p, CAN_MEMLOCK_SIZE) >= 0;
if (b)
assert_se(munlock(p, CAN_MEMLOCK_SIZE) >= 0);
assert_se(munmap(p, CAN_MEMLOCK_SIZE) >= 0);
return b;
}

View File

@ -12,3 +12,7 @@ int log_tests_skipped(const char *message);
int log_tests_skipped_errno(int r, const char *message);
bool have_namespaces(void);
/* We use the small but non-trivial limit here */
#define CAN_MEMLOCK_SIZE (512 * 1024U)
bool can_memlock(void);

View File

@ -2,7 +2,6 @@
#include <linux/bpf_insn.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "bpf-firewall.h"
@ -16,30 +15,6 @@
#include "unit.h"
#include "virt.h"
/* We use the small but non-trivial limit here */
#define CAN_MEMLOCK_SIZE (512 * 1024U)
static bool can_memlock(void) {
void *p;
bool b;
/* Let's see if we can mlock() a larger blob of memory. BPF programs are charged against
* RLIMIT_MEMLOCK, hence let's first make sure we can lock memory at all, and skip the test if we
* cannot. Why not check RLIMIT_MEMLOCK explicitly? Because in container environments the
* RLIMIT_MEMLOCK value we see might not match the RLIMIT_MEMLOCK value actually in effect. */
p = mmap(NULL, CAN_MEMLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
return false;
b = mlock(p, CAN_MEMLOCK_SIZE) >= 0;
if (b)
assert_se(munlock(p, CAN_MEMLOCK_SIZE) >= 0);
assert_se(munmap(p, CAN_MEMLOCK_SIZE) >= 0);
return b;
}
int main(int argc, char *argv[]) {
const struct bpf_insn exit_insn[] = {
BPF_MOV64_IMM(BPF_REG_0, 0), /* drop */