LTP C API

Core LTP API

enum tst_res_flags

enum tst_res_flags

Test result reporting flags.

Definition

enum tst_res_flags {
    TPASS,
    TFAIL,
    TBROK,
    TWARN,
    TDEBUG,
    TINFO,
    TCONF,
    TERRNO,
    TTERRNO,
    TRERRNO
};

Constants

TPASS

Reports a single success. Successes increment passed counter and show up in the test results.

TFAIL

Reports a single failure. Failures increment failure counter and show up in the test results. A failure occurs when test assertion is broken.

TBROK

Reports a single breakage. Breakages increment breakage counter and show up in the test results. Breakages are reported in cases where a test couldn’t be executed due to an unexpected failure during the test setup. The TBROK status is mostly used with tst_brk() which exit the test immediately. The difference between TBROK and TCONF is that TCONF is used in cases where optional functionality is missing while TBROK is used in cases where something that is supposed to work is broken unexpectedly.

TWARN

Reports a single warning. Warnings increment a warning counter and show up in test results. Warnings are somewhere in the middle between TBROK and TCONF. Warnings usually appear when something that is supposed to be working is broken but the test can somehow continue.

TDEBUG

Prints additional debugging messages, it does not change the test result counters and the message is not displayed unless debugging is enabled with -D test command line parameter.

TINFO

Prints an additional information, it does not change the test result counters but unlike TDEBUG the message is always displayed.

TCONF

Reports unsupported configuration. When tests produce this result at least a subset of test was skipped, because it couldn’t run. The usual reasons are, missing kernel modules or CONFIG options. Unsuitable CPU architecture, not enough memory, etc.

TERRNO

Combine bitwise with result flags to append errno to the output message.

TTERRNO

Combine bitwise with result flags to append error from TST_ERR to the message. The TST_TEST() macros store the errno into the TST_ERR global variable in order to make sure it’s not change between the test is done and results are printed.

TRERRNO

Combine bitwise with result flags to errno from TST_RET variable to the message. The TST_TEST() macros store return value into the TST_RET global variable and quite a few, e.g. pthread functions, return the error value directly instead of storing it to the errno.

Description

A result flag with optional bitwise combination of errno flag are passed to the tst_res() and tst_brk() functions. Each message counts as a single test result and tests can produce arbitrary number of results, i.e. TPASS, TFAIL, TBROK, TWARN and TCONF messages. Each such message increases a result counter in a piece of shared memory, which means that reported results are accounted immediately even from child processes and there is no need for result propagation.

macro tst_res

tst_res(ttype, arg_fmt, ...)

Reports a test result.

Parameters:
  • ttype – An enum tst_res_type.

  • arg_fmt – A printf-like format.

  • ellipsis (ellipsis) – A printf-like parameters.

Description

This is the main test reporting function. Each time this function is called with one of TPASS, TFAIL, TCONF, TBROK or TWARN a counter in page of shared memory is incremented. This means that there is no need to propagate test results from children and that results are accounted for once this function returns. The counters are incremented atomically which makes this function thread-safe.

macro tst_res_hexd

tst_res_hexd(ttype, buf, size, arg_fmt, ...)

Reports a test result along with hex dump of a buffer.

Parameters:
  • ttype – An enum tst_res_type.

  • buf – A pointer to a buffer to print in hexadecimal format.

  • size – A size of the buffer.

  • arg_fmt – A printf-like format.

  • ellipsis (ellipsis) – A printf-like parameters.

Description

This call is the same as tst_res() but includes a pointer and size of the buffer that is going to be printed in the output in a hexadecimal format.

macro tst_brk

tst_brk(ttype, arg_fmt, ...)

Reports a breakage and exits the test.

Parameters:
  • ttype – An enum tst_res_type.

  • arg_fmt – A printf-like format.

  • ellipsis (ellipsis) – A printf-like parameters.

Description

Reports either TBROK or TCONF and exits the test immediately. When called all children in the same process group as the main test library process are killed. This function, unless in a test cleanup, calls _exit() and does not return.

When test is in cleanup() function TBROK is converted into TWARN by the test library and we attempt to carry on with a cleanup even when tst_brk() was called. This makes it possible to use SAFE_FOO() macros in the test cleanup without interrupting the cleanup process on a failure.

tst_flush

void tst_flush(void)

Flushes the output file streams.

Parameters:
  • void – no arguments

Description

There are rare cases when we want to flush the output file streams explicitly, e.g. before we do an action that may crash the test to ensure that the messages have been written out.

This is also called by the SAFE_FORK() because otherwise each child would end up with the same copy of the file in it’s memory and any messages in buffers would be multiplied.

macro SAFE_FORK

SAFE_FORK(void)

Forks a test child.

Parameters:
  • void – no arguments

Description

This call makes sure that output file streams are flushed and also handles errors from fork(). Use this instead of fork() whenever possible!

tst_strerrno

const char *tst_strerrno(int err)

Converts an errno number into a name.

Parameters:
  • err (int) – An errno number.

Return

An errno name e.g. “EINVAL”.

tst_strsig

const char *tst_strsig(int sig)

Converts a signal number into a name.

Parameters:
  • sig (int) – A signal number.

Return

A signal name e.g. “SIGINT”.

tst_strstatus

const char *tst_strstatus(int status)

Returns string describing status as returned by wait().

Parameters:
  • status (int) – A status as returned by wait()

Description

WARNING: Not thread safe.

Return

A string description for the status e.g. “killed by SIGKILL”.

tst_reap_children

void tst_reap_children(void)

Waits for all child processes to exit.

Parameters:
  • void – no arguments

Description

Wait for all children and exit with TBROK if any of them returned a non-zero exit status.

struct tst_option

struct tst_option

Test command line option.

Definition

struct tst_option {
    char *optstr;
    char **arg;
    char *help;
}

Members

optstr

A short command line option, e.g. “a” or “a:”.

arg

A pointer to store the option value to.

help

A help string for the option displayed when test is passed ‘-h’ on the command-line.

struct tst_tag

struct tst_tag

A test tag.

Definition

struct tst_tag {
    const char *name;
    const char *value;
}

Members

name

A tag name.

value

A tag value.

Description

This structure is used to encode pointers to upstream commits in regression tests as well as CVE numbers or any additional useful hints.

The content of these tags is printed by the test on a failure to help the testers with debugging.

The supported tags are

  • “linux-git” with first 12 numbers from an upstream kernel git hash.

  • “CVE” with a CVE number e.g. “2000-1234”.

  • “glibc-git” with first 12 numbers from an upstream glibc git hash.

  • “musl-git” with first 12 numbers from an upstream musl git hash.

  • “known-fail” a message describing something that is supposed to work but rather than that produces a longstanding failures.

struct tst_ulimit_val

struct tst_ulimit_val

An ulimit resource and value.

Definition

struct tst_ulimit_val {
    int resource;
    rlim_t rlim_cur;
}

Members

resource

Which resource limits should be adjusted. See setrlimit(2) for the list of the RLIMIT_* constants.

rlim_cur

A limit value.

struct tst_fs

struct tst_fs

A file system type, mkfs and mount options

Definition

struct tst_fs {
    const char *type;
    const char *const *mkfs_opts;
    const char *mkfs_size_opt;
    const char *mkfs_ver;
    unsigned int mnt_flags;
    const void *mnt_data;
    const char *min_kver;
}

Members

type

A filesystem type to use.

mkfs_opts

A NULL terminated array of options passed to mkfs in the case of ‘tst_test.format_device’. These options are passed to mkfs before the device path.

mkfs_size_opt

An option passed to mkfs in the case of ‘tst_test.format_device’. The device size in blocks is passed to mkfs after the device path and can be used to limit the file system not to use the whole block device.

mkfs_ver

mkfs tool version. The string format supports relational operators such as < > <= >= ==.

mnt_flags

MS_* flags passed to mount(2) when the test library mounts a device in the case of ‘tst_test.mount_device’.

mnt_data

The data passed to mount(2) when the test library mounts a device in the case of ‘tst_test.mount_device’.

min_kver

A minimum kernel version supporting the filesystem which has been created with mkfs.

struct tst_test

struct tst_test

A test description.

Definition

struct tst_test {
    unsigned int tcnt;
    struct tst_option *options;
    const char *min_kver;
    const char *const *supported_archs;
    const char *tconf_msg;
    unsigned int needs_tmpdir:1;
    unsigned int needs_root:1;
    unsigned int forks_child:1;
    unsigned int needs_device:1;
    unsigned int needs_checkpoints:1;
    unsigned int needs_overlay:1;
    unsigned int format_device:1;
    unsigned int mount_device:1;
    unsigned int needs_rofs:1;
    unsigned int child_needs_reinit:1;
    unsigned int runs_script:1;
    unsigned int needs_devfs:1;
    unsigned int restore_wallclock:1;
    unsigned int all_filesystems:1;
    unsigned int skip_in_lockdown:1;
    unsigned int skip_in_secureboot:1;
    unsigned int skip_in_compat:1;
    int needs_abi_bits;
    unsigned int needs_hugetlbfs:1;
    const char *const *skip_filesystems;
    unsigned long min_cpus;
    unsigned long min_mem_avail;
    unsigned long min_swap_avail;
    struct tst_hugepage hugepages;
    unsigned int taint_check;
    unsigned int test_variants;
    unsigned int dev_min_size;
    struct tst_fs *filesystems;
    const char *mntpoint;
    int max_runtime;
    void (*setup)(void);
    void (*cleanup)(void);
    void (*test)(unsigned int test_nr);
    void (*test_all)(void);
    const char *scall;
    int (*sample)(int clk_id, long long usec);
    const char *const *resource_files;
    const char * const *needs_drivers;
    const struct tst_path_val *save_restore;
    const struct tst_ulimit_val *ulimit;
    const char *const *needs_kconfigs;
    struct tst_buffers *bufs;
    struct tst_cap *caps;
    const struct tst_tag *tags;
    const char *const *needs_cmds;
    const enum tst_cg_ver needs_cgroup_ver;
    const char *const *needs_cgroup_ctrls;
    int needs_cgroup_nsdelegate:1;
}

Members

tcnt

A number of tests. If set the test() callback is called tcnt times and each time passed an increasing counter value.

options

An NULL optstr terminated array of struct tst_option.

min_kver

A minimal kernel version the test can run on. e.g. “3.10”.

supported_archs

A NULL terminated array of architectures the test runs on e.g. {“x86_64, “x86”, NULL}. Calls tst_is_on_arch() to check if current CPU architecture is supported and exits the test with TCONF if it’s not.

tconf_msg

If set the test exits with TCONF right after entering the test library. This is used by the TST_TEST_TCONF() macro to disable tests at compile time.

needs_tmpdir

If set a temporary directory is prepared for the test inside $TMPDIR and the test $CWD is set to point to it. The content of the temporary directory is removed automatically after the test is finished.

needs_root

If set the test exit with TCONF unless it’s executed under root user.

forks_child

Has to be set if the test intends to fork children.

needs_device

If set a block device is prepared for the test, the device path and size are set in the struct tst_device variable called tst_device. If $LTP_DEV variable exists in the test environment the test attempts to use that device first and only if that fails the test falls back to use loop devices. This flag implies needs_tmpdir flag because loop device backing files are created in the test temporary directory.

needs_checkpoints

Has to be set if the test wants to use checkpoint synchronization primitives.

needs_overlay

If set overlay file system is mounted on the top of the file system at tst_test.mntpoint.

format_device

Does all tst_test.needs_device would do and also formats the device with a file system as well.

mount_device

Does all tst_test.format_device would do and also mounts the device at tst_test.mntpoint.

needs_rofs

If set a read-only file system is mounted at tst_test.mntpoint.

child_needs_reinit

Has to be set if the test needs to call tst_reinit() from a process started by exec().

runs_script

Implies child_needs_reinit and forks_child at the moment.

needs_devfs

If set the devfs is mounted at tst_test.mntpoint. This is needed for tests that need to create device files since tmpfs at /tmp is usually mounted with ‘nodev’ option.

restore_wallclock

Saves wall clock at the start of the test and restores it at the end with the help of monotonic timers. Testcases that modify system wallclock use this to restore the system to the previous state.

all_filesystems

If set the test is executed for all supported filesytems, i.e. file system that is supported by the kernel and has mkfs installed on the system.The file system is mounted at tst_test.mntpoint and file system details, e.g. type are set in the struct tst_device. Each execution is independent, that means that for each iteration tst_test.setup() is called at the test start and tst_test.cleanup() is called at the end and tst_brk() only exits test for a single file system. That especially means that calling tst_brk(TCONF, …) in the test setup will skip the current file system.

skip_in_lockdown

Skip the test if kernel lockdown is enabled.

skip_in_secureboot

Skip the test if secureboot is enabled.

skip_in_compat

Skip the test if we are executing 32bit binary on a 64bit kernel, i.e. we are testing the kernel compat layer.

needs_abi_bits

Skip the test if runs on a different kernel ABI than requested (on 32bit instead of 64bit or vice versa). Possible values: 32, 64.

needs_hugetlbfs

If set hugetlbfs is mounted at tst_test.mntpoint.

skip_filesystems

A NULL terminated array of unsupported file systems. The test reports TCONF if the file system to be tested is present in the array. This is especially useful to filter out unsupported file system when tst_test.all_filesystems is enabled.

min_cpus

Minimal number of online CPUs the test needs to run.

min_mem_avail

Minimal amount of available RAM memory in megabytes required for the test to run.

min_swap_avail

Minimal amount of available swap memory in megabytes required for the test to run.

hugepages

An interface to reserve hugepages prior running the test. Request how many hugepages should be reserved in the global pool and also if having hugepages is required for the test run or not, i.e. if test should exit with TCONF if the requested amount of hugepages cannot be reserved. If TST_REQUEST is set the library will try it’s best to reserve the hugepages and return the number of available hugepages in tst_hugepages, which may be 0 if there is no free memory or hugepages are not supported at all. If TST_NEEDS the requested hugepages are required for the test and the test exits if it couldn’t be required. It can also be used to disable hugepages by setting .hugepages = {TST_NO_HUGEPAGES}. The test library restores the original poll allocations after the test has finished.

taint_check

If set the test fails if kernel is tainted during the test run. That means tst_taint_init() is called during the test setup and tst_taint_check() at the end of the test. If all_filesystems is set taint check will be performed after each iteration and testing will be terminated by TBROK if taint is detected.

test_variants

If set denotes number of test variant, the test is executed variants times each time with tst_variant set to different number. This allows us to run the same test for different settings. The intended use is to test different syscall wrappers/variants but the API is generic and does not limit usage in any way.

dev_min_size

A minimal device size in megabytes.

filesystems

A NULL type terminated array of per file system type parameters for mkfs and mount. If the first entry type is NULL it describes a default parameters for all file system tests. The rest of the entries the describes per file system type parameters. If tst_test.all_filesystems is set, the test runs for all filesystems and uses the array to lookup the mkfs and mount options. If tst_test.all_filesystems is not set the test iterates over file system types defined in the array. If there is only a single entry in the array with a NULL type, the test runs just once for the default file sytem i.e. $TST_FS_TYPE.

mntpoint

A mount point where the test library mounts requested file system. The directory is created by the library, the test must not create it itself.

max_runtime

Maximal test runtime in seconds. Any test that runs for more than a second or two should set this and also use tst_remaining_runtime() to exit when runtime was used up. Tests may finish sooner, for example if requested number of iterations was reached before the runtime runs out. If test runtime cannot be know in advance it should be set to TST_UNLIMITED_RUNTIME.

setup

Setup callback is called once at the start of the test in order to prepare the test environment.

cleanup

Cleanup callback is either called at the end of the test, or in a case that tst_brk() was called. That means that cleanup must be able to handle all possible states the test can be in. This usually means that we have to check if file descriptor was opened before we attempt to close it, etc.

test

A main test function, only one of the tst_test.test and test_all can be set. When this function is set the tst_test.tcnt must be set to a positive integer and this function will be executed tcnt times during a single test iteration. May be executed several times if test was passed ‘-i’ or ‘-d’ command line parameters.

test_all

A main test function, only one of the tst_test.test and test_all can be set. May be executed several times if test was passed ‘-i’ or ‘-d’ command line parameters.

scall

Internal only (timer measurement library).

sample

Internal only (timer measurement library).

resource_files

A NULL terminated array of filenames that will be copied to the test temporary directory from the LTP datafiles directory.

needs_drivers

A NULL terminated array of kernel modules required to run the test. The module has to be build in or present in order for the test to run.

save_restore

A {} terminated array of /proc or /sys files that should saved at the start of the test and restored at the end. See tst_sys_conf_save() and struct tst_path_val for details.

ulimit

A {} terminated array of process limits RLIMIT_* to be adjusted for the test.

needs_kconfigs

A NULL terminated array of kernel config options that are required for the test. All strings in the array have to be evaluated to true for the test to run. Boolean operators and parenthesis are supported, e.g. “CONFIG_X86_INTEL_UMIP=y | CONFIG_X86_UIMP=y” is evaluated to true if at least one of the options is present.

bufs

A description of guarded buffers to be allocated for the test. Guarded buffers are buffers with poisoned page allocated right before the start of the buffer and canary right after the end of the buffer. See struct tst_buffers and tst_buffer_alloc() for details.

caps

A {} terminated array of capabilities to change before the start of the test. See struct tst_cap and tst_cap_setup() for details.

tags

A {} terminated array of test tags. See struct tst_tag for details.

needs_cmds

A NULL terminated array of commands required for the test to run.

needs_cgroup_ver

If set the test will run only if the specified cgroup version is present on the system.

needs_cgroup_ctrls

A {} terminated array of cgroup controllers the test needs to run.

needs_cgroup_nsdelegate

If set test the will run only if cgroup2 is mounted with nsdelegate option.

tst_run_tcases

void tst_run_tcases(int argc, char *argv, struct tst_test *self)

Entry point to the test library.

Parameters:
  • argc (int) – An argc that was passed to the main().

  • argv (char*) – An argv that was passed to the main().

  • self (struct tst_test*) – The test description and callbacks packed in the struct tst_test structure.

Description

A main() function which calls this function is added to each test automatically by including the tst_test.h header. The test has to define the struct tst_test called test.

This function does not return, i.e. calls exit() after the test has finished.

tst_reinit

void tst_reinit(void)

Reinitialize the test library.

Parameters:
  • void – no arguments

Description

In a cases where a test child process calls exec() it no longer can access the test library shared memory and therefore use the test reporting functions, checkpoint library, etc. This function re-initializes the test library so that it can be used again.

important The LTP_IPC_PATH variable must be passed to the program environment.

tst_run_script

int tst_run_script(const char *script_name, char *const params)

Prepare the environment and execute a (shell) script.

Parameters:
  • script_name (const char*) – A filename of the script.

  • params (char *const) – A NULL terminated array of (shell) script parameters, pass NULL if none are needed. This what is passed starting from argv[1].

Description

The (shell) script is executed with LTP_IPC_PATH in environment so that the binary helpers such as tst_res or tst_checkpoint work properly when executed from the script. This also means that the tst_test.runs_script flag needs to be set.

A shell script has to source the tst_env.sh shell script at the start and after that it’s free to use tst_res in the same way C code would use.

Example shell script that reports success:

#!/bin/sh
. tst_env.sh

tst_res TPASS "Example test works"

The call returns a pid in a case that you want to examine the return value of the script yourself. If you do not need to check the return value yourself you can use tst_reap_children() to wait for the completion. Or let the test library collect the child automatically, just be wary that the script and the test both runs concurently at the same time in this case.

Return

A pid of the (shell) script process.

macro TST_TEST_TCONF

TST_TEST_TCONF(message)

Exit tests with a TCONF message.

Parameters:
  • message – Error message (the reason to skip test).

Description

This macro is used in test that couldn’t be compiled either because current CPU architecture is unsupported or because of missing development libraries.

tst_kernel_bits

int tst_kernel_bits(void)

Detect if running on 32bit or 64bit kernel.

Parameters:
  • void – no arguments

Return

32 if the test process is running on 32bit kernel and 64 if on 64bit kernel.

tst_is_compat_mode

int tst_is_compat_mode(void)

Detect if running in compat mode.

Parameters:
  • void – no arguments

Description

Detect if the test is 32bit binary executed on a 64bit kernel, i.e. we are testing the kernel compat layer.

Return

non-zero if the test process is running in compat mode.

tst_abi_bits

bool tst_abi_bits(int abi)

Detect if compiled for required kernel ABI.

Parameters:
  • abi (int) – kernel ABI bits (32 or 64).

Return

true if compiled for required ABI or false otherwise.

tst_check_builtin_driver

int tst_check_builtin_driver(const char *driver)

Check if the kernel module is built-in.

Parameters:
  • driver (const char*) – the name of the driver.

Return

0 if builtin driver or -1 when driver is missing or config file not available. On Android always 0 (always expect the driver is available).

tst_check_driver

int tst_check_driver(const char *driver)

Check support for the kernel module.

Parameters:
  • driver (const char*) – the name of the driver.

Description

Check support for the kernel module (both built-in and loadable).

Return

0 if the kernel has the driver, -1 when driver is missing or config file not available. On Android always 0 (always expect the driver is available).

Option parsing

Option parsing functions

Implements simple helpers on the top of the strtol() and strtod() for command line option parsing.

tst_parse_int

int tst_parse_int(const char *str, int *val, int min, int max)

Parse an integer from a string.

Parameters:
  • str (const char*) – A string with an integer number.

  • val (int*) – A pointer to integer to store the result to.

  • min (int) – A lower bound, pass INT_MIN for full range.

  • max (int) – An upper bound, pass INT_MAX for full range.

Return

A zero if whole string was consumed and the value was within bounds,

an errno otherwise.

tst_parse_long

int tst_parse_long(const char *str, long *val, long min, long max)

Parse a long integer from a string.

Parameters:
  • str (const char*) – A string with an integer number.

  • val (long*) – A pointer to long integer to store the result to.

  • min (long) – A lower bound, pass LONG_MIN for full range.

  • max (long) – An upper bound, pass LONG_MAX for full range.

Return

A zero if whole string was consumed and the value was within bounds,

an errno otherwise.

tst_parse_float

int tst_parse_float(const char *str, float *val, float min, float max)

Parse a floating point number from a string.

Parameters:
  • str (const char*) – A string with a floating point number.

  • val (float*) – A pointer to float to store the result to.

  • min (float) – A lower bound.

  • max (float) – An upper bound.

Return

A zero if whole string was consumed and the value was within bounds,

an errno otherwise.

tst_parse_filesize

int tst_parse_filesize(const char *str, long long *val, long long min, long long max)

Parse a file size from a string.

Parameters:
  • str (const char*) – A string a positive number optionally followed by an unit, i.e. K, M, or G for kilobytes, megabytes and gigabytes.

  • val (long long*) – A pointer to long long integer to store the size in bytes to.

  • min (long long) – A lower bound.

  • max (long long) – An upper bound.

Return

A zero if whole string was consumed and the value was within bounds,

an errno otherwise.

Guarded buffers

Guarded buffers introduction

Guarded buffer has a page with PROT_NONE allocated right before the start of the buffer and canary after the end of the buffer. That means that any memory access before the buffer ends with EFAULT or SEGFAULT and any write after the end of the buffer will be detected because it would overwrite the canaries.

It should be used for all buffers passed to syscalls to make sure off-by-one buffer accesses does not happen.

struct tst_buffers

struct tst_buffers

A guarded buffer description for allocator.

Definition

struct tst_buffers {
    void *ptr;
    size_t size;
    int *iov_sizes;
    char *str;
}

Members

ptr

A pointer to the pointer to buffer. This is dereferenced and set by the allocator.

size

A buffer size in bytes. Only one of size and iov_sizes can be set.

iov_sizes

An -1 terminated array of sizes used to construct a struct iovec buffers.

str

If size is zero and iov_sizes is NULL this string is going to be copied into the buffer.

Description

Buffer description consist of a pointer to a pointer and buffer type/size encoded as a different structure members.

tst_buffers_alloc

void tst_buffers_alloc(struct tst_buffers bufs)

Allocates buffers based on the tst_buffers structure.

Parameters:
  • bufs (struct tst_buffers) – A NULL terminated array of test buffer descriptions.

Description

This is called from the test library if the tst_test.bufs pointer is set.

tst_strdup

char *tst_strdup(const char *str)

Copies a string into a newly allocated guarded buffer.

Parameters:
  • str (const char*) – A string to be duplicated.

Return

A pointer to the string duplicated in a guarded buffer.

Allocates a buffer with tst_alloc() and copies the string into it.

tst_alloc

void *tst_alloc(size_t size)

Allocates a guarded buffer.

Parameters:
  • size (size_t) – A size of the buffer.

Return

A newly allocated guarded buffer.

tst_aprintf

char *tst_aprintf(const char *fmt, ...)

Printf into a newly allocated guarded buffer.

Parameters:
  • fmt (const char*) – A printf-like format.

  • ellipsis (ellipsis) – A printf-like parameters.

Return

A newly allocated buffer.

Allocates a buffer with tst_alloc() then prints the data into it.

tst_iovec_alloc

struct iovec *tst_iovec_alloc(int sizes)

Allocates a complete iovec structure.

Parameters:
  • sizes (int) – A -1 terminated array of buffer sizes.

Return

Newly allocated iovec structure.

tst_free_all

void tst_free_all(void)

Frees all allocated buffers.

Parameters:
  • void – no arguments

Description

It’s important to free all guarded buffers because the canaries after the buffer are checked only when the buffer is being freed.

This is called at the end of the test automatically.

Checkpoints

Checkpoints introduction

Checkpoints implements a futex based synchronization primitive for threads and processes. When a process calls wait function its execution is suspended until wake is called for a corresponding checkpoint. Checkpoints are numbered from 0 and process can use at least hundred of them.

In order to use checkpoints the test must set the tst_test.needs_checkpoints flag.

macro TST_CHECKPOINT_WAIT

TST_CHECKPOINT_WAIT(id)

Waits for a checkpoint.

Parameters:
  • id – A checkpoint id a positive integer.

Description

Suspends thread/process execution until it’s woken up with a wake. The call does not wait indefinitely it gives up after 10 seconds. If an error happened or timeout was reached the function calls tst_brk(TBROK, …) which exits the test.

macro TST_CHECKPOINT_WAIT2

TST_CHECKPOINT_WAIT2(id, msec_timeout)

Waits for a checkpoint.

Parameters:
  • id – A checkpoint id a positive integer.

  • msec_timeout – A timeout.

Description

Suspends thread/process execution until it’s woken up with a wake. If an error happened or timeout was reached the function calls tst_brk(TBROK, …) which exits the test.

macro TST_CHECKPOINT_WAKE

TST_CHECKPOINT_WAKE(id)

Wakes up a checkpoint.

Parameters:
  • id – A checkpoint id a positive integer.

Description

Wakes up a process suspended on a checkpoint and retries if there is no process suspended on the checkpoint yet. The call does not retry indefinitely but gives up after 10 seconds. If an error happened or timeout was reached the function calls tst_brk(TBROK, …) which exits the test.

macro TST_CHECKPOINT_WAKE2

TST_CHECKPOINT_WAKE2(id, nr_wake)

Wakes up several checkpoints.

Parameters:
  • id – A checkpoint id a positive integer.

  • nr_wake – A number of processes to wake.

Description

Wakes up nr_wake processes suspended on a checkpoint and retries if there wasn’t enough process suspended on the checkpoint yet. The call does not retry indefinitely but gives up if it does not wake nr_wake processes after 10 seconds. If an error happened or timeout was reached the function calls tst_brk(TBROK, …) which exits the test.

macro TST_CHECKPOINT_WAKE_AND_WAIT

TST_CHECKPOINT_WAKE_AND_WAIT(id)

Wakes up a checkpoint and immediately waits on it.

Parameters:
  • id – A checkpoint id a positive integer.

Description

This is a combination of TST_CHECKPOINT_WAKE() and TST_CHECKPOINT_WAIT().

Capabilities

Capabilities introduction

Limited capability operations without libcap.

enum tst_cap_act

enum tst_cap_act

A capability action masks.

Definition

enum tst_cap_act {
    TST_CAP_DROP,
    TST_CAP_REQ
};

Constants

TST_CAP_DROP

Drop capabilities.

TST_CAP_REQ

Add capabilities.

struct tst_cap_user_header

struct tst_cap_user_header

Kernel capget(), capset() syscall header.

Definition

struct tst_cap_user_header {
    uint32_t version;
    int pid;
}

Members

version

A capability API version.

pid

A process to operate on.

struct tst_cap_user_data

struct tst_cap_user_data

Kernel capset(), capget() syscall payload.

Definition

struct tst_cap_user_data {
    uint32_t effective;
    uint32_t permitted;
    uint32_t inheritable;
}

Members

effective

A capability effective set.

permitted

A capability permitted set.

inheritable

A capability inheritable set.

struct tst_cap

struct tst_cap

A capability to alter.

Definition

struct tst_cap {
    uint32_t action;
    uint32_t id;
    char *name;
}

Members

action

What should we do, i.e. drop or add a capability.

id

A capability id.

name

A capability name.

Description

This structure is usually constructed with the TST_CAP() macro so that the name is created automatically.

macro TST_CAP

TST_CAP(action, capability)

Create a struct tst_cap entry.

Parameters:
  • action – What should we do, i.e. drop or add capability.

  • capability – A capability id, e.g. CAP_BPF.

tst_capget

int tst_capget(struct tst_cap_user_header *hdr, struct tst_cap_user_data *data)

Get the capabilities as decided by hdr.

Parameters:
  • hdr (struct tst_cap_user_header*) – A capability user header stores a pid to operate on and which capability API version is used.

  • data (struct tst_cap_user_data*) – A memory to store the capabilities to. The memory pointed to by data should be large enough to store two structs.

Return

Returns 0 on success, -1 on a failure and sets errno.

tst_capset

int tst_capset(struct tst_cap_user_header *hdr, const struct tst_cap_user_data *data)

Set the capabilities as decided by hdr and data

Parameters:
  • hdr (struct tst_cap_user_header*) – A capability user header stores a pid to operate on and which capability API version is used.

  • data (const struct tst_cap_user_data*) – A memory to store the capabilities to. The memory pointed to by data should be large enough to store two structs.

Return

Returns 0 on success, -1 on a failure and sets errno.

tst_cap_action

void tst_cap_action(struct tst_cap *cap)

Add, check or remove a capability.

Parameters:
  • cap (struct tst_cap*) – An {} terminated array of capabilities to alter.

Description

It will attempt to drop or add capability to the effective set. It will try to detect if this is needed and whether it can or can’t be done. If it clearly can not add a privilege to the effective set then it will return TCONF. However it may fail for some other reason and return TBROK.

This only tries to change the effective set. Some tests may need to change the inheritable and ambient sets, so that child processes retain some capability.

tst_cap_setup

void tst_cap_setup(struct tst_cap *cap, enum tst_cap_act action_mask)

Add, check or remove a capabilities.

Parameters:
  • cap (struct tst_cap*) – An {} terminated array of capabilities to alter.

  • action_mask (enum tst_cap_act) – Decides which actions are done, i.e. only drop caps, add them or both.

Description

Takes a NULL terminated array of structs which describe whether some capabilities are needed or not and mask that determines subset of the actions to be performed. Loops over the array and if mask matches the element action it’s passed to tst_cap_action().

libltpswap

macro MAKE_SMALL_SWAPFILE

MAKE_SMALL_SWAPFILE(swapfile)

create small swap file.

Parameters:
  • swapfile – swap filename.

Description

Macro to create small swap file. Size defined with MINIMAL_SWAP_SIZE_MB.

macro SAFE_MAKE_SMALL_SWAPFILE

SAFE_MAKE_SMALL_SWAPFILE(swapfile)

create small swap file (safe version).

Parameters:
  • swapfile – swap filename.

Description

Macro to create small swap file. Size defined with MINIMAL_SWAP_SIZE_MB. Includes safety checks to handle potential errors.

macro MAKE_SWAPFILE_SIZE

MAKE_SWAPFILE_SIZE(swapfile, size)

create swap file (MB).

Parameters:
  • swapfile – swap filename.

  • size – swap size in MB.

Description

Macro to create swap file, size specified in megabytes (MB).

macro MAKE_SWAPFILE_BLKS

MAKE_SWAPFILE_BLKS(swapfile, blocks)

create swap file (blocks).

Parameters:
  • swapfile – swap filename.

  • blocks – number of blocks.

Description

Macro to create swap file, size specified in block numbers.

macro SAFE_MAKE_SWAPFILE_SIZE

SAFE_MAKE_SWAPFILE_SIZE(swapfile, size)

create swap file (MB, safe version).

Parameters:
  • swapfile – swap file name.

  • size – swap size in MB.

Description

Macro to safely create swap file, size specified in megabytes (MB). Includes safety checks to handle potential errors.

macro SAFE_MAKE_SWAPFILE_BLKS

SAFE_MAKE_SWAPFILE_BLKS(swapfile, blocks)

create swap file (block, safe version)

Parameters:
  • swapfile – swap file name.

  • blocks – number of blocks.

Description

Macro to safely create swap file, size specified in block numbers. Includes safety checks to handle potential errors.

is_swap_supported

bool is_swap_supported(const char *filename)

Check swapon/swapoff support.

Parameters:
  • filename (const char*) – swap file name.

Description

Check swapon/swapoff support status of filesystems or files we are testing on.

Return

true if swap is supported, false if not.

tst_max_swapfiles

int tst_max_swapfiles(void)

Get kernel constant MAX_SWAPFILES value.

Parameters:
  • void – no arguments

Return

MAX_SWAPFILES value.

tst_count_swaps

int tst_count_swaps(void)

Get the used swapfiles number.

Parameters:
  • void – no arguments

Return

used swapfiles number.

Temporary directory

tst_purge_dir

void tst_purge_dir(const char *path)

Wipe the content of given directory.

Parameters:
  • path (const char*) – Path of the directory to be wiped.

Description

Wipe the content of given directory but keep the directory itself.

tst_tmpdir_path

char *tst_tmpdir_path(void)

Returns a pointer to a tmpdir path.

Parameters:
  • void – no arguments

Description

The returned path is allocated and initialized the first time this function is called, each subsequent call will return the same pointer.

Return

A newly allocated path. The memory is freed automatically at the end of the test. If allocation fails the function calls tst_brk() and exits the test.

tst_tmpdir_genpath

char *tst_tmpdir_genpath(const char *fmt, ...)

Construct an absolute path pointing to a file inside tmpdir.

Parameters:
  • fmt (const char*) – A printf-like format string.

  • ellipsis (ellipsis) – A printf-like parameter list.

Description

Constructs a path inside tmpdir i.e. adds a prefix pointing to the current test tmpdir to the string build by the printf-like format.

Return

A newly allocated path. The memory is freed automatically at the end of the test. If allocation fails the function calls tst_brk() and exits the test.