repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
criu
|
criu-master/criu/include/vma.h
|
#ifndef __CR_VMA_H__
#define __CR_VMA_H__
#include "image.h"
#include "common/list.h"
#include "images/vma.pb-c.h"
#include <sys/mman.h>
#include <string.h>
struct vm_area_list {
struct list_head h; /* list of VMAs */
unsigned nr; /* nr of all VMAs in the list */
unsigned int nr_aios; /* nr of AIOs VMAs in the list */
union {
unsigned long nr_priv_pages; /* dmp: nr of pages in private VMAs */
unsigned long rst_priv_size; /* rst: size of private VMAs */
};
unsigned long nr_priv_pages_longest; /* nr of pages in longest private VMA */
unsigned long nr_shared_pages_longest; /* nr of pages in longest shared VMA */
};
static inline void vm_area_list_init(struct vm_area_list *vml)
{
memset(vml, 0, sizeof(*vml));
INIT_LIST_HEAD(&vml->h);
}
struct file_desc;
struct vma_area {
struct list_head list;
VmaEntry *e;
union {
struct /* for dump */ {
int vm_socket_id;
char *aufs_rpath; /* path from aufs root */
char *aufs_fpath; /* full path from global root */
/*
* When several subsequent vmas have the same
* dev:ino pair all 'tail' ones set this to true
* and the vmst points to the head's stat buf.
*/
bool file_borrowed;
struct stat *vmst;
int mnt_id;
};
struct /* for restore */ {
int (*vm_open)(int pid, struct vma_area *vma);
struct file_desc *vmfd;
struct vma_area *pvma; /* parent for inherited VMAs */
unsigned long *page_bitmap; /* existent pages */
unsigned long premmaped_addr; /* restore only */
/*
* Some notes about pvma, page_bitmap and premmaped_addr bits
* above.
*
* The pvma is set in prepare_cow_vmas() when we resolve which
* VMAs _may_ inherit pages from each other.
* The page_bitmap and premmaped_addr are set in prepare_mappings()
* when the respective VMAs get mmap-ed or mremap-ed.
* These VMAs are then inherited during fork_with_pid()-s
* called from create_children_and_session().
*/
};
};
};
#define VMA_COW_ROOT ((struct vma_area *)1)
typedef int (*dump_filemap_t)(struct vma_area *vma_area, int fd);
extern struct vma_area *alloc_vma_area(void);
extern int collect_mappings(pid_t pid, struct vm_area_list *vma_area_list, dump_filemap_t cb);
extern void free_mappings(struct vm_area_list *vma_area_list);
extern int parse_smaps(pid_t pid, struct vm_area_list *vma_area_list, dump_filemap_t cb);
extern int parse_self_maps_lite(struct vm_area_list *vms);
#define vma_area_is(vma_area, s) vma_entry_is((vma_area)->e, s)
#define vma_area_len(vma_area) vma_entry_len((vma_area)->e)
#define vma_entry_is(vma, s) (((vma)->status & (s)) == (s))
#define vma_entry_len(vma) ((vma)->end - (vma)->start)
/*
* vma_premmaped_start() can be used only in restorer.
* In other cases vma_area->premmaped_addr must be used.
* This hack is required, because vma_area isn't transferred in restorer and
* shmid is used to determine which vma-s are cowed.
*/
#define vma_premmaped_start(vma) ((vma)->shmid)
static inline int in_vma_area(struct vma_area *vma, unsigned long addr)
{
return addr >= (unsigned long)vma->e->start && addr < (unsigned long)vma->e->end;
}
static inline bool vma_entry_is_private(VmaEntry *entry, unsigned long task_size)
{
return (vma_entry_is(entry, VMA_AREA_REGULAR) &&
(vma_entry_is(entry, VMA_ANON_PRIVATE) || vma_entry_is(entry, VMA_FILE_PRIVATE)) &&
(entry->end <= task_size)) ||
vma_entry_is(entry, VMA_AREA_AIORING);
}
static inline bool vma_area_is_private(struct vma_area *vma, unsigned long task_size)
{
return vma_entry_is_private(vma->e, task_size);
}
static inline struct vma_area *vma_next(struct vma_area *vma)
{
return list_entry(vma->list.next, struct vma_area, list);
}
static inline bool vma_entry_can_be_lazy(VmaEntry *e)
{
return ((e->flags & MAP_ANONYMOUS) && (e->flags & MAP_PRIVATE) && !(e->flags & MAP_LOCKED) &&
!(vma_entry_is(e, VMA_AREA_VDSO)) && !(vma_entry_is(e, VMA_AREA_VSYSCALL)) &&
!(e->flags & MAP_HUGETLB));
}
#endif /* __CR_VMA_H__ */
| 4,001 | 29.784615 | 94 |
h
|
criu
|
criu-master/criu/include/linux/mount.h
|
#ifndef _CRIU_LINUX_MOUNT_H
#define _CRIU_LINUX_MOUNT_H
#include "common/config.h"
#include "compel/plugins/std/syscall-codes.h"
/* Copied from /usr/include/sys/mount.h */
#ifndef FSOPEN_CLOEXEC
/* The type of fsconfig call made. */
enum fsconfig_command {
FSCONFIG_SET_FLAG = 0, /* Set parameter, supplying no value */
#define FSCONFIG_SET_FLAG FSCONFIG_SET_FLAG
FSCONFIG_SET_STRING = 1, /* Set parameter, supplying a string value */
#define FSCONFIG_SET_STRING FSCONFIG_SET_STRING
FSCONFIG_SET_BINARY = 2, /* Set parameter, supplying a binary blob value */
#define FSCONFIG_SET_BINARY FSCONFIG_SET_BINARY
FSCONFIG_SET_PATH = 3, /* Set parameter, supplying an object by path */
#define FSCONFIG_SET_PATH FSCONFIG_SET_PATH
FSCONFIG_SET_PATH_EMPTY = 4, /* Set parameter, supplying an object by (empty) path */
#define FSCONFIG_SET_PATH_EMPTY FSCONFIG_SET_PATH_EMPTY
FSCONFIG_SET_FD = 5, /* Set parameter, supplying an object by fd */
#define FSCONFIG_SET_FD FSCONFIG_SET_FD
FSCONFIG_CMD_CREATE = 6, /* Invoke superblock creation */
#define FSCONFIG_CMD_CREATE FSCONFIG_CMD_CREATE
FSCONFIG_CMD_RECONFIGURE = 7, /* Invoke superblock reconfiguration */
#define FSCONFIG_CMD_RECONFIGURE FSCONFIG_CMD_RECONFIGURE
};
#endif // FSOPEN_CLOEXEC
/* fsopen flags. With the redundant definition, we check if the kernel,
* glibc value and our value still match.
*/
#define FSOPEN_CLOEXEC 0x00000001
#ifndef MS_MGC_VAL
/* Magic mount flag number. Has to be or-ed to the flag values. */
#define MS_MGC_VAL 0xc0ed0000 /* Magic flag number to indicate "new" flags */
#define MS_MGC_MSK 0xffff0000 /* Magic flag number mask */
#endif
#endif
| 1,642 | 36.340909 | 86 |
h
|
criu
|
criu-master/criu/include/linux/rseq.h
|
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
#ifndef _UAPI_LINUX_RSEQ_H
#define _UAPI_LINUX_RSEQ_H
#ifdef __has_include
#if __has_include("sys/rseq.h")
#include <sys/rseq.h>
#include "asm/thread_pointer.h"
#endif
#endif
#include <linux/types.h>
#include <asm/byteorder.h>
#include "common/config.h"
#ifdef CONFIG_HAS_NO_LIBC_RSEQ_DEFS
/*
* linux/rseq.h
*
* Restartable sequences system call API
*
* Copyright (c) 2015-2018 Mathieu Desnoyers <[email protected]>
*/
enum rseq_cpu_id_state {
RSEQ_CPU_ID_UNINITIALIZED = -1,
RSEQ_CPU_ID_REGISTRATION_FAILED = -2,
};
enum rseq_flags {
RSEQ_FLAG_UNREGISTER = (1 << 0),
};
enum rseq_cs_flags_bit {
RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT = 0,
RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT = 1,
RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT = 2,
};
enum rseq_cs_flags {
RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT),
RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT),
RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT),
};
#endif /* CONFIG_HAS_NO_LIBC_RSEQ_DEFS */
/*
* Let's use our own definition of struct rseq_cs because some distros
* (for example Mariner GNU/Linux) declares this structure their-own way.
* This makes trouble with inconsistency between printf formatters and
* struct rseq_cs field types.
*/
/*
* struct rseq_cs is aligned on 4 * 8 bytes to ensure it is always
* contained within a single cache-line. It is usually declared as
* link-time constant data.
*/
struct criu_rseq_cs {
/* Version of this structure. */
__u32 version;
/* enum rseq_cs_flags */
__u32 flags;
__u64 start_ip;
/* Offset from start_ip. */
__u64 post_commit_offset;
__u64 abort_ip;
} __attribute__((aligned(4 * sizeof(__u64))));
/*
* We have to have our own copy of struct rseq definition because
* of breaking UAPI change:
* https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?id=bfdf4e6208051ed7165b2e92035b4bf11f43eb63
*/
/*
* struct rseq is aligned on 4 * 8 bytes to ensure it is always
* contained within a single cache-line.
*
* A single struct rseq per thread is allowed.
*/
struct criu_rseq {
/*
* Restartable sequences cpu_id_start field. Updated by the
* kernel. Read by user-space with single-copy atomicity
* semantics. This field should only be read by the thread which
* registered this data structure. Aligned on 32-bit. Always
* contains a value in the range of possible CPUs, although the
* value may not be the actual current CPU (e.g. if rseq is not
* initialized). This CPU number value should always be compared
* against the value of the cpu_id field before performing a rseq
* commit or returning a value read from a data structure indexed
* using the cpu_id_start value.
*/
__u32 cpu_id_start;
/*
* Restartable sequences cpu_id field. Updated by the kernel.
* Read by user-space with single-copy atomicity semantics. This
* field should only be read by the thread which registered this
* data structure. Aligned on 32-bit. Values
* RSEQ_CPU_ID_UNINITIALIZED and RSEQ_CPU_ID_REGISTRATION_FAILED
* have a special semantic: the former means "rseq uninitialized",
* and latter means "rseq initialization failed". This value is
* meant to be read within rseq critical sections and compared
* with the cpu_id_start value previously read, before performing
* the commit instruction, or read and compared with the
* cpu_id_start value before returning a value loaded from a data
* structure indexed using the cpu_id_start value.
*/
__u32 cpu_id;
/*
* Restartable sequences rseq_cs field.
*
* Contains NULL when no critical section is active for the current
* thread, or holds a pointer to the currently active struct rseq_cs.
*
* Updated by user-space, which sets the address of the currently
* active rseq_cs at the beginning of assembly instruction sequence
* block, and set to NULL by the kernel when it restarts an assembly
* instruction sequence block, as well as when the kernel detects that
* it is preempting or delivering a signal outside of the range
* targeted by the rseq_cs. Also needs to be set to NULL by user-space
* before reclaiming memory that contains the targeted struct rseq_cs.
*
* Read and set by the kernel. Set by user-space with single-copy
* atomicity semantics. This field should only be updated by the
* thread which registered this data structure. Aligned on 64-bit.
*
* 32-bit architectures should update the low order bits of the
* rseq_cs field, leaving the high order bits initialized to 0.
*/
__u64 rseq_cs;
/*
* Restartable sequences flags field.
*
* This field should only be updated by the thread which
* registered this data structure. Read by the kernel.
* Mainly used for single-stepping through rseq critical sections
* with debuggers.
*
* - RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT
* Inhibit instruction sequence block restart on preemption
* for this thread.
* - RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL
* Inhibit instruction sequence block restart on signal
* delivery for this thread.
* - RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE
* Inhibit instruction sequence block restart on migration for
* this thread.
*/
__u32 flags;
} __attribute__((aligned(4 * sizeof(__u64))));
#endif /* _UAPI_LINUX_RSEQ_H */
| 5,421 | 33.980645 | 114 |
h
|
criu
|
criu-master/criu/include/linux/userfaultfd.h
|
/*
* include/linux/userfaultfd.h
*
* Copyright (C) 2007 Davide Libenzi <[email protected]>
* Copyright (C) 2015 Red Hat, Inc.
*
*/
#ifndef _LINUX_USERFAULTFD_H
#define _LINUX_USERFAULTFD_H
#include <linux/types.h>
/*
* If the UFFDIO_API is upgraded someday, the UFFDIO_UNREGISTER and
* UFFDIO_WAKE ioctls should be defined as _IOW and not as _IOR. In
* userfaultfd.h we assumed the kernel was reading (instead _IOC_READ
* means the userland is reading).
*/
#define UFFD_API ((__u64)0xAA)
#define UFFD_API_FEATURES \
(UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP | UFFD_FEATURE_EVENT_REMOVE | UFFD_FEATURE_EVENT_UNMAP | \
UFFD_FEATURE_MISSING_HUGETLBFS | UFFD_FEATURE_MISSING_SHMEM)
#define UFFD_API_IOCTLS ((__u64)1 << _UFFDIO_REGISTER | (__u64)1 << _UFFDIO_UNREGISTER | (__u64)1 << _UFFDIO_API)
#define UFFD_API_RANGE_IOCTLS ((__u64)1 << _UFFDIO_WAKE | (__u64)1 << _UFFDIO_COPY | (__u64)1 << _UFFDIO_ZEROPAGE)
#define UFFD_API_RANGE_IOCTLS_BASIC ((__u64)1 << _UFFDIO_WAKE | (__u64)1 << _UFFDIO_COPY)
/*
* Valid ioctl command number range with this API is from 0x00 to
* 0x3F. UFFDIO_API is the fixed number, everything else can be
* changed by implementing a different UFFD_API. If sticking to the
* same UFFD_API more ioctl can be added and userland will be aware of
* which ioctl the running kernel implements through the ioctl command
* bitmask written by the UFFDIO_API.
*/
#define _UFFDIO_REGISTER (0x00)
#define _UFFDIO_UNREGISTER (0x01)
#define _UFFDIO_WAKE (0x02)
#define _UFFDIO_COPY (0x03)
#define _UFFDIO_ZEROPAGE (0x04)
#define _UFFDIO_API (0x3F)
/* userfaultfd ioctl ids */
#define UFFDIO 0xAA
#define UFFDIO_API _IOWR(UFFDIO, _UFFDIO_API, struct uffdio_api)
#define UFFDIO_REGISTER _IOWR(UFFDIO, _UFFDIO_REGISTER, struct uffdio_register)
#define UFFDIO_UNREGISTER _IOR(UFFDIO, _UFFDIO_UNREGISTER, struct uffdio_range)
#define UFFDIO_WAKE _IOR(UFFDIO, _UFFDIO_WAKE, struct uffdio_range)
#define UFFDIO_COPY _IOWR(UFFDIO, _UFFDIO_COPY, struct uffdio_copy)
#define UFFDIO_ZEROPAGE _IOWR(UFFDIO, _UFFDIO_ZEROPAGE, struct uffdio_zeropage)
/* read() structure */
struct uffd_msg {
__u8 event;
__u8 reserved1;
__u16 reserved2;
__u32 reserved3;
union {
struct {
__u64 flags;
__u64 address;
} pagefault;
struct {
__u32 ufd;
} fork;
struct {
__u64 from;
__u64 to;
__u64 len;
} remap;
struct {
__u64 start;
__u64 end;
} remove;
struct {
/* unused reserved fields */
__u64 reserved1;
__u64 reserved2;
__u64 reserved3;
} reserved;
} arg;
} __packed;
/*
* Start at 0x12 and not at 0 to be more strict against bugs.
*/
#define UFFD_EVENT_PAGEFAULT 0x12
#define UFFD_EVENT_FORK 0x13
#define UFFD_EVENT_REMAP 0x14
#define UFFD_EVENT_REMOVE 0x15
#define UFFD_EVENT_UNMAP 0x16
/* flags for UFFD_EVENT_PAGEFAULT */
#define UFFD_PAGEFAULT_FLAG_WRITE (1 << 0) /* If this was a write fault */
#define UFFD_PAGEFAULT_FLAG_WP (1 << 1) /* If reason is VM_UFFD_WP */
struct uffdio_api {
/* userland asks for an API number and the features to enable */
__u64 api;
/*
* Kernel answers below with the all available features for
* the API, this notifies userland of which events and/or
* which flags for each event are enabled in the current
* kernel.
*
* Note: UFFD_EVENT_PAGEFAULT and UFFD_PAGEFAULT_FLAG_WRITE
* are to be considered implicitly always enabled in all kernels as
* long as the uffdio_api.api requested matches UFFD_API.
*
* UFFD_FEATURE_MISSING_HUGETLBFS means an UFFDIO_REGISTER
* with UFFDIO_REGISTER_MODE_MISSING mode will succeed on
* hugetlbfs virtual memory ranges. Adding or not adding
* UFFD_FEATURE_MISSING_HUGETLBFS to uffdio_api.features has
* no real functional effect after UFFDIO_API returns, but
* it's only useful for an initial feature set probe at
* UFFDIO_API time. There are two ways to use it:
*
* 1) by adding UFFD_FEATURE_MISSING_HUGETLBFS to the
* uffdio_api.features before calling UFFDIO_API, an error
* will be returned by UFFDIO_API on a kernel without
* hugetlbfs missing support
*
* 2) the UFFD_FEATURE_MISSING_HUGETLBFS can not be added in
* uffdio_api.features and instead it will be set by the
* kernel in the uffdio_api.features if the kernel supports
* it, so userland can later check if the feature flag is
* present in uffdio_api.features after UFFDIO_API
* succeeded.
*
* UFFD_FEATURE_MISSING_SHMEM works the same as
* UFFD_FEATURE_MISSING_HUGETLBFS, but it applies to shmem
* (i.e. tmpfs and other shmem based APIs).
*/
#define UFFD_FEATURE_PAGEFAULT_FLAG_WP (1 << 0)
#define UFFD_FEATURE_EVENT_FORK (1 << 1)
#define UFFD_FEATURE_EVENT_REMAP (1 << 2)
#define UFFD_FEATURE_EVENT_REMOVE (1 << 3)
#define UFFD_FEATURE_MISSING_HUGETLBFS (1 << 4)
#define UFFD_FEATURE_MISSING_SHMEM (1 << 5)
#define UFFD_FEATURE_EVENT_UNMAP (1 << 6)
__u64 features;
__u64 ioctls;
};
struct uffdio_range {
__u64 start;
__u64 len;
};
struct uffdio_register {
struct uffdio_range range;
#define UFFDIO_REGISTER_MODE_MISSING ((__u64)1 << 0)
#define UFFDIO_REGISTER_MODE_WP ((__u64)1 << 1)
__u64 mode;
/*
* kernel answers which ioctl commands are available for the
* range, keep at the end as the last 8 bytes aren't read.
*/
__u64 ioctls;
};
struct uffdio_copy {
__u64 dst;
__u64 src;
__u64 len;
/*
* There will be a wrprotection flag later that allows to map
* pages wrprotected on the fly. And such a flag will be
* available if the wrprotection ioctl are implemented for the
* range according to the uffdio_register.ioctls.
*/
#define UFFDIO_COPY_MODE_DONTWAKE ((__u64)1 << 0)
__u64 mode;
/*
* "copy" is written by the ioctl and must be at the end: the
* copy_from_user will not read the last 8 bytes.
*/
__s64 copy;
};
struct uffdio_zeropage {
struct uffdio_range range;
#define UFFDIO_ZEROPAGE_MODE_DONTWAKE ((__u64)1 << 0)
__u64 mode;
/*
* "zeropage" is written by the ioctl and must be at the end:
* the copy_from_user will not read the last 8 bytes.
*/
__s64 zeropage;
};
#endif /* _LINUX_USERFAULTFD_H */
| 6,273 | 29.906404 | 118 |
h
|
criu
|
criu-master/criu/pie/parasite-vdso.c
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <elf.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include "int.h"
#include "types.h"
#include "page.h"
#include "compel/plugins/std/syscall.h"
#include "compel/plugins/std/log.h"
#include "image.h"
#include "parasite-vdso.h"
#include "vma.h"
#include "log.h"
#include "common/bug.h"
#ifdef LOG_PREFIX
#undef LOG_PREFIX
#endif
#define LOG_PREFIX "vdso: "
/* Updates @from on success */
static int remap_one(char *who, unsigned long *from, unsigned long to, size_t size)
{
unsigned long addr;
pr_debug("Remap %s %lx -> %lx\n", who, *from, to);
addr = sys_mremap(*from, size, size, MREMAP_MAYMOVE | MREMAP_FIXED, to);
if (addr != to) {
pr_err("Unable to remap %lx -> %lx %lx\n", *from, to, addr);
return -1;
}
*from = addr;
return 0;
}
static int park_at(struct vdso_maps *rt, unsigned long vdso, unsigned long vvar)
{
unsigned long vvar_size = rt->sym.vvar_size;
unsigned long vdso_size = rt->sym.vdso_size;
int ret;
ret = remap_one("rt-vdso", &rt->vdso_start, vdso, vdso_size);
if (ret)
return ret;
std_log_set_gettimeofday(NULL); /* stop using vdso for timings */
if (vvar)
ret = remap_one("rt-vvar", &rt->vvar_start, vvar, vvar_size);
if (!ret)
vdso_update_gtod_addr(rt);
return ret;
}
void vdso_update_gtod_addr(struct vdso_maps *rt)
{
struct vdso_symbol *gtod_sym;
void *gtod;
if (rt->vdso_start == VDSO_BAD_ADDR) {
pr_debug("No rt-vdso - no fast gettimeofday()\n");
return;
}
if (VDSO_SYMBOL_GTOD < 0) {
pr_debug("Arch doesn't support gettimeofday() from vdso\n");
return;
}
/*
* XXX: Don't enable vdso timings for compatible applications.
* We would need to temporary map 64-bit vdso for timings in restorer
* and remap it with compatible at the end of restore.
* And vdso proxification should be done much later.
* Also, restorer should have two sets of vdso_maps in arguments.
*/
if (rt->compatible) {
pr_debug("compat mode: using syscall for gettimeofday()\n");
return;
}
gtod_sym = &rt->sym.symbols[VDSO_SYMBOL_GTOD];
if (gtod_sym->offset == VDSO_BAD_ADDR) {
pr_debug("No gettimeofday() on rt-vdso\n");
return;
}
gtod = (void *)(rt->vdso_start + gtod_sym->offset);
pr_info("Using gettimeofday() on vdso at %p\n", gtod);
std_log_set_gettimeofday(gtod);
}
/*
* Park runtime vDSO in some safe place where it can be accessible
* from the restorer
*/
int vdso_do_park(struct vdso_maps *rt, unsigned long addr, unsigned long space)
{
unsigned long vvar_size = rt->sym.vvar_size;
unsigned long vdso_size = rt->sym.vdso_size;
if (rt->vvar_start == VVAR_BAD_ADDR) {
BUG_ON(vdso_size < space);
return park_at(rt, addr, 0);
}
BUG_ON((vdso_size + vvar_size) < space);
if (rt->sym.vdso_before_vvar)
return park_at(rt, addr, addr + vdso_size);
else
return park_at(rt, addr + vvar_size, addr);
}
#ifndef CONFIG_COMPAT
static int __vdso_fill_symtable(uintptr_t mem, size_t size, struct vdso_symtable *t, bool __always_unused compat_vdso)
{
return vdso_fill_symtable(mem, size, t);
}
#endif
/*
* Proxification strategy
*
* - There might be two vDSO zones: vdso code and optionally vvar data
* - To be able to use in-place remapping we need
*
* a) Size and order of vDSO zones are to match
* b) Symbols offsets must match
* c) Have same number of vDSO zones
*/
static bool blobs_matches(VmaEntry *vdso_img, VmaEntry *vvar_img, struct vdso_symtable *sym_img,
struct vdso_symtable *sym_rt)
{
unsigned long vdso_size = vma_entry_len(vdso_img);
unsigned long rt_vdso_size = sym_rt->vdso_size;
size_t i;
if (vdso_size != rt_vdso_size) {
pr_info("size differs: %lx != %lx (rt)\n", vdso_size, rt_vdso_size);
return false;
}
for (i = 0; i < ARRAY_SIZE(sym_img->symbols); i++) {
unsigned long sym_offset = sym_img->symbols[i].offset;
unsigned long rt_sym_offset = sym_rt->symbols[i].offset;
char *sym_name = sym_img->symbols[i].name;
if (sym_offset != rt_sym_offset) {
pr_info("[%zu]`%s` offset differs: %lx != %lx (rt)\n", i, sym_name, sym_offset, rt_sym_offset);
return false;
}
}
if (vvar_img && sym_rt->vvar_size != VVAR_BAD_SIZE) {
bool vdso_firstly = (vvar_img->start > vdso_img->start);
unsigned long vvar_size = vma_entry_len(vvar_img);
unsigned long rt_vvar_size = sym_rt->vvar_size;
if (vvar_size != rt_vvar_size) {
pr_info("vvar size differs: %lx != %lx (rt)\n", vdso_size, rt_vdso_size);
return false;
}
if (vdso_firstly != sym_rt->vdso_before_vvar) {
pr_info("[%s] pair has different order\n", vdso_firstly ? "vdso/vvar" : "vvar/vdso");
return false;
}
}
return true;
}
/*
* The easy case -- the vdso from an image has the same offsets,
* order and size as runtime vdso, so we simply remap runtime vdso
* to dumpee position without generating any proxy.
*/
static int remap_rt_vdso(VmaEntry *vma_vdso, VmaEntry *vma_vvar, struct vdso_maps *rt)
{
void *remap_addr;
pr_info("Runtime vdso/vvar matches dumpee, remap inplace\n");
/*
* Ugly casts for 32bit platforms, which don't like uint64_t
* cast to (void *)
*/
remap_addr = (void *)(uintptr_t)vma_vdso->start;
if (sys_munmap(remap_addr, vma_entry_len(vma_vdso))) {
pr_err("Failed to unmap dumpee vdso\n");
return -1;
}
if (!vma_vvar)
return park_at(rt, vma_vdso->start, 0);
remap_addr = (void *)(uintptr_t)vma_vvar->start;
if (sys_munmap(remap_addr, vma_entry_len(vma_vvar))) {
pr_err("Failed to unmap dumpee vvar\n");
return -1;
}
return park_at(rt, vma_vdso->start, vma_vvar->start);
}
/*
* The complex case -- we need to proxify calls. We redirect
* calls from dumpee vdso to runtime vdso, making dumpee
* to operate as proxy vdso.
*/
static int add_vdso_proxy(VmaEntry *vma_vdso, VmaEntry *vma_vvar, struct vdso_symtable *sym_img, struct vdso_maps *rt,
bool compat_vdso)
{
unsigned long orig_vvar_addr = vma_vvar ? vma_vvar->start : VVAR_BAD_ADDR;
pr_info("Runtime vdso mismatches dumpee, generate proxy\n");
/*
* Note: we assume that after first migration with inserted
* rt-vdso and trampoilines on the following migrations
* number of vdso symbols will not decrease.
* We don't save the content of original vdso under inserted
* jumps, so we can't remove them if on the following migration
* found that number of symbols in vdso has decreased.
*/
if (vdso_redirect_calls(rt->vdso_start, vma_vdso->start, &rt->sym, sym_img, compat_vdso)) {
pr_err("Failed to proxify dumpee contents\n");
return -1;
}
/*
* Put a special mark into runtime vdso, thus at next checkpoint
* routine we could detect this vdso and do not dump it, since
* it's auto-generated every new session if proxy required.
*/
sys_mprotect((void *)rt->vdso_start, rt->sym.vdso_size, PROT_WRITE);
vdso_put_mark((void *)rt->vdso_start, rt->vvar_start, vma_vdso->start, orig_vvar_addr);
sys_mprotect((void *)rt->vdso_start, rt->sym.vdso_size, VDSO_PROT);
return 0;
}
int vdso_proxify(struct vdso_maps *rt, bool *added_proxy, VmaEntry *vmas, size_t nr_vmas, bool compat_vdso,
bool force_trampolines)
{
VmaEntry *vma_vdso = NULL, *vma_vvar = NULL;
struct vdso_symtable s = VDSO_SYMTABLE_INIT;
unsigned int i;
for (i = 0; i < nr_vmas; i++) {
if (vma_entry_is(&vmas[i], VMA_AREA_VDSO))
vma_vdso = &vmas[i];
else if (vma_entry_is(&vmas[i], VMA_AREA_VVAR))
vma_vvar = &vmas[i];
}
if (!vma_vdso && !vma_vvar) {
pr_info("No VVAR, no vDSO in image\n");
/*
* We don't have to unmap rt-vdso, rt-vvar as we didn't
* park them previously.
*/
return 0;
}
if (!vma_vdso) {
pr_err("Can't find vDSO area in image\n");
return -1;
}
/*
* We could still do something about it here..
* 1. Hope that vDSO from images still works (might not be the case).
* 2. Try to map vDSO.
* But, hopefully no one intends to migrate application that uses
* vDSO to a dut where kernel doesn't provide it.
*/
if (!vdso_is_present(rt)) {
pr_err("vDSO isn't provided by kernel, but exists in images\n");
return -1;
}
/*
* vDSO mark overwrites Elf program header of proxy vDSO thus
* it must never ever be greater in size.
*/
BUILD_BUG_ON(sizeof(struct vdso_mark) > sizeof(Elf64_Phdr));
/*
* Find symbols in vDSO zone read from image.
*/
if (__vdso_fill_symtable((uintptr_t)vma_vdso->start, vma_entry_len(vma_vdso), &s, compat_vdso))
return -1;
pr_debug("image [vdso] %lx-%lx [vvar] %lx-%lx\n", (unsigned long)vma_vdso->start, (unsigned long)vma_vdso->end,
vma_vvar ? (unsigned long)vma_vvar->start : VVAR_BAD_ADDR,
vma_vvar ? (unsigned long)vma_vvar->end : VVAR_BAD_ADDR);
*added_proxy = false;
if (blobs_matches(vma_vdso, vma_vvar, &s, &rt->sym) && !force_trampolines)
return remap_rt_vdso(vma_vdso, vma_vvar, rt);
*added_proxy = true;
return add_vdso_proxy(vma_vdso, vma_vvar, &s, rt, compat_vdso);
}
| 8,895 | 26.887147 | 118 |
c
|
criu
|
criu-master/criu/pie/parasite.c
|
#include <sys/mman.h>
#include <errno.h>
#include <signal.h>
#include <linux/limits.h>
#include <linux/capability.h>
#include <stdarg.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include "linux/rseq.h"
#include "common/config.h"
#include "int.h"
#include "types.h"
#include <compel/plugins/std/syscall.h>
#include "linux/mount.h"
#include "parasite.h"
#include "fcntl.h"
#include "prctl.h"
#include "common/lock.h"
#include "parasite-vdso.h"
#include "criu-log.h"
#include "tty.h"
#include "aio.h"
#include "asm/parasite.h"
#include "restorer.h"
#include "infect-pie.h"
/*
* PARASITE_CMD_DUMPPAGES is called many times and the parasite args contains
* an array of VMAs at this time, so VMAs can be unprotected in any moment
*/
static struct parasite_dump_pages_args *mprotect_args = NULL;
#ifndef SPLICE_F_GIFT
#define SPLICE_F_GIFT 0x08
#endif
#ifndef PR_GET_PDEATHSIG
#define PR_GET_PDEATHSIG 2
#endif
#ifndef PR_GET_CHILD_SUBREAPER
#define PR_GET_CHILD_SUBREAPER 37
#endif
static int mprotect_vmas(struct parasite_dump_pages_args *args)
{
struct parasite_vma_entry *vmas, *vma;
int ret = 0, i;
vmas = pargs_vmas(args);
for (i = 0; i < args->nr_vmas; i++) {
vma = vmas + i;
ret = sys_mprotect((void *)vma->start, vma->len, vma->prot | args->add_prot);
if (ret) {
pr_err("mprotect(%08lx, %ld) failed with code %d\n", vma->start, vma->len, ret);
break;
}
}
if (args->add_prot)
mprotect_args = args;
else
mprotect_args = NULL;
return ret;
}
static int dump_pages(struct parasite_dump_pages_args *args)
{
int p, ret, tsock;
struct iovec *iovs;
int off, nr_segs;
unsigned long spliced_bytes = 0;
tsock = parasite_get_rpc_sock();
p = recv_fd(tsock);
if (p < 0)
return -1;
iovs = pargs_iovs(args);
off = 0;
nr_segs = args->nr_segs;
if (nr_segs > UIO_MAXIOV)
nr_segs = UIO_MAXIOV;
while (1) {
ret = sys_vmsplice(p, &iovs[args->off + off], nr_segs, SPLICE_F_GIFT | SPLICE_F_NONBLOCK);
if (ret < 0) {
sys_close(p);
pr_err("Can't splice pages to pipe (%d/%d/%d)\n", ret, nr_segs, args->off + off);
return -1;
}
spliced_bytes += ret;
off += nr_segs;
if (off == args->nr_segs)
break;
if (off + nr_segs > args->nr_segs)
nr_segs = args->nr_segs - off;
}
if (spliced_bytes != args->nr_pages * PAGE_SIZE) {
sys_close(p);
pr_err("Can't splice all pages to pipe (%ld/%d)\n", spliced_bytes, args->nr_pages);
return -1;
}
sys_close(p);
return 0;
}
static int dump_sigact(struct parasite_dump_sa_args *da)
{
int sig, ret = 0;
for (sig = 1; sig <= SIGMAX; sig++) {
int i = sig - 1;
if (sig == SIGKILL || sig == SIGSTOP)
continue;
ret = sys_sigaction(sig, NULL, &da->sas[i], sizeof(k_rtsigset_t));
if (ret < 0) {
pr_err("sys_sigaction failed (%d)\n", ret);
break;
}
}
return ret;
}
static int dump_itimers(struct parasite_dump_itimers_args *args)
{
int ret;
ret = sys_getitimer(ITIMER_REAL, &args->real);
if (!ret)
ret = sys_getitimer(ITIMER_VIRTUAL, &args->virt);
if (!ret)
ret = sys_getitimer(ITIMER_PROF, &args->prof);
if (ret)
pr_err("getitimer failed (%d)\n", ret);
return ret;
}
static int dump_posix_timers(struct parasite_dump_posix_timers_args *args)
{
int i;
int ret = 0;
for (i = 0; i < args->timer_n; i++) {
ret = sys_timer_gettime(args->timer[i].it_id, &args->timer[i].val);
if (ret < 0) {
pr_err("sys_timer_gettime failed (%d)\n", ret);
return ret;
}
ret = sys_timer_getoverrun(args->timer[i].it_id);
if (ret < 0) {
pr_err("sys_timer_getoverrun failed (%d)\n", ret);
return ret;
}
args->timer[i].overrun = ret;
ret = 0;
}
return ret;
}
static int dump_creds(struct parasite_dump_creds *args);
static int check_rseq(struct parasite_check_rseq *rseq);
static int dump_thread_common(struct parasite_dump_thread *ti)
{
int ret;
arch_get_tls(&ti->tls);
ret = sys_prctl(PR_GET_TID_ADDRESS, (unsigned long)&ti->tid_addr, 0, 0, 0);
if (ret) {
pr_err("Unable to get the clear_child_tid address: %d\n", ret);
goto out;
}
ret = sys_sigaltstack(NULL, &ti->sas);
if (ret) {
pr_err("Unable to get signal stack context: %d\n", ret);
goto out;
}
ret = sys_prctl(PR_GET_PDEATHSIG, (unsigned long)&ti->pdeath_sig, 0, 0, 0);
if (ret) {
pr_err("Unable to get the parent death signal: %d\n", ret);
goto out;
}
ret = sys_prctl(PR_GET_NAME, (unsigned long)&ti->comm, 0, 0, 0);
if (ret) {
pr_err("Unable to get the thread name: %d\n", ret);
goto out;
}
ret = check_rseq(&ti->rseq);
if (ret) {
pr_err("Unable to check if rseq() is initialized: %d\n", ret);
goto out;
}
ret = dump_creds(ti->creds);
out:
return ret;
}
static int dump_misc(struct parasite_dump_misc *args)
{
int ret;
args->brk = sys_brk(0);
args->pid = sys_getpid();
args->sid = sys_getsid();
args->pgid = sys_getpgid(0);
args->umask = sys_umask(0);
sys_umask(args->umask); /* never fails */
args->dumpable = sys_prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
args->thp_disabled = sys_prctl(PR_GET_THP_DISABLE, 0, 0, 0, 0);
ret = sys_prctl(PR_GET_CHILD_SUBREAPER, (unsigned long)&args->child_subreaper, 0, 0, 0);
if (ret)
pr_err("PR_GET_CHILD_SUBREAPER failed (%d)\n", ret);
return ret;
}
static int dump_creds(struct parasite_dump_creds *args)
{
int ret, i, j;
struct cap_data data[_LINUX_CAPABILITY_U32S_3];
struct cap_header hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
ret = sys_capget(&hdr, data);
if (ret < 0) {
pr_err("Unable to get capabilities: %d\n", ret);
return -1;
}
/*
* Loop through the capability constants until we reach cap_last_cap.
* The cap_bnd set is stored as a bitmask comprised of CR_CAP_SIZE number of
* 32-bit uints, hence the inner loop from 0 to 32.
*/
for (i = 0; i < CR_CAP_SIZE; i++) {
args->cap_eff[i] = data[i].eff;
args->cap_prm[i] = data[i].prm;
args->cap_inh[i] = data[i].inh;
args->cap_bnd[i] = 0;
for (j = 0; j < 32; j++) {
if (j + i * 32 > args->cap_last_cap)
break;
ret = sys_prctl(PR_CAPBSET_READ, j + i * 32, 0, 0, 0);
if (ret < 0) {
pr_err("Unable to read capability %d: %d\n", j + i * 32, ret);
return -1;
}
if (ret)
args->cap_bnd[i] |= (1 << j);
}
}
args->secbits = sys_prctl(PR_GET_SECUREBITS, 0, 0, 0, 0);
ret = sys_getgroups(0, NULL);
if (ret < 0)
goto grps_err;
args->ngroups = ret;
if (args->ngroups >= PARASITE_MAX_GROUPS) {
pr_err("Too many groups in task %d\n", (int)args->ngroups);
return -1;
}
ret = sys_getgroups(args->ngroups, args->groups);
if (ret < 0)
goto grps_err;
if (ret != args->ngroups) {
pr_err("Groups changed on the fly %d -> %d\n", args->ngroups, ret);
return -1;
}
ret = sys_getresuid(&args->uids[0], &args->uids[1], &args->uids[2]);
if (ret) {
pr_err("Unable to get uids: %d\n", ret);
return -1;
}
args->uids[3] = sys_setfsuid(-1L);
/*
* FIXME In https://github.com/checkpoint-restore/criu/issues/95 it is
* been reported that only low 16 bits are set upon syscall
* on ARMv7.
*
* We may rather need implement builtin-memset and clear the
* whole memory needed here.
*/
args->gids[0] = args->gids[1] = args->gids[2] = args->gids[3] = 0;
ret = sys_getresgid(&args->gids[0], &args->gids[1], &args->gids[2]);
if (ret) {
pr_err("Unable to get uids: %d\n", ret);
return -1;
}
args->gids[3] = sys_setfsgid(-1L);
return 0;
grps_err:
pr_err("Error calling getgroups (%d)\n", ret);
return -1;
}
static int check_rseq(struct parasite_check_rseq *rseq)
{
int ret;
unsigned long rseq_abi_pointer;
unsigned long rseq_abi_size;
uint32_t rseq_signature;
void *addr;
/* no need to do hacky check if we can get all info from ptrace() */
if (!rseq->has_rseq || rseq->has_ptrace_get_rseq_conf)
return 0;
/*
* We need to determine if victim process has rseq()
* initialized, but we have no *any* proper kernel interface
* supported at this point.
* Our plan:
* 1. We know that if we call rseq() syscall and process already
* has current->rseq filled, then we get:
* -EINVAL if current->rseq != rseq || rseq_len != sizeof(*rseq),
* -EPERM if current->rseq_sig != sig),
* -EBUSY if current->rseq == rseq && rseq_len == sizeof(*rseq) &&
* current->rseq_sig != sig
* if current->rseq == NULL (rseq() wasn't used) then we go to:
* IS_ALIGNED(rseq ...) check, if we fail it we get -EINVAL and it
* will be hard to distinguish case when rseq() was initialized or not.
* Let's construct arguments payload
* with:
* 1. correct rseq_abi_size
* 2. aligned and correct rseq_abi_pointer
* And see what rseq() return to us.
* If ret value is:
* 0: it means that rseq *wasn't* used and we successfully registered it,
* -EINVAL or : it means that rseq is already initialized,
* so we *have* to dump it. But as we have has_ptrace_get_rseq_conf = false,
* we should just fail dump as it's unsafe to skip rseq() dump for processes
* with rseq() initialized.
* -EPERM or -EBUSY: should not happen as we take a fresh memory area for rseq
*/
addr = (void *)sys_mmap(NULL, sizeof(struct criu_rseq), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1,
0);
if (addr == MAP_FAILED) {
pr_err("mmap() failed for struct rseq ret = %lx\n", (unsigned long)addr);
return -1;
}
memset(addr, 0, sizeof(struct criu_rseq));
/* sys_mmap returns page aligned addresses */
rseq_abi_pointer = (unsigned long)addr;
rseq_abi_size = (unsigned long)sizeof(struct criu_rseq);
/* it's not so important to have unique signature for us,
* because rseq_abi_pointer is guaranteed to be unique
*/
rseq_signature = 0x12345612;
pr_info("\ttrying sys_rseq(%lx, %lx, %x, %x)\n", rseq_abi_pointer, rseq_abi_size, 0, rseq_signature);
ret = sys_rseq((void *)rseq_abi_pointer, rseq_abi_size, 0, rseq_signature);
if (ret) {
if (ret == -EINVAL) {
pr_info("\trseq is initialized in the victim\n");
rseq->rseq_inited = true;
ret = 0;
} else {
pr_err("\tunexpected failure of sys_rseq(%lx, %lx, %x, %x) = %d\n", rseq_abi_pointer,
rseq_abi_size, 0, rseq_signature, ret);
ret = -1;
}
} else {
ret = sys_rseq((void *)rseq_abi_pointer, sizeof(struct criu_rseq), RSEQ_FLAG_UNREGISTER,
rseq_signature);
if (ret) {
pr_err("\tfailed to unregister sys_rseq(%lx, %lx, %x, %x) = %d\n", rseq_abi_pointer,
rseq_abi_size, RSEQ_FLAG_UNREGISTER, rseq_signature, ret);
ret = -1;
/* we can't do munmap() because rseq is registered and we failed to unregister it */
goto out_nounmap;
}
rseq->rseq_inited = false;
ret = 0;
}
sys_munmap(addr, sizeof(struct criu_rseq));
out_nounmap:
return ret;
}
static int fill_fds_fown(int fd, struct fd_opts *p)
{
int flags, ret;
struct f_owner_ex owner_ex;
uint32_t v[2];
/*
* For O_PATH opened files there is no owner at all.
*/
flags = sys_fcntl(fd, F_GETFL, 0);
if (flags < 0) {
pr_err("fcntl(%d, F_GETFL) -> %d\n", fd, flags);
return -1;
}
if (flags & O_PATH) {
p->fown.pid = 0;
return 0;
}
ret = sys_fcntl(fd, F_GETOWN_EX, (long)&owner_ex);
if (ret) {
pr_err("fcntl(%d, F_GETOWN_EX) -> %d\n", fd, ret);
return -1;
}
/*
* Simple case -- nothing is changed.
*/
if (owner_ex.pid == 0) {
p->fown.pid = 0;
return 0;
}
ret = sys_fcntl(fd, F_GETOWNER_UIDS, (long)&v);
if (ret) {
pr_err("fcntl(%d, F_GETOWNER_UIDS) -> %d\n", fd, ret);
return -1;
}
p->fown.uid = v[0];
p->fown.euid = v[1];
p->fown.pid_type = owner_ex.type;
p->fown.pid = owner_ex.pid;
return 0;
}
static int fill_fds_opts(struct parasite_drain_fd *fds, struct fd_opts *opts)
{
int i;
for (i = 0; i < fds->nr_fds; i++) {
int flags, fd = fds->fds[i];
struct fd_opts *p = opts + i;
flags = sys_fcntl(fd, F_GETFD, 0);
if (flags < 0) {
pr_err("fcntl(%d, F_GETFD) -> %d\n", fd, flags);
return -1;
}
p->flags = (char)flags;
if (fill_fds_fown(fd, p))
return -1;
}
return 0;
}
static int drain_fds(struct parasite_drain_fd *args)
{
int ret, tsock;
struct fd_opts *opts;
/*
* See the drain_fds_size() in criu code, the memory
* for this args is ensured to be large enough to keep
* an array of fd_opts at the tail.
*/
opts = ((void *)args) + sizeof(*args) + args->nr_fds * sizeof(args->fds[0]);
ret = fill_fds_opts(args, opts);
if (ret)
return ret;
tsock = parasite_get_rpc_sock();
ret = send_fds(tsock, NULL, 0, args->fds, args->nr_fds, opts, sizeof(struct fd_opts));
if (ret)
pr_err("send_fds failed (%d)\n", ret);
return ret;
}
static int dump_thread(struct parasite_dump_thread *args)
{
args->tid = sys_gettid();
return dump_thread_common(args);
}
static char proc_mountpoint[] = "proc.crtools";
static int pie_atoi(char *str)
{
int ret = 0;
while (*str) {
ret *= 10;
ret += *str - '0';
str++;
}
return ret;
}
static int get_proc_fd(void)
{
int ret;
char buf[11];
ret = sys_readlinkat(AT_FDCWD, "/proc/self", buf, sizeof(buf) - 1);
if (ret < 0 && ret != -ENOENT) {
pr_err("Can't readlink /proc/self (%d)\n", ret);
return ret;
}
if (ret > 0) {
buf[ret] = 0;
/* Fast path -- if /proc belongs to this pidns */
if (pie_atoi(buf) == sys_getpid())
return sys_open("/proc", O_RDONLY, 0);
}
ret = sys_mkdir(proc_mountpoint, 0700);
if (ret) {
pr_err("Can't create a directory (%d)\n", ret);
return -1;
}
ret = sys_mount("proc", proc_mountpoint, "proc", MS_MGC_VAL, NULL);
if (ret) {
if (ret == -EPERM)
pr_err("can't dump unprivileged task whose /proc doesn't belong to it\n");
else
pr_err("mount failed (%d)\n", ret);
sys_rmdir(proc_mountpoint);
return -1;
}
return open_detach_mount(proc_mountpoint);
}
static int parasite_get_proc_fd(void)
{
int fd, ret, tsock;
fd = get_proc_fd();
if (fd < 0) {
pr_err("Can't get /proc fd\n");
return -1;
}
tsock = parasite_get_rpc_sock();
ret = send_fd(tsock, NULL, 0, fd);
sys_close(fd);
return ret;
}
static inline int tty_ioctl(int fd, int cmd, int *arg)
{
int ret;
ret = sys_ioctl(fd, cmd, (unsigned long)arg);
if (ret < 0) {
if (ret != -ENOTTY)
return ret;
*arg = 0;
}
return 0;
}
/*
* Stolen from kernel/fs/aio.c
*
* Is it valid to go to memory and check it? Should be,
* as libaio does the same.
*/
#define AIO_RING_MAGIC 0xa10a10a1
#define AIO_RING_COMPAT_FEATURES 1
#define AIO_RING_INCOMPAT_FEATURES 0
static int sane_ring(struct parasite_aio *aio)
{
struct aio_ring *ring = (struct aio_ring *)aio->ctx;
unsigned nr;
nr = (aio->size - sizeof(struct aio_ring)) / sizeof(struct io_event);
return ring->magic == AIO_RING_MAGIC && ring->compat_features == AIO_RING_COMPAT_FEATURES &&
ring->incompat_features == AIO_RING_INCOMPAT_FEATURES &&
ring->header_length == sizeof(struct aio_ring) && ring->nr == nr;
}
static int parasite_check_aios(struct parasite_check_aios_args *args)
{
int i;
for (i = 0; i < args->nr_rings; i++) {
struct aio_ring *ring;
ring = (struct aio_ring *)args->ring[i].ctx;
if (!sane_ring(&args->ring[i])) {
pr_err("Not valid ring #%d\n", i);
pr_info(" `- magic %x\n", ring->magic);
pr_info(" `- cf %d\n", ring->compat_features);
pr_info(" `- if %d\n", ring->incompat_features);
pr_info(" `- header size %d (%zd)\n", ring->header_length, sizeof(struct aio_ring));
pr_info(" `- nr %d\n", ring->nr);
return -1;
}
/* XXX: wait aio completion */
}
return 0;
}
static int parasite_dump_tty(struct parasite_tty_args *args)
{
int ret;
#ifndef TIOCGPKT
#define TIOCGPKT _IOR('T', 0x38, int)
#endif
#ifndef TIOCGPTLCK
#define TIOCGPTLCK _IOR('T', 0x39, int)
#endif
#ifndef TIOCGEXCL
#define TIOCGEXCL _IOR('T', 0x40, int)
#endif
args->sid = 0;
args->pgrp = 0;
args->st_pckt = 0;
args->st_lock = 0;
args->st_excl = 0;
#define __tty_ioctl(cmd, arg) \
do { \
ret = tty_ioctl(args->fd, cmd, &arg); \
if (ret < 0) { \
if (ret == -ENOTTY) \
arg = 0; \
else if (ret == -EIO) \
goto err_io; \
else \
goto err; \
} \
} while (0)
__tty_ioctl(TIOCGSID, args->sid);
__tty_ioctl(TIOCGPGRP, args->pgrp);
__tty_ioctl(TIOCGEXCL, args->st_excl);
if (args->type == TTY_TYPE__PTY) {
__tty_ioctl(TIOCGPKT, args->st_pckt);
__tty_ioctl(TIOCGPTLCK, args->st_lock);
}
args->hangup = false;
return 0;
err:
pr_err("tty: Can't fetch params: err = %d\n", ret);
return -1;
err_io:
/* kernel reports EIO for get ioctls on pair-less ptys */
pr_debug("tty: EIO on tty\n");
args->hangup = true;
return 0;
#undef __tty_ioctl
}
static int parasite_check_vdso_mark(struct parasite_vdso_vma_entry *args)
{
struct vdso_mark *m = (void *)args->start;
if (is_vdso_mark(m)) {
/*
* Make sure we don't meet some corrupted entry
* where signature matches but versions do not!
*/
if (m->version != VDSO_MARK_CUR_VERSION) {
pr_err("vdso: Mark version mismatch!\n");
return -EINVAL;
}
args->is_marked = 1;
args->orig_vdso_addr = m->orig_vdso_addr;
args->orig_vvar_addr = m->orig_vvar_addr;
args->rt_vvar_addr = m->rt_vvar_addr;
} else {
args->is_marked = 0;
args->orig_vdso_addr = VDSO_BAD_ADDR;
args->orig_vvar_addr = VVAR_BAD_ADDR;
args->rt_vvar_addr = VVAR_BAD_ADDR;
if (args->try_fill_symtable) {
struct vdso_symtable t;
if (vdso_fill_symtable(args->start, args->len, &t))
args->is_vdso = false;
else
args->is_vdso = true;
}
}
return 0;
}
static int parasite_dump_cgroup(struct parasite_dump_cgroup_args *args)
{
int proc, cgroup, len;
proc = get_proc_fd();
if (proc < 0) {
pr_err("can't get /proc fd\n");
return -1;
}
cgroup = sys_openat(proc, args->thread_cgrp, O_RDONLY, 0);
sys_close(proc);
if (cgroup < 0) {
pr_err("can't get /proc/self/cgroup fd\n");
sys_close(cgroup);
return -1;
}
len = sys_read(cgroup, args->contents, sizeof(args->contents));
sys_close(cgroup);
if (len < 0) {
pr_err("can't read /proc/self/cgroup %d\n", len);
return -1;
}
if (len == sizeof(args->contents)) {
pr_warn("/proc/self/cgroup was bigger than the page size\n");
return -1;
}
/* null terminate */
args->contents[len] = 0;
return 0;
}
void parasite_cleanup(void)
{
if (mprotect_args) {
mprotect_args->add_prot = 0;
mprotect_vmas(mprotect_args);
}
}
int parasite_daemon_cmd(int cmd, void *args)
{
int ret;
switch (cmd) {
case PARASITE_CMD_DUMPPAGES:
ret = dump_pages(args);
break;
case PARASITE_CMD_MPROTECT_VMAS:
ret = mprotect_vmas(args);
break;
case PARASITE_CMD_DUMP_SIGACTS:
ret = dump_sigact(args);
break;
case PARASITE_CMD_DUMP_ITIMERS:
ret = dump_itimers(args);
break;
case PARASITE_CMD_DUMP_POSIX_TIMERS:
ret = dump_posix_timers(args);
break;
case PARASITE_CMD_DUMP_THREAD:
ret = dump_thread(args);
break;
case PARASITE_CMD_DUMP_MISC:
ret = dump_misc(args);
break;
case PARASITE_CMD_DRAIN_FDS:
ret = drain_fds(args);
break;
case PARASITE_CMD_GET_PROC_FD:
ret = parasite_get_proc_fd();
break;
case PARASITE_CMD_DUMP_TTY:
ret = parasite_dump_tty(args);
break;
case PARASITE_CMD_CHECK_AIOS:
ret = parasite_check_aios(args);
break;
case PARASITE_CMD_CHECK_VDSO_MARK:
ret = parasite_check_vdso_mark(args);
break;
case PARASITE_CMD_DUMP_CGROUP:
ret = parasite_dump_cgroup(args);
break;
default:
pr_err("Unknown command in parasite daemon thread leader: %d\n", cmd);
ret = -1;
break;
}
return ret;
}
int parasite_trap_cmd(int cmd, void *args)
{
switch (cmd) {
case PARASITE_CMD_DUMP_THREAD:
return dump_thread(args);
}
pr_err("Unknown command to parasite: %d\n", cmd);
return -EINVAL;
}
| 19,603 | 22.227488 | 113 |
c
|
criu
|
criu-master/criu/pie/util-vdso.c
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <elf.h>
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include "image.h"
#include "util-vdso.h"
#include "vma.h"
#include "log.h"
#include "common/bug.h"
#ifdef CR_NOGLIBC
#include <compel/plugins/std/string.h>
#else
#include <string.h>
#define std_strncmp strncmp
#endif
#ifdef LOG_PREFIX
#undef LOG_PREFIX
#endif
#define LOG_PREFIX "vdso: "
/* Check if pointer is out-of-bound */
static bool __ptr_oob(uintptr_t ptr, uintptr_t start, size_t size)
{
uintptr_t end = start + size;
return ptr >= end || ptr < start;
}
/* Check if pointed structure's end is out-of-bound */
static bool __ptr_struct_end_oob(uintptr_t ptr, size_t struct_size, uintptr_t start, size_t size)
{
return __ptr_oob(ptr + struct_size - 1, start, size);
}
/* Check if pointed structure is out-of-bound */
static bool __ptr_struct_oob(uintptr_t ptr, size_t struct_size, uintptr_t start, size_t size)
{
return __ptr_oob(ptr, start, size) || __ptr_struct_end_oob(ptr, struct_size, start, size);
}
/*
* Elf hash, see format specification.
*/
static unsigned long elf_hash(const unsigned char *name)
{
unsigned long h = 0, g;
while (*name) {
h = (h << 4) + *name++;
g = h & 0xf0000000ul;
if (g)
h ^= g >> 24;
h &= ~g;
}
return h;
}
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define BORD ELFDATA2MSB /* 0x02 */
#else
#define BORD ELFDATA2LSB /* 0x01 */
#endif
static int has_elf_identity(Ehdr_t *ehdr)
{
/*
* See Elf specification for this magic values.
*/
#if defined(CONFIG_VDSO_32)
static const char elf_ident[] = {
0x7f, 0x45, 0x4c, 0x46, 0x01, BORD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#else
static const char elf_ident[] = {
0x7f, 0x45, 0x4c, 0x46, 0x02, BORD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif
BUILD_BUG_ON(sizeof(elf_ident) != sizeof(ehdr->e_ident));
if (memcmp(ehdr->e_ident, elf_ident, sizeof(elf_ident))) {
pr_err("ELF header magic mismatch\n");
return false;
}
return true;
}
static int parse_elf_phdr(uintptr_t mem, size_t size, Phdr_t **dynamic, Phdr_t **load)
{
Ehdr_t *ehdr = (void *)mem;
uintptr_t addr;
Phdr_t *phdr;
int i;
if (__ptr_struct_end_oob(mem, sizeof(Ehdr_t), mem, size))
goto err_oob;
/*
* Make sure it's a file we support.
*/
if (!has_elf_identity(ehdr))
return -EINVAL;
addr = mem + ehdr->e_phoff;
if (__ptr_oob(addr, mem, size))
goto err_oob;
for (i = 0; i < ehdr->e_phnum; i++, addr += sizeof(Phdr_t)) {
if (__ptr_struct_end_oob(addr, sizeof(Phdr_t), mem, size))
goto err_oob;
phdr = (void *)addr;
switch (phdr->p_type) {
case PT_DYNAMIC:
if (*dynamic) {
pr_err("Second PT_DYNAMIC header\n");
return -EINVAL;
}
*dynamic = phdr;
break;
case PT_LOAD:
if (*load) {
pr_err("Second PT_LOAD header\n");
return -EINVAL;
}
*load = phdr;
break;
}
}
return 0;
err_oob:
pr_err("Corrupted Elf phdr\n");
return -EFAULT;
}
/*
* Parse dynamic program header.
* Output parameters are:
* @dyn_strtab - address of the symbol table
* @dyn_symtab - address of the string table section
* @dyn_hash - address of the symbol hash table
*/
static int parse_elf_dynamic(uintptr_t mem, size_t size, Phdr_t *dynamic, Dyn_t **dyn_strtab, Dyn_t **dyn_symtab,
Dyn_t **dyn_hash)
{
Dyn_t *dyn_syment = NULL;
Dyn_t *dyn_strsz = NULL;
uintptr_t addr;
Dyn_t *d;
int i;
addr = mem + dynamic->p_offset;
if (__ptr_oob(addr, mem, size))
goto err_oob;
for (i = 0; i < dynamic->p_filesz / sizeof(*d); i++, addr += sizeof(Dyn_t)) {
if (__ptr_struct_end_oob(addr, sizeof(Dyn_t), mem, size))
goto err_oob;
d = (void *)addr;
if (d->d_tag == DT_NULL) {
break;
} else if (d->d_tag == DT_STRTAB) {
*dyn_strtab = d;
pr_debug("DT_STRTAB: %lx\n", (unsigned long)d->d_un.d_ptr);
} else if (d->d_tag == DT_SYMTAB) {
*dyn_symtab = d;
pr_debug("DT_SYMTAB: %lx\n", (unsigned long)d->d_un.d_ptr);
} else if (d->d_tag == DT_STRSZ) {
dyn_strsz = d;
pr_debug("DT_STRSZ: %lx\n", (unsigned long)d->d_un.d_val);
} else if (d->d_tag == DT_SYMENT) {
dyn_syment = d;
pr_debug("DT_SYMENT: %lx\n", (unsigned long)d->d_un.d_val);
} else if (d->d_tag == DT_HASH) {
*dyn_hash = d;
pr_debug("DT_HASH: %lx\n", (unsigned long)d->d_un.d_ptr);
}
}
if (!*dyn_strtab || !*dyn_symtab || !dyn_strsz || !dyn_syment || !*dyn_hash) {
pr_err("Not all dynamic entries are present\n");
return -EINVAL;
}
return 0;
err_oob:
pr_err("Corrupted Elf dynamic section\n");
return -EFAULT;
}
/* On s390x Hash_t is 64 bit */
#ifdef __s390x__
typedef unsigned long Hash_t;
#else
typedef Word_t Hash_t;
#endif
static void parse_elf_symbols(uintptr_t mem, size_t size, Phdr_t *load, struct vdso_symtable *t,
uintptr_t dynsymbol_names, Hash_t *hash, Dyn_t *dyn_symtab)
{
ARCH_VDSO_SYMBOLS_LIST
const char *vdso_symbols[VDSO_SYMBOL_MAX] = { ARCH_VDSO_SYMBOLS };
const size_t vdso_symbol_length = sizeof(t->symbols[0].name) - 1;
Hash_t nbucket, nchain;
Hash_t *bucket, *chain;
unsigned int i, j, k;
uintptr_t addr;
nbucket = hash[0];
nchain = hash[1];
bucket = &hash[2];
chain = &hash[nbucket + 2];
pr_debug("nbucket %lx nchain %lx bucket %lx chain %lx\n", (long)nbucket, (long)nchain, (unsigned long)bucket,
(unsigned long)chain);
for (i = 0; i < VDSO_SYMBOL_MAX; i++) {
const char *symbol = vdso_symbols[i];
k = elf_hash((const unsigned char *)symbol);
for (j = bucket[k % nbucket]; j < nchain && j != STN_UNDEF; j = chain[j]) {
Sym_t *sym;
char *name;
addr = mem + dyn_symtab->d_un.d_ptr - load->p_vaddr;
addr += sizeof(Sym_t) * j;
if (__ptr_struct_oob(addr, sizeof(Sym_t), mem, size))
continue;
sym = (void *)addr;
if (ELF_ST_TYPE(sym->st_info) != STT_FUNC && ELF_ST_BIND(sym->st_info) != STB_GLOBAL)
continue;
addr = dynsymbol_names + sym->st_name;
if (__ptr_struct_oob(addr, vdso_symbol_length, mem, size))
continue;
name = (void *)addr;
if (std_strncmp(name, symbol, vdso_symbol_length))
continue;
/* XXX: provide strncpy() implementation for PIE */
memcpy(t->symbols[i].name, name, vdso_symbol_length);
t->symbols[i].offset = (unsigned long)sym->st_value - load->p_vaddr;
break;
}
}
}
int vdso_fill_symtable(uintptr_t mem, size_t size, struct vdso_symtable *t)
{
Phdr_t *dynamic = NULL, *load = NULL;
Dyn_t *dyn_strtab = NULL;
Dyn_t *dyn_symtab = NULL;
Dyn_t *dyn_hash = NULL;
Hash_t *hash = NULL;
uintptr_t dynsymbol_names;
uintptr_t addr;
int ret;
pr_debug("Parsing at %lx %lx\n", (long)mem, (long)mem + (long)size);
/*
* We need PT_LOAD and PT_DYNAMIC here. Each once.
*/
ret = parse_elf_phdr(mem, size, &dynamic, &load);
if (ret < 0)
return ret;
if (!load || !dynamic) {
pr_err("One of obligated program headers is missed\n");
return -EINVAL;
}
pr_debug("PT_LOAD p_vaddr: %lx\n", (unsigned long)load->p_vaddr);
/*
* Dynamic section tags should provide us the rest of information
* needed. Note that we're interested in a small set of tags.
*/
ret = parse_elf_dynamic(mem, size, dynamic, &dyn_strtab, &dyn_symtab, &dyn_hash);
if (ret < 0)
return ret;
addr = mem + dyn_strtab->d_un.d_val - load->p_vaddr;
if (__ptr_oob(addr, mem, size))
goto err_oob;
dynsymbol_names = addr;
addr = mem + dyn_hash->d_un.d_ptr - load->p_vaddr;
if (__ptr_struct_oob(addr, sizeof(Word_t), mem, size))
goto err_oob;
hash = (void *)addr;
parse_elf_symbols(mem, size, load, t, dynsymbol_names, hash, dyn_symtab);
return 0;
err_oob:
pr_err("Corrupted Elf symbols/hash\n");
return -EFAULT;
}
| 7,702 | 22.996885 | 113 |
c
|
criu
|
criu-master/criu/unittest/unit.c
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "log.h"
#include "util.h"
#include "criu-log.h"
int parse_statement(int i, char *line, char **configuration);
int main(int argc, char *argv[], char *envp[])
{
char **configuration;
int i;
configuration = malloc(10 * sizeof(char *));
log_init(NULL);
i = parse_statement(0, "", configuration);
assert(i == 0);
i = parse_statement(0, "\n", configuration);
assert(i == 0);
i = parse_statement(0, "# comment\n", configuration);
assert(i == 0);
i = parse_statement(0, "#comment\n", configuration);
assert(i == 0);
i = parse_statement(0, "tcp-close #comment\n", configuration);
assert(i == 1);
assert(!strcmp(configuration[0], "--tcp-close"));
i = parse_statement(0, " tcp-close #comment\n", configuration);
assert(i == 1);
assert(!strcmp(configuration[0], "--tcp-close"));
i = parse_statement(0, "test \"test\"\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--test"));
assert(!strcmp(configuration[1], "test"));
i = parse_statement(0, "dsfa \"aaaaa \\\"bbbbbb\\\"\"\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--dsfa"));
assert(!strcmp(configuration[1], "aaaaa \"bbbbbb\""));
i = parse_statement(0, "verbosity 4\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--verbosity"));
assert(!strcmp(configuration[1], "4"));
i = parse_statement(0, "verbosity \"\n", configuration);
assert(i == -1);
i = parse_statement(0, "verbosity 4#comment\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--verbosity"));
assert(!strcmp(configuration[1], "4"));
i = parse_statement(0, "verbosity 4 #comment\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--verbosity"));
assert(!strcmp(configuration[1], "4"));
i = parse_statement(0, "verbosity 4 #comment\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--verbosity"));
assert(!strcmp(configuration[1], "4"));
i = parse_statement(0, "verbosity 4 no-comment\n", configuration);
assert(i == -1);
i = parse_statement(0, "lsm-profile \"\" # more comments\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--lsm-profile"));
assert(!strcmp(configuration[1], ""));
i = parse_statement(0, "lsm-profile \"something\"# comment\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--lsm-profile"));
assert(!strcmp(configuration[1], "something"));
i = parse_statement(0, "#\n", configuration);
assert(i == 0);
i = parse_statement(0, "lsm-profile \"selinux:something\\\"with\\\"quotes\"\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--lsm-profile"));
assert(!strcmp(configuration[1], "selinux:something\"with\"quotes"));
i = parse_statement(0, "work-dir \"/tmp with spaces\" no-comment\n", configuration);
assert(i == -1);
i = parse_statement(0, "work-dir \"/tmp with spaces\"\n", configuration);
assert(i == 2);
assert(!strcmp(configuration[0], "--work-dir"));
assert(!strcmp(configuration[1], "/tmp with spaces"));
i = parse_statement(0, "a b c d e f g h i\n", configuration);
assert(i == -1);
/* get_relative_path */
/* different kinds of representation of "/" */
assert(!strcmp(get_relative_path("/", "/"), ""));
assert(!strcmp(get_relative_path("/", ""), ""));
assert(!strcmp(get_relative_path("", "/"), ""));
assert(!strcmp(get_relative_path(".", "/"), ""));
assert(!strcmp(get_relative_path("/", "."), ""));
assert(!strcmp(get_relative_path("/", "./"), ""));
assert(!strcmp(get_relative_path("./", "/"), ""));
assert(!strcmp(get_relative_path("/.", "./"), ""));
assert(!strcmp(get_relative_path("./", "/."), ""));
assert(!strcmp(get_relative_path(".//////.", ""), ""));
assert(!strcmp(get_relative_path("/./", ""), ""));
/* all relative paths given are assumed relative to "/" */
assert(!strcmp(get_relative_path("/a/b/c", "a/b/c"), ""));
/* multiple slashes are ignored, only directory names matter */
assert(!strcmp(get_relative_path("///alfa///beta///gamma///", "//alfa//beta//gamma//"), ""));
/* returned path is always relative */
assert(!strcmp(get_relative_path("/a/b/c", "/"), "a/b/c"));
assert(!strcmp(get_relative_path("/a/b/c", "/a/b"), "c"));
/* single dots supported */
assert(!strcmp(get_relative_path("./a/b", "a/"), "b"));
/* double dots are partially supported */
assert(!strcmp(get_relative_path("a/../b", "a"), "../b"));
assert(!strcmp(get_relative_path("a/../b", "a/.."), "b"));
assert(!get_relative_path("a/../b/c", "b"));
/* if second path is not subpath - NULL returned */
assert(!get_relative_path("/a/b/c", "/a/b/d"));
assert(!get_relative_path("/a/b", "/a/b/c"));
assert(!get_relative_path("/a/b/c/d", "b/c/d"));
assert(!strcmp(get_relative_path("./a////.///./b//././c", "///./a/b"), "c"));
/* leaves punctuation in returned string as is */
assert(!strcmp(get_relative_path("./a////.///./b//././c", "a"), "b//././c"));
pr_msg("OK\n");
return 0;
}
| 4,992 | 32.510067 | 96 |
c
|
criu
|
criu-master/include/apparmor.h
|
#ifndef __CR_APPARMOR_H__
#define __CR_APPARMOR_H__
int collect_aa_namespace(char *profile);
int dump_aa_namespaces(void);
/*
* This is an operation similar to PTRACE_O_SUSPEND_SECCOMP but for apparmor,
* done entirely from userspace. All the namespaces to be dumped should be
* collected via collect_aa_namespaces() before calling this.
*/
int suspend_aa(void);
int unsuspend_aa(void);
bool check_aa_ns_dumping(void);
int prepare_apparmor_namespaces(void);
int render_aa_profile(char **out, const char *cur);
#endif /* __CR_APPARMOR_H__ */
| 551 | 24.090909 | 77 |
h
|
criu
|
criu-master/include/common/bug.h
|
#ifndef __CR_BUG_H__
#define __CR_BUG_H__
#include <signal.h>
#include <stdbool.h>
#include "common/compiler.h"
#ifndef BUG_ON_HANDLER
#ifdef CR_NOGLIBC
#define __raise()
#else
#define __raise() raise(SIGABRT)
#endif
#ifndef __clang_analyzer__
#ifndef pr_err
#error pr_err macro must be defined
#endif
#define BUG_ON_HANDLER(condition) \
do { \
if ((condition)) { \
pr_err("BUG at %s:%d\n", __FILE__, __LINE__); \
__raise(); \
*(volatile unsigned long *)NULL = 0xdead0000 + __LINE__; \
__builtin_unreachable(); \
} \
} while (0)
#else
#define BUG_ON_HANDLER(condition) \
do { \
assert(!condition); \
} while (0)
#endif
#endif /* BUG_ON_HANDLER */
#define BUG_ON(condition) BUG_ON_HANDLER((condition))
#define BUG() BUG_ON(true)
#endif /* __CR_BUG_H__ */
| 1,125 | 25.186047 | 82 |
h
|
criu
|
criu-master/include/common/compiler.h
|
#ifndef __CR_COMPILER_H__
#define __CR_COMPILER_H__
/*
* Various definitions for success build,
* picked from various places, mostly from
* the linux kernel.
*/
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define NELEMS_AS_ARRAY(x, y) (sizeof(x) / sizeof((y)[0]))
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2 * !!(condition)]))
#define ASSIGN_TYPED(a, b) \
do { \
(a) = (typeof(a))(b); \
} while (0)
#define ASSIGN_MEMBER(a, b, m) \
do { \
ASSIGN_TYPED((a)->m, (b)->m); \
} while (0)
#define __stringify_1(x...) #x
#define __stringify(x...) __stringify_1(x)
#define NORETURN __attribute__((__noreturn__))
#define __packed __attribute__((__packed__))
#define __used __attribute__((__used__))
#define __maybe_unused __attribute__((unused))
#define __always_unused __attribute__((unused))
#define __must_check __attribute__((__warn_unused_result__))
#define __section(S) __attribute__((__section__(#S)))
#ifndef __always_inline
#define __always_inline inline __attribute__((always_inline))
#endif
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#ifndef always_inline
#define always_inline __always_inline
#endif
#ifndef noinline
#define noinline __attribute__((noinline))
#endif
#define __aligned(x) __attribute__((aligned(x)))
/*
* Macro to define stack alignment.
* aarch64 requires stack to be aligned to 16 bytes.
*/
#define __stack_aligned__ __attribute__((aligned(16)))
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) & ((TYPE *)0)->MEMBER)
#endif
#define barrier() asm volatile("" ::: "memory")
#define container_of(ptr, type, member) \
({ \
const typeof(((type *)0)->member) *__mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); \
})
#ifndef FIELD_SIZEOF
#define FIELD_SIZEOF(t, f) (sizeof(((t *)0)->f))
#endif
#define __round_mask(x, y) ((__typeof__(x))((y)-1))
#define round_up(x, y) ((((x)-1) | __round_mask(x, y)) + 1)
#define round_down(x, y) ((x) & ~__round_mask(x, y))
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define ALIGN(x, a) (((x) + (a)-1) & ~((a)-1))
#define min(x, y) \
({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void)(&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; \
})
#define max(x, y) \
({ \
typeof(x) _max1 = (x); \
typeof(y) _max2 = (y); \
(void)(&_max1 == &_max2); \
_max1 > _max2 ? _max1 : _max2; \
})
#define min_t(type, x, y) \
({ \
type __min1 = (x); \
type __min2 = (y); \
__min1 < __min2 ? __min1 : __min2; \
})
#define max_t(type, x, y) \
({ \
type __max1 = (x); \
type __max2 = (y); \
__max1 > __max2 ? __max1 : __max2; \
})
#define SWAP(x, y) \
do { \
typeof(x) ____val = x; \
x = y; \
y = ____val; \
} while (0)
#define is_log2(v) (((v) & ((v)-1)) == 0)
/*
* Use "__ignore_value" to avoid a warning when using a function declared with
* gcc's warn_unused_result attribute, but for which you really do want to
* ignore the result. Traditionally, people have used a "(void)" cast to
* indicate that a function's return value is deliberately unused. However,
* if the function is declared with __attribute__((warn_unused_result)),
* gcc issues a warning even with the cast.
*
* Caution: most of the time, you really should heed gcc's warning, and
* check the return value. However, in those exceptional cases in which
* you're sure you know what you're doing, use this function.
*
* Normally casting an expression to void discards its value, but GCC
* versions 3.4 and newer have __attribute__ ((__warn_unused_result__))
* which may cause unwanted diagnostics in that case. Use __typeof__
* and __extension__ to work around the problem, if the workaround is
* known to be needed.
* Written by Jim Meyering, Eric Blake and Pádraig Brady.
* (See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 for the details)
*/
#if 3 < __GNUC__ + (4 <= __GNUC_MINOR__)
#define __ignore_value(x) \
({ \
__typeof__(x) __x = (x); \
(void)__x; \
})
#else
#define __ignore_value(x) ((void)(x))
#endif
#endif /* __CR_COMPILER_H__ */
| 4,759 | 30.733333 | 78 |
h
|
criu
|
criu-master/include/common/list.h
|
#ifndef __CR_LIST_H__
#define __CR_LIST_H__
/*
* Double linked lists.
*/
#include <stddef.h>
#include "common/compiler.h"
#define POISON_POINTER_DELTA 0
#define LIST_POISON1 ((void *)0x00100100 + POISON_POINTER_DELTA)
#define LIST_POISON2 ((void *)0x00200200 + POISON_POINTER_DELTA)
struct list_head {
struct list_head *prev, *next;
};
#define LIST_HEAD_INIT(name) \
{ \
&(name), &(name) \
}
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
next->prev = prev;
prev->next = next;
}
static inline void __list_del_entry(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
}
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
static inline void list_replace(struct list_head *old, struct list_head *new)
{
new->next = old->next;
new->next->prev = new;
new->prev = old->prev;
new->prev->next = new;
}
static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
list_replace(old, new);
INIT_LIST_HEAD(old);
}
static inline void list_del_init(struct list_head *entry)
{
__list_del_entry(entry);
INIT_LIST_HEAD(entry);
}
static inline void list_move(struct list_head *list, struct list_head *head)
{
__list_del_entry(list);
list_add(list, head);
}
static inline void list_move_tail(struct list_head *list, struct list_head *head)
{
__list_del_entry(list);
list_add_tail(list, head);
}
static inline int list_is_last(const struct list_head *list, const struct list_head *head)
{
return list->next == head;
}
static inline int list_is_first(const struct list_head *list, const struct list_head *head)
{
return list->prev == head;
}
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}
static inline int list_empty_careful(const struct list_head *head)
{
struct list_head *next = head->next;
return (next == head) && (next == head->prev);
}
static inline void list_rotate_left(struct list_head *head)
{
struct list_head *first;
if (!list_empty(head)) {
first = head->next;
list_move_tail(first, head);
}
}
static inline int list_is_singular(const struct list_head *head)
{
return !list_empty(head) && (head->next == head->prev);
}
static inline void __list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
struct list_head *new_first = entry->next;
list->next = head->next;
list->next->prev = list;
list->prev = entry;
entry->next = list;
head->next = new_first;
new_first->prev = head;
}
static inline void list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
if (list_empty(head))
return;
if (list_is_singular(head) && (head->next != entry && head != entry))
return;
if (entry == head)
INIT_LIST_HEAD(list);
else
__list_cut_position(list, head, entry);
}
static inline void __list_splice(const struct list_head *list, struct list_head *prev, struct list_head *next)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
first->prev = prev;
prev->next = first;
last->next = next;
next->prev = last;
}
static inline void list_splice(const struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head, head->next);
}
static inline void list_splice_tail(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head->prev, head);
}
static inline void list_splice_init(struct list_head *list, struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head, head->next);
INIT_LIST_HEAD(list);
}
}
static inline void list_splice_tail_init(struct list_head *list, struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head->prev, head);
INIT_LIST_HEAD(list);
}
}
#define list_entry(ptr, type, member) container_of(ptr, type, member)
#define list_first_entry(ptr, type, member) list_entry((ptr)->next, type, member)
#define list_for_each(pos, head) for (pos = (head)->next; pos != (head); pos = pos->next)
#define list_for_each_prev(pos, head) for (pos = (head)->prev; pos != (head); pos = pos->prev)
#define list_for_each_safe(pos, n, head) for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
#define list_for_each_prev_safe(pos, n, head) \
for (pos = (head)->prev, n = pos->prev; pos != (head); pos = n, n = pos->prev)
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_reverse(pos, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
#define list_prepare_entry(pos, head, member) ((pos) ?: list_entry(head, typeof(*pos), member))
#define list_for_each_entry_continue(pos, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_continue_reverse(pos, head, member) \
for (pos = list_entry(pos->member.prev, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
#define list_for_each_entry_from(pos, head, member) \
for (; &pos->member != (head); pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_continue(pos, n, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_from(pos, n, head, member) \
for (n = list_entry(pos->member.next, typeof(*pos), member); &pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_reverse(pos, n, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member), \
n = list_entry(pos->member.prev, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.prev, typeof(*n), member))
#define list_safe_reset_next(pos, n, member) n = list_entry(pos->member.next, typeof(*pos), member)
/*
* Double linked lists with a single pointer list head.
*/
struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next, **pprev;
};
#define HLIST_HEAD_INIT \
{ \
.first = NULL \
}
#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL }
#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
static inline void INIT_HLIST_NODE(struct hlist_node *h)
{
h->next = NULL;
h->pprev = NULL;
}
static inline int hlist_unhashed(const struct hlist_node *h)
{
return !h->pprev;
}
static inline int hlist_empty(const struct hlist_head *h)
{
return !h->first;
}
static inline void __hlist_del(struct hlist_node *n)
{
struct hlist_node *next = n->next;
struct hlist_node **pprev = n->pprev;
*pprev = next;
if (next)
next->pprev = pprev;
}
static inline void hlist_del(struct hlist_node *n)
{
__hlist_del(n);
n->next = LIST_POISON1;
n->pprev = LIST_POISON2;
}
static inline void hlist_del_init(struct hlist_node *n)
{
if (!hlist_unhashed(n)) {
__hlist_del(n);
INIT_HLIST_NODE(n);
}
}
static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
struct hlist_node *first = h->first;
n->next = first;
if (first)
first->pprev = &n->next;
h->first = n;
n->pprev = &h->first;
}
/* next must be != NULL */
static inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next)
{
n->pprev = next->pprev;
n->next = next;
next->pprev = &n->next;
*(n->pprev) = n;
}
static inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next)
{
next->next = n->next;
n->next = next;
next->pprev = &n->next;
if (next->next)
next->next->pprev = &next->next;
}
/* after that we'll appear to be on some hlist and hlist_del will work */
static inline void hlist_add_fake(struct hlist_node *n)
{
n->pprev = &n->next;
}
/*
* Move a list from one list head to another. Fixup the pprev
* reference of the first entry if it exists.
*/
static inline void hlist_move_list(struct hlist_head *old, struct hlist_head *new)
{
new->first = old->first;
if (new->first)
new->first->pprev = &new->first;
old->first = NULL;
}
#define hlist_entry(ptr, type, member) container_of(ptr, type, member)
#define hlist_for_each(pos, head) for (pos = (head)->first; pos; pos = pos->next)
#define hlist_for_each_safe(pos, n, head) \
for (pos = (head)->first; pos && ({ \
n = pos->next; \
1; \
}); \
pos = n)
#define hlist_entry_safe(ptr, type, member) (ptr) ? hlist_entry(ptr, type, member) : NULL
#define hlist_for_each_entry(pos, head, member) \
for (pos = hlist_entry_safe((head)->first, typeof(*(pos)), member); pos; \
pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_continue(pos, member) \
for (pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member); pos; \
pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_from(pos, member) \
for (; pos; pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_safe(pos, n, head, member) \
for (pos = hlist_entry_safe((head)->first, typeof(*pos), member); pos && ({ \
n = pos->member.next; \
1; \
}); \
pos = hlist_entry_safe(n, typeof(*pos), member))
#endif /* __CR_LIST_H__ */
| 11,166 | 27.633333 | 119 |
h
|
criu
|
criu-master/include/common/lock.h
|
#ifndef __CR_COMMON_LOCK_H__
#define __CR_COMMON_LOCK_H__
#include <stdint.h>
#include <linux/futex.h>
#include <sys/time.h>
#include <limits.h>
#include <errno.h>
#include "common/asm/atomic.h"
#include "common/compiler.h"
/* scan-build complains about dereferencing a NULL pointer here. */
#ifndef __clang_analyzer__
#define LOCK_BUG_ON(condition) \
if ((condition)) \
*(volatile unsigned long *)NULL = 0xdead0000 + __LINE__
#define LOCK_BUG() LOCK_BUG_ON(1)
#endif /* __clang_analyzer__ */
#ifdef CR_NOGLIBC
#include <compel/plugins/std/syscall.h>
#else
#include <unistd.h>
#include <sys/syscall.h>
static inline long sys_futex(uint32_t *addr1, int op, uint32_t val1, struct timespec *timeout, uint32_t *addr2,
uint32_t val3)
{
int rc = syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
if (rc == -1)
rc = -errno;
return rc;
}
#endif
typedef struct {
atomic_t raw;
} __aligned(sizeof(int)) futex_t;
#define FUTEX_ABORT_FLAG (0x80000000)
#define FUTEX_ABORT_RAW (-1U)
/* Get current futex @f value */
static inline uint32_t futex_get(futex_t *f)
{
return atomic_read(&f->raw);
}
/* Set futex @f value to @v */
static inline void futex_set(futex_t *f, uint32_t v)
{
atomic_set(&f->raw, (int)v);
}
#define futex_init(f) futex_set(f, 0)
/* Wait on futex @__f value @__v become in condition @__c */
#define futex_wait_if_cond(__f, __v, __cond) \
do { \
int ret; \
uint32_t tmp; \
\
while (1) { \
struct timespec to = { .tv_sec = 120 }; \
tmp = futex_get(__f); \
if ((tmp & FUTEX_ABORT_FLAG) || (tmp __cond(__v))) \
break; \
ret = sys_futex((uint32_t *)&(__f)->raw.counter, FUTEX_WAIT, tmp, &to, NULL, 0); \
if (ret == -ETIMEDOUT) \
continue; \
if (ret == -EINTR || ret == -EWOULDBLOCK) \
continue; \
if (ret < 0) \
LOCK_BUG(); \
} \
} while (0)
/* Set futex @f to @v and wake up all waiters */
static inline void futex_set_and_wake(futex_t *f, uint32_t v)
{
atomic_set(&f->raw, (int)v);
LOCK_BUG_ON(sys_futex((uint32_t *)&f->raw.counter, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Wake up all futex @f waiters */
static inline void futex_wake(futex_t *f)
{
LOCK_BUG_ON(sys_futex((uint32_t *)&f->raw.counter, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Mark futex @f as wait abort needed and wake up all waiters */
static inline void futex_abort_and_wake(futex_t *f)
{
BUILD_BUG_ON(!(FUTEX_ABORT_RAW & FUTEX_ABORT_FLAG));
futex_set_and_wake(f, FUTEX_ABORT_RAW);
}
/* Decrement futex @f value and wake up all waiters */
static inline void futex_dec_and_wake(futex_t *f)
{
atomic_dec(&f->raw);
LOCK_BUG_ON(sys_futex((uint32_t *)&f->raw.counter, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Increment futex @f value and wake up all waiters */
static inline void futex_inc_and_wake(futex_t *f)
{
atomic_inc(&f->raw);
LOCK_BUG_ON(sys_futex((uint32_t *)&f->raw.counter, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Plain increment futex @f value */
static inline void futex_inc(futex_t *f)
{
atomic_inc(&f->raw);
}
/* Plain decrement futex @f value */
static inline void futex_dec(futex_t *f)
{
atomic_dec(&f->raw);
}
/* Wait until futex @f value become @v */
#define futex_wait_until(f, v) futex_wait_if_cond(f, v, ==)
/* Wait while futex @f value is greater than @v */
#define futex_wait_while_gt(f, v) futex_wait_if_cond(f, v, <=)
/* Wait while futex @f value is less than @v */
#define futex_wait_while_lt(f, v) futex_wait_if_cond(f, v, >=)
/* Wait while futex @f value is equal to @v */
#define futex_wait_while_eq(f, v) futex_wait_if_cond(f, v, !=)
/* Wait while futex @f value is @v */
static inline void futex_wait_while(futex_t *f, uint32_t v)
{
while ((uint32_t)atomic_read(&f->raw) == v) {
int ret = sys_futex((uint32_t *)&f->raw.counter, FUTEX_WAIT, v, NULL, NULL, 0);
LOCK_BUG_ON(ret < 0 && ret != -EWOULDBLOCK);
}
}
typedef struct {
atomic_t raw;
} mutex_t;
static inline void mutex_init(mutex_t *m)
{
uint32_t c = 0;
atomic_set(&m->raw, (int)c);
}
static inline void mutex_lock(mutex_t *m)
{
uint32_t c;
int ret;
while ((c = (uint32_t)atomic_inc_return(&m->raw)) != 1) {
ret = sys_futex((uint32_t *)&m->raw.counter, FUTEX_WAIT, c, NULL, NULL, 0);
LOCK_BUG_ON(ret < 0 && ret != -EWOULDBLOCK);
}
}
static inline void mutex_unlock(mutex_t *m)
{
uint32_t c = 0;
atomic_set(&m->raw, (int)c);
LOCK_BUG_ON(sys_futex((uint32_t *)&m->raw.counter, FUTEX_WAKE, 1, NULL, NULL, 0) < 0);
}
#endif /* __CR_COMMON_LOCK_H__ */
| 5,590 | 31.317919 | 111 |
h
|
criu
|
criu-master/include/common/scm-code.c
|
#ifndef __sys
#error "The __sys macro is required"
#endif
static void scm_fdset_init_chunk(struct scm_fdset *fdset, int nr_fds, void *data, unsigned ch_size)
{
struct cmsghdr *cmsg;
static char dummy;
fdset->hdr.msg_controllen = CMSG_LEN(sizeof(int) * nr_fds);
cmsg = CMSG_FIRSTHDR(&fdset->hdr);
cmsg->cmsg_len = fdset->hdr.msg_controllen;
if (data) {
fdset->iov.iov_base = data;
fdset->iov.iov_len = nr_fds * ch_size;
} else {
fdset->iov.iov_base = &dummy;
fdset->iov.iov_len = 1;
}
}
static int *scm_fdset_init(struct scm_fdset *fdset, struct sockaddr_un *saddr, int saddr_len)
{
struct cmsghdr *cmsg;
BUILD_BUG_ON(sizeof(fdset->msg_buf) < (CMSG_SPACE(sizeof(int) * CR_SCM_MAX_FD)));
fdset->iov.iov_base = (void *)0xdeadbeef;
fdset->hdr.msg_iov = &fdset->iov;
fdset->hdr.msg_iovlen = 1;
fdset->hdr.msg_name = (struct sockaddr *)saddr;
fdset->hdr.msg_namelen = saddr_len;
fdset->hdr.msg_control = &fdset->msg_buf;
fdset->hdr.msg_controllen = CMSG_LEN(sizeof(int) * CR_SCM_MAX_FD);
cmsg = CMSG_FIRSTHDR(&fdset->hdr);
cmsg->cmsg_len = fdset->hdr.msg_controllen;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
return (int *)CMSG_DATA(cmsg);
}
int send_fds(int sock, struct sockaddr_un *saddr, int len, int *fds, int nr_fds, void *data, unsigned ch_size)
{
/* In musl_libc the msghdr structure has pads which has to be zeroed */
struct scm_fdset fdset = {};
int *cmsg_data;
int i, min_fd, ret;
cmsg_data = scm_fdset_init(&fdset, saddr, len);
for (i = 0; i < nr_fds; i += min_fd) {
min_fd = min(CR_SCM_MAX_FD, nr_fds - i);
scm_fdset_init_chunk(&fdset, min_fd, data, ch_size);
memcpy(cmsg_data, &fds[i], sizeof(int) * min_fd);
ret = __sys(sendmsg)(sock, &fdset.hdr, 0);
if (ret <= 0)
return ret ?: -1;
if (data)
data += min_fd * ch_size;
}
return 0;
}
int __recv_fds(int sock, int *fds, int nr_fds, void *data, unsigned ch_size, int flags)
{
/* In musl_libc the msghdr structure has pads which has to be zeroed */
struct scm_fdset fdset = {};
struct cmsghdr *cmsg;
int *cmsg_data;
int ret;
int i, min_fd;
cmsg_data = scm_fdset_init(&fdset, NULL, 0);
for (i = 0; i < nr_fds; i += min_fd) {
min_fd = min(CR_SCM_MAX_FD, nr_fds - i);
scm_fdset_init_chunk(&fdset, min_fd, data, ch_size);
ret = __sys(recvmsg)(sock, &fdset.hdr, flags);
if (ret <= 0)
return ret ? __sys_err(ret) : -ENOMSG;
cmsg = CMSG_FIRSTHDR(&fdset.hdr);
if (!cmsg || cmsg->cmsg_type != SCM_RIGHTS)
return -EINVAL;
if (fdset.hdr.msg_flags & MSG_CTRUNC)
return -ENFILE;
min_fd = (cmsg->cmsg_len - sizeof(struct cmsghdr)) / sizeof(int);
/*
* In case if kernel screwed the recipient, most probably
* the caller stack frame will be overwritten, just scream
* and exit.
*
* FIXME Need to sanitize util.h to be able to include it
* into files which do not have glibc and a couple of
* sys_write_ helpers. Meawhile opencoded BUG_ON here.
*/
BUG_ON(min_fd > CR_SCM_MAX_FD);
if (unlikely(min_fd <= 0))
return -EBADFD;
memcpy(&fds[i], cmsg_data, sizeof(int) * min_fd);
if (data)
data += ch_size * min_fd;
}
return 0;
}
| 3,135 | 25.576271 | 110 |
c
|
criu
|
criu-master/include/common/scm.h
|
#ifndef __COMMON_SCM_H__
#define __COMMON_SCM_H__
#include <stdint.h>
#include <stdbool.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
/*
* Because of kernel doing kmalloc for user data passed
* in SCM messages, and there is kernel's SCM_MAX_FD as a limit
* for descriptors passed at once we're trying to reduce
* the pressue on kernel memory manager and use predefined
* known to work well size of the message buffer.
*/
#define CR_SCM_MSG_SIZE (1024)
#define CR_SCM_MAX_FD (252)
struct scm_fdset {
struct msghdr hdr;
struct iovec iov;
char msg_buf[CR_SCM_MSG_SIZE];
};
#ifndef F_GETOWNER_UIDS
#define F_GETOWNER_UIDS 17
#endif
extern int send_fds(int sock, struct sockaddr_un *saddr, int len, int *fds, int nr_fds, void *data, unsigned ch_size);
extern int __recv_fds(int sock, int *fds, int nr_fds, void *data, unsigned ch_size, int flags);
static inline int recv_fds(int sock, int *fds, int nr_fds, void *data, unsigned ch_size)
{
return __recv_fds(sock, fds, nr_fds, data, ch_size, 0);
}
static inline int send_fd(int sock, struct sockaddr_un *saddr, int saddr_len, int fd)
{
return send_fds(sock, saddr, saddr_len, &fd, 1, NULL, 0);
}
static inline int recv_fd(int sock)
{
int fd, ret;
ret = recv_fds(sock, &fd, 1, NULL, 0);
if (ret)
return -1;
return fd;
}
#endif
| 1,319 | 23.444444 | 118 |
h
|
criu
|
criu-master/include/common/xmalloc.h
|
#ifndef __COMMON_XMALLOC_H__
#define __COMMON_XMALLOC_H__
#include <stdlib.h>
#include <string.h>
#ifndef pr_err
#error "Macro pr_err is needed."
#endif
#define __xalloc(op, size, ...) \
({ \
void *___p = op(__VA_ARGS__); \
if (!___p) \
pr_err("%s: Can't allocate %li bytes\n", __func__, (long)(size)); \
___p; \
})
#define xstrdup(str) __xalloc(strdup, strlen(str) + 1, str)
#define xmalloc(size) __xalloc(malloc, size, size)
#define xzalloc(size) __xalloc(calloc, size, 1, size)
#define xrealloc(p, size) __xalloc(realloc, size, p, size)
#define xfree(p) free(p)
#define xrealloc_safe(pptr, size) \
({ \
int __ret = -1; \
void *new = xrealloc(*pptr, size); \
if (new) { \
*pptr = new; \
__ret = 0; \
} \
__ret; \
})
#define xmemdup(ptr, size) \
({ \
void *new = xmalloc(size); \
if (new) \
memcpy(new, ptr, size); \
new; \
})
#define memzero_p(p) memset(p, 0, sizeof(*p))
#define memzero(p, size) memset(p, 0, size)
/*
* Helper for allocating trees with single xmalloc.
* This one advances the void *pointer on s bytes and
* returns the previous value. Use like this
*
* m = xmalloc(total_size);
* a = xptr_pull(&m, tree_root_t);
* a->b = xptr_pull(&m, leaf_a_t);
* a->c = xptr_pull(&m, leaf_c_t);
* ...
*/
static inline void *xptr_pull_s(void **m, size_t s)
{
void *ret = (*m);
(*m) += s;
return ret;
}
#define xptr_pull(m, type) xptr_pull_s(m, sizeof(type))
#endif /* __CR_XMALLOC_H__ */
| 2,079 | 29.144928 | 91 |
h
|
criu
|
criu-master/include/common/arch/aarch64/asm/page.h
|
#ifndef __CR_ASM_PAGE_H__
#define __CR_ASM_PAGE_H__
#define ARCH_HAS_LONG_PAGES
#ifndef CR_NOGLIBC
#include <string.h> /* ffsl() */
#include <unistd.h> /* _SC_PAGESIZE */
extern unsigned __page_size;
extern unsigned __page_shift;
static inline unsigned page_size(void)
{
if (!__page_size)
__page_size = sysconf(_SC_PAGESIZE);
return __page_size;
}
static inline unsigned page_shift(void)
{
if (!__page_shift)
__page_shift = (ffsl(page_size()) - 1);
return __page_shift;
}
/*
* Don't add ifdefs for PAGE_SIZE: if any header defines it as a constant
* on aarch64, then we need refrain using PAGE_SIZE in criu and use
* page_size() across sources (as it may differ on aarch64).
*/
#define PAGE_SIZE page_size()
#define PAGE_MASK (~(PAGE_SIZE - 1))
#define PAGE_SHIFT page_shift()
#define PAGE_PFN(addr) ((addr) / PAGE_SIZE)
#else /* CR_NOGLIBC */
extern unsigned page_size(void);
#define PAGE_SIZE page_size()
#endif /* CR_NOGLIBC */
#endif /* __CR_ASM_PAGE_H__ */
| 986 | 20.933333 | 73 |
h
|
criu
|
criu-master/include/common/arch/arm/asm/processor.h
|
#ifndef __CR_PROCESSOR_H__
#define __CR_PROCESSOR_H__
/* Copied from linux kernel arch/arm/include/asm/unified.h */
#define WASM(instr) #instr
/* Copied from linux kernel arch/arm/include/asm/processor.h */
#define __ALT_SMP_ASM(smp, up) \
"9998: " smp "\n" \
" .pushsection \".alt.smp.init\", \"a\"\n" \
" .long 9998b\n" \
" " up "\n" \
" .popsection\n"
static inline void prefetchw(const void *ptr)
{
__asm__ __volatile__(
".arch_extension mp\n" __ALT_SMP_ASM(WASM(pldw) "\t%a0", WASM(pld) "\t%a0")::"p"(ptr));
}
#endif /* __CR_PROCESSOR_H__ */
| 656 | 26.375 | 89 |
h
|
criu
|
criu-master/include/common/arch/mips/asm/bitops.h
|
#ifndef _LINUX_BITOPS_H
#define _LINUX_BITOPS_H
#include <asm/types.h>
#include "common/compiler.h"
#include "common/asm-generic/bitops.h"
/**
* test_and_set_bit - Set a bit and return its old value
* @nr: Bit to set
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_set_bit(unsigned long nr, volatile unsigned long *addr)
{
unsigned long *m = ((unsigned long *)addr) + (nr >> 6);
unsigned long temp = 0;
unsigned long res;
int bit = nr & 63UL;
do {
__asm__ __volatile__(" .set mips3 \n"
" lld %0, %1 # test_and_set_bit \n"
" or %2, %0, %3 \n"
" scd %2, %1 \n"
" .set mips0 \n"
: "=&r"(temp), "+m"(*m), "=&r"(res)
: "r"(1UL << bit)
: "memory");
} while (unlikely(!res));
res = temp & (1UL << bit);
return res != 0;
}
#endif
| 926 | 22.175 | 82 |
h
|
criu
|
criu-master/include/common/arch/mips/asm/cmpxchg.h
|
#ifndef __CR_CMPXCHG_H__
#define __CR_CMPXCHG_H__
#define __cmpxchg_asm(ld, st, m, old, new) \
({ \
__typeof(*(m)) __ret; \
\
if (kernel_uses_llsc) { \
__asm__ __volatile__(" .set push \n" \
" .set noat \n" \
" .set mips3 \n" \
"1: " ld " %0, %2 # __cmpxchg_asm \n" \
" bne %0, %z3, 2f \n" \
" .set mips0 \n" \
" move $1, %z4 \n" \
" .set mips3 \n" \
" " st " $1, %1 \n" \
" beqz $1, 1b \n" \
" .set pop \n" \
"2: \n" \
: "=&r"(__ret), "=R"(*m) \
: "R"(*m), "Jr"(old), "Jr"(new) \
: "memory"); \
} else { \
} \
\
__ret; \
})
/*
* This function doesn't exist, so you'll get a linker error
* if something tries to do an invalid cmpxchg().
*/
extern void __cmpxchg_called_with_bad_pointer(void);
#define __cmpxchg(ptr, old, new, pre_barrier, post_barrier) \
({ \
__typeof__(ptr) __ptr = (ptr); \
__typeof__(*(ptr)) __old = (old); \
__typeof__(*(ptr)) __new = (new); \
__typeof__(*(ptr)) __res = 0; \
\
pre_barrier; \
\
switch (sizeof(*(__ptr))) { \
case 4: \
__res = __cmpxchg_asm("ll", "sc", __ptr, __old, __new); \
break; \
case 8: \
if (sizeof(long) == 8) { \
__res = __cmpxchg_asm("lld", "scd", __ptr, __old, __new); \
break; \
} \
default: \
__cmpxchg_called_with_bad_pointer(); \
break; \
} \
\
post_barrier; \
\
__res; \
})
#define cmpxchg(ptr, old, new) __cmpxchg(ptr, old, new, smp_mb__before_llsc(), smp_llsc_mb())
#endif /* __CR_CMPXCHG_H__ */
| 4,028 | 60.045455 | 93 |
h
|
criu
|
criu-master/include/common/arch/mips/asm/fls64.h
|
#ifndef _ASM_GENERIC_BITOPS_FLS64_H_
#define _ASM_GENERIC_BITOPS_FLS64_H_
#include <asm/types.h>
/**
* fls64 - find last set bit in a 64-bit word
* @x: the word to search
*
* This is defined in a similar way as the libc and compiler builtin
* ffsll, but returns the position of the most significant set bit.
*
* fls64(value) returns 0 if value is 0 or the position of the last
* set bit if value is nonzero. The last (most significant) bit is
* at position 64.
*/
#include "common/arch/mips/asm/bitops.h"
#if BITS_PER_LONG == 32
static __always_inline int fls64(__u64 x)
{
__u32 h = x >> 32;
if (h)
return fls(h) + 32;
return fls(x);
}
#elif BITS_PER_LONG == 64
extern unsigned long __fls(unsigned long word);
static __always_inline int fls64(__u64 x)
{
if (x == 0)
return 0;
return __fls(x) + 1;
}
#else
#error BITS_PER_LONG not 32 or 64
#endif
#endif /* _ASM_GENERIC_BITOPS_FLS64_H_ */
| 910 | 22.358974 | 68 |
h
|
criu
|
criu-master/include/common/arch/ppc64/asm/bitops.h
|
#ifndef __CR_BITOPS_H__
#define __CR_BITOPS_H__
/*
* PowerPC atomic bit operations.
*
* Merged version by David Gibson <[email protected]>.
* Based on ppc64 versions by: Dave Engebretsen, Todd Inglett, Don
* Reed, Pat McCarthy, Peter Bergner, Anton Blanchard. They
* originally took it from the ppc32 code.
*
* Within a word, bits are numbered LSB first. Lot's of places make
* this assumption by directly testing bits with (val & (1<<nr)).
* This can cause confusion for large (> 1 word) bitmaps on a
* big-endian system because, unlike little endian, the number of each
* bit depends on the word size.
*
* The bitop functions are defined to work on unsigned longs, so for a
* ppc64 system the bits end up numbered:
* |63..............0|127............64|191...........128|255...........192|
* and on ppc32:
* |31.....0|63....32|95....64|127...96|159..128|191..160|223..192|255..224|
*
* There are a few little-endian macros used mostly for filesystem
* bitmaps, these work on similar bit arrays layouts, but
* byte-oriented:
* |7...0|15...8|23...16|31...24|39...32|47...40|55...48|63...56|
*
* The main difference is that bit 3-5 (64b) or 3-4 (32b) in the bit
* number field needs to be reversed compared to the big-endian bit
* fields. This can be achieved by XOR with 0x38 (64b) or 0x18 (32b).
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* --
* Copied from the kernel file arch/powerpc/include/asm/bitops.h
*/
#include "common/compiler.h"
#include "common/asm/bitsperlong.h"
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)
#define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)]
#define BITMAP_SIZE(name) (sizeof(name) * CHAR_BIT)
#define __stringify_in_c(...) #__VA_ARGS__
#define stringify_in_c(...) __stringify_in_c(__VA_ARGS__) " "
#define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG))
#define BIT_WORD(nr) ((nr) / BITS_PER_LONG)
/* PPC bit number conversion */
#define PPC_BITLSHIFT(be) (BITS_PER_LONG - 1 - (be))
#define PPC_BIT(bit) (1UL << PPC_BITLSHIFT(bit))
#define PPC_BITMASK(bs, be) ((PPC_BIT(bs) - PPC_BIT(be)) | PPC_BIT(bs))
#define PPC_INST_LDARX 0x7c0000a8
#define ___PPC_RA(a) (((a)&0x1f) << 16)
#define ___PPC_RB(b) (((b)&0x1f) << 11)
#define ___PPC_RS(s) (((s)&0x1f) << 21)
#define __PPC_EH(eh) (((eh)&0x1) << 0)
#define ___PPC_RT(t) ___PPC_RS(t)
#define PPC_LDARX(t, a, b, eh) \
stringify_in_c(.long PPC_INST_LDARX | ___PPC_RT(t) | ___PPC_RA(a) | ___PPC_RB(b) | __PPC_EH(eh))
#define PPC_LLARX(t, a, b, eh) PPC_LDARX(t, a, b, eh)
/* clang-format off */
/* Macro for generating the ***_bits() functions */
#define DEFINE_BITOP(fn, op) \
static __inline__ void fn(unsigned long mask, \
volatile unsigned long *_p) \
{ \
unsigned long old; \
unsigned long *p = (unsigned long *)_p; \
__asm__ __volatile__ ( \
"1: ldarx %0,0,%3\n" \
stringify_in_c(op) "%0,%0,%2\n" \
"stdcx. %0,0,%3\n" \
"bne- 1b\n" \
: "=&r" (old), "+m" (*p) \
: "r" (mask), "r" (p) \
: "cc", "memory"); \
}
/* clang-format on */
DEFINE_BITOP(set_bits, or)
DEFINE_BITOP(clear_bits, andc)
DEFINE_BITOP(change_bits, xor)
static __inline__ void set_bit(int nr, volatile unsigned long *addr)
{
set_bits(BIT_MASK(nr), addr + BIT_WORD(nr));
}
static __inline__ void clear_bit(int nr, volatile unsigned long *addr)
{
clear_bits(BIT_MASK(nr), addr + BIT_WORD(nr));
}
static __inline__ void change_bit(int nr, volatile unsigned long *addr)
{
change_bits(BIT_MASK(nr), addr + BIT_WORD(nr));
}
static inline int test_bit(int nr, const volatile unsigned long *addr)
{
return 1UL & (addr[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1)));
}
/* Like DEFINE_BITOP(), with changes to the arguments to 'op' and the output
* operands. */
/* clang-format off */
#define DEFINE_TESTOP(fn, op, prefix, postfix, eh) \
static __inline__ unsigned long fn( \
unsigned long mask, \
volatile unsigned long *_p) \
{ \
unsigned long old, t; \
unsigned long *p = (unsigned long *)_p; \
__asm__ __volatile__ ( \
prefix \
"1:" PPC_LLARX(%0,0,%3,eh) "\n" \
stringify_in_c(op) "%1,%0,%2\n" \
"stdcx. %1,0,%3\n" \
"bne- 1b\n" \
postfix \
: "=&r" (old), "=&r" (t) \
: "r" (mask), "r" (p) \
: "cc", "memory"); \
return (old & mask); \
}
/* clang-format on */
DEFINE_TESTOP(test_and_set_bits, or, "\nLWSYNC\n", "\nsync\n", 0)
static __inline__ int test_and_set_bit(unsigned long nr, volatile unsigned long *addr)
{
return test_and_set_bits(BIT_MASK(nr), addr + BIT_WORD(nr)) != 0;
}
/*
* Return the zero-based bit position (LE, not IBM bit numbering) of
* the most significant 1-bit in a double word.
*/
static __inline__ __attribute__((const)) int __ilog2(unsigned long x)
{
int lz;
asm("cntlzd %0,%1" : "=r"(lz) : "r"(x));
return BITS_PER_LONG - 1 - lz;
}
static __inline__ unsigned long __ffs(unsigned long x)
{
return __ilog2(x & -x);
}
#define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
/*
* Find the next set bit in a memory region.
*/
static inline unsigned long find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BITOP_WORD(offset);
unsigned long result = offset & ~(BITS_PER_LONG - 1);
unsigned long tmp;
if (offset >= size)
return size;
size -= result;
offset %= BITS_PER_LONG;
if (offset) {
tmp = *(p++);
tmp &= (~0UL << offset);
if (size < BITS_PER_LONG)
goto found_first;
if (tmp)
goto found_middle;
size -= BITS_PER_LONG;
result += BITS_PER_LONG;
}
while (size & ~(BITS_PER_LONG - 1)) {
if ((tmp = *(p++)))
goto found_middle;
result += BITS_PER_LONG;
size -= BITS_PER_LONG;
}
if (!size)
return result;
tmp = *p;
found_first:
tmp &= (~0UL >> (BITS_PER_LONG - size));
if (tmp == 0UL) /* Are any bits set? */
return result + size; /* Nope. */
found_middle:
return result + __ffs(tmp);
}
#define for_each_bit(i, bitmask) \
for (i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), 0); i < BITMAP_SIZE(bitmask); \
i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), i + 1))
#endif /* __CR_BITOPS_H__ */
| 6,669 | 30.611374 | 110 |
h
|
criu
|
criu-master/include/common/arch/ppc64/asm/cmpxchg.h
|
#ifndef __CR_CMPXCHG_H__
#define __CR_CMPXCHG_H__
/*
* Copied from kernel header file arch/powerpc/include/asm/cmpxchg.h
*/
#define PPC_ACQUIRE_BARRIER "isync \n"
#define PPC_RELEASE_BARRIER "lwsync \n"
/*
* Compare and exchange - if *p == old, set it to new,
* and return the old value of *p.
*/
static __always_inline unsigned long __cmpxchg_u32(volatile unsigned int *p, unsigned long old, unsigned long new)
{
unsigned int prev;
__asm__ __volatile__(PPC_RELEASE_BARRIER "1: lwarx %0,0,%2 # __cmpxchg_u32\n\
cmpw 0,%0,%3\n\
bne- 2f\n"
" stwcx. %4,0,%2\n\
bne- 1b \n" PPC_ACQUIRE_BARRIER "\n\
2:"
: "=&r"(prev), "+m"(*p)
: "r"(p), "r"(old), "r"(new)
: "cc", "memory");
return prev;
}
static __always_inline unsigned long __cmpxchg_u64(volatile unsigned long *p, unsigned long old, unsigned long new)
{
unsigned long prev;
__asm__ __volatile__(PPC_RELEASE_BARRIER "1: ldarx %0,0,%2 # __cmpxchg_u64\n\
cmpd 0,%0,%3\n\
bne- 2f\n\
stdcx. %4,0,%2\n\
bne- 1b \n" PPC_ACQUIRE_BARRIER "\n\
2:"
: "=&r"(prev), "+m"(*p)
: "r"(p), "r"(old), "r"(new)
: "cc", "memory");
return prev;
}
/* This function doesn't exist, so you'll get a linker error
if something tries to do an invalid cmpxchg(). */
#ifdef CR_DEBUG
static inline void __cmpxchg_called_with_bad_pointer(void)
{
__asm__ __volatile__("1: twi 31,0,0 # trap\n"
" b 1b"
:
:
: "memory");
}
#else
extern void __cmpxchg_called_with_bad_pointer(void);
#endif
static __always_inline unsigned long __cmpxchg(volatile void *ptr, unsigned long old, unsigned long new,
unsigned int size)
{
switch (size) {
case 4:
return __cmpxchg_u32(ptr, old, new);
case 8:
return __cmpxchg_u64(ptr, old, new);
}
__cmpxchg_called_with_bad_pointer();
return old;
}
#define cmpxchg(ptr, o, n) \
({ \
__typeof__(*(ptr)) _o_ = (o); \
__typeof__(*(ptr)) _n_ = (n); \
(__typeof__(*(ptr)))__cmpxchg((ptr), (unsigned long)_o_, (unsigned long)_n_, sizeof(*(ptr))); \
})
#endif /* __CR_CMPXCHG_H__ */
| 2,381 | 26.697674 | 115 |
h
|
criu
|
criu-master/include/common/arch/ppc64/asm/page.h
|
#ifndef __CR_ASM_PAGE_H__
#define __CR_ASM_PAGE_H__
#define ARCH_HAS_LONG_PAGES
#ifndef CR_NOGLIBC
#include <string.h> /* ffsl() */
#include <unistd.h> /* _SC_PAGESIZE */
extern unsigned __page_size;
extern unsigned __page_shift;
static inline unsigned page_size(void)
{
if (!__page_size)
__page_size = sysconf(_SC_PAGESIZE);
return __page_size;
}
static inline unsigned page_shift(void)
{
if (!__page_shift)
__page_shift = (ffsl(page_size()) - 1);
return __page_shift;
}
/*
* Don't add ifdefs for PAGE_SIZE: if any header defines it as a constant
* on ppc64, then we need refrain using PAGE_SIZE in criu and use
* page_size() across sources (as it may differ on ppc64).
*/
#define PAGE_SIZE page_size()
#define PAGE_MASK (~(PAGE_SIZE - 1))
#define PAGE_SHIFT page_shift()
#define PAGE_PFN(addr) ((addr) / PAGE_SIZE)
#else /* CR_NOGLIBC */
extern unsigned page_size(void);
#define PAGE_SIZE page_size()
#endif /* CR_NOGLIBC */
#endif /* __CR_ASM_PAGE_H__ */
| 982 | 20.844444 | 73 |
h
|
criu
|
criu-master/include/common/arch/s390/asm/atomic.h
|
#ifndef __ARCH_S390_ATOMIC__
#define __ARCH_S390_ATOMIC__
#include "common/arch/s390/asm/atomic_ops.h"
#include "common/compiler.h"
#define ATOMIC_INIT(i) \
{ \
(i) \
}
typedef struct {
int counter;
} atomic_t;
static inline int atomic_read(const atomic_t *v)
{
int c;
asm volatile(" l %0,%1\n" : "=d"(c) : "Q"(v->counter));
return c;
}
static inline void atomic_set(atomic_t *v, int i)
{
asm volatile(" st %1,%0\n" : "=Q"(v->counter) : "d"(i));
}
static inline int atomic_add_return(int i, atomic_t *v)
{
return __atomic_add_barrier(i, &v->counter) + i;
}
static inline void atomic_add(int i, atomic_t *v)
{
__atomic_add(i, &v->counter);
}
#define atomic_inc(_v) atomic_add(1, _v)
#define atomic_inc_return(_v) atomic_add_return(1, _v)
#define atomic_sub(_i, _v) atomic_add(-(int)(_i), _v)
#define atomic_sub_return(_i, _v) atomic_add_return(-(int)(_i), _v)
#define atomic_dec(_v) atomic_sub(1, _v)
#define atomic_dec_return(_v) atomic_sub_return(1, _v)
#define atomic_dec_and_test(_v) (atomic_sub_return(1, _v) == 0)
#define ATOMIC_OPS(op) \
static inline void atomic_##op(int i, atomic_t *v) \
{ \
__atomic_##op(i, &v->counter); \
}
ATOMIC_OPS(and)
ATOMIC_OPS(or)
ATOMIC_OPS(xor)
#undef ATOMIC_OPS
static inline int atomic_cmpxchg(atomic_t *v, int old, int new)
{
return __atomic_cmpxchg(&v->counter, old, new);
}
#endif /* __ARCH_S390_ATOMIC__ */
| 1,510 | 22.246154 | 67 |
h
|
criu
|
criu-master/include/common/arch/s390/asm/atomic_ops.h
|
#ifndef __ARCH_S390_ATOMIC_OPS__
#define __ARCH_S390_ATOMIC_OPS__
/* clang-format off */
#define __ATOMIC_OP(op_name, op_string) \
static inline int op_name(int val, int *ptr) \
{ \
int old, new; \
\
asm volatile( \
"0: lr %[new],%[old]\n" \
op_string " %[new],%[val]\n" \
" cs %[old],%[new],%[ptr]\n" \
" jl 0b" \
: [old] "=d" (old), [new] "=&d" (new), [ptr] "+Q" (*ptr)\
: [val] "d" (val), "0" (*ptr) : "cc", "memory"); \
return old; \
}
/* clang-format on */
#define __ATOMIC_OPS(op_name, op_string) \
__ATOMIC_OP(op_name, op_string) \
__ATOMIC_OP(op_name##_barrier, op_string)
__ATOMIC_OPS(__atomic_add, "ar")
__ATOMIC_OPS(__atomic_and, "nr")
__ATOMIC_OPS(__atomic_or, "or")
__ATOMIC_OPS(__atomic_xor, "xr")
#undef __ATOMIC_OPS
/* clang-format off */
#define __ATOMIC64_OP(op_name, op_string) \
static inline long op_name(long val, long *ptr) \
{ \
long old, new; \
\
asm volatile( \
"0: lgr %[new],%[old]\n" \
op_string " %[new],%[val]\n" \
" csg %[old],%[new],%[ptr]\n" \
" jl 0b" \
: [old] "=d" (old), [new] "=&d" (new), [ptr] "+Q" (*ptr)\
: [val] "d" (val), "0" (*ptr) : "cc", "memory"); \
return old; \
}
/* clang-format on */
#define __ATOMIC64_OPS(op_name, op_string) \
__ATOMIC64_OP(op_name, op_string) \
__ATOMIC64_OP(op_name##_barrier, op_string)
__ATOMIC64_OPS(__atomic64_add, "agr")
__ATOMIC64_OPS(__atomic64_and, "ngr")
__ATOMIC64_OPS(__atomic64_or, "ogr")
__ATOMIC64_OPS(__atomic64_xor, "xgr")
#undef __ATOMIC64_OPS
static inline int __atomic_cmpxchg(int *ptr, int old, int new)
{
asm volatile(" cs %[old],%[new],%[ptr]"
: [old] "+d"(old), [ptr] "+Q"(*ptr)
: [new] "d"(new)
: "cc", "memory");
return old;
}
static inline long __atomic64_cmpxchg(long *ptr, long old, long new)
{
asm volatile(" csg %[old],%[new],%[ptr]"
: [old] "+d"(old), [ptr] "+Q"(*ptr)
: [new] "d"(new)
: "cc", "memory");
return old;
}
#endif /* __ARCH_S390_ATOMIC_OPS__ */
| 2,058 | 25.063291 | 68 |
h
|
criu
|
criu-master/include/common/arch/s390/asm/bitops.h
|
#ifndef _S390_BITOPS_H
#define _S390_BITOPS_H
#include "common/asm/bitsperlong.h"
#include "common/compiler.h"
#include "common/arch/s390/asm/atomic_ops.h"
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)
#define __BITOPS_WORDS(bits) (((bits) + BITS_PER_LONG - 1) / BITS_PER_LONG)
#define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)]
#define BITMAP_SIZE(name) (sizeof(name) * CHAR_BIT)
static inline unsigned long *__bitops_word(unsigned long nr, volatile unsigned long *ptr)
{
unsigned long addr;
addr = (unsigned long)ptr + ((nr ^ (nr & (BITS_PER_LONG - 1))) >> 3);
return (unsigned long *)addr;
}
static inline unsigned char *__bitops_byte(unsigned long nr, volatile unsigned long *ptr)
{
return ((unsigned char *)ptr) + ((nr ^ (BITS_PER_LONG - 8)) >> 3);
}
static inline void set_bit(unsigned long nr, volatile unsigned long *ptr)
{
unsigned long *addr = __bitops_word(nr, ptr);
unsigned long mask;
mask = 1UL << (nr & (BITS_PER_LONG - 1));
__atomic64_or((long)mask, (long *)addr);
}
static inline void clear_bit(unsigned long nr, volatile unsigned long *ptr)
{
unsigned long *addr = __bitops_word(nr, ptr);
unsigned long mask;
mask = ~(1UL << (nr & (BITS_PER_LONG - 1)));
__atomic64_and((long)mask, (long *)addr);
}
static inline void change_bit(unsigned long nr, volatile unsigned long *ptr)
{
unsigned long *addr = __bitops_word(nr, ptr);
unsigned long mask;
mask = 1UL << (nr & (BITS_PER_LONG - 1));
__atomic64_xor((long)mask, (long *)addr);
}
static inline int test_and_set_bit(unsigned long nr, volatile unsigned long *ptr)
{
unsigned long *addr = __bitops_word(nr, ptr);
unsigned long old, mask;
mask = 1UL << (nr & (BITS_PER_LONG - 1));
old = __atomic64_or_barrier((long)mask, (long *)addr);
return (old & mask) != 0;
}
static inline int test_bit(unsigned long nr, const volatile unsigned long *ptr)
{
const volatile unsigned char *addr;
addr = ((const volatile unsigned char *)ptr);
addr += (nr ^ (BITS_PER_LONG - 8)) >> 3;
return (*addr >> (nr & 7)) & 1;
}
static inline unsigned char __flogr(unsigned long word)
{
if (__builtin_constant_p(word)) {
unsigned long bit = 0;
if (!word)
return 64;
if (!(word & 0xffffffff00000000UL)) {
word <<= 32;
bit += 32;
}
if (!(word & 0xffff000000000000UL)) {
word <<= 16;
bit += 16;
}
if (!(word & 0xff00000000000000UL)) {
word <<= 8;
bit += 8;
}
if (!(word & 0xf000000000000000UL)) {
word <<= 4;
bit += 4;
}
if (!(word & 0xc000000000000000UL)) {
word <<= 2;
bit += 2;
}
if (!(word & 0x8000000000000000UL)) {
word <<= 1;
bit += 1;
}
return bit;
} else {
return __builtin_clzl(word);
}
}
static inline unsigned long __ffs(unsigned long word)
{
return __flogr(-word & word) ^ (BITS_PER_LONG - 1);
}
#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) & (BITS_PER_LONG - 1)))
static inline unsigned long _find_next_bit(const unsigned long *addr, unsigned long nbits, unsigned long start,
unsigned long invert)
{
unsigned long tmp;
if (!nbits || start >= nbits)
return nbits;
tmp = addr[start / BITS_PER_LONG] ^ invert;
tmp &= BITMAP_FIRST_WORD_MASK(start);
start = round_down(start, BITS_PER_LONG);
while (!tmp) {
start += BITS_PER_LONG;
if (start >= nbits)
return nbits;
tmp = addr[start / BITS_PER_LONG] ^ invert;
}
return min(start + __ffs(tmp), nbits);
}
static inline unsigned long find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset)
{
return _find_next_bit(addr, size, offset, 0UL);
}
#define for_each_bit(i, bitmask) \
for (i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), 0); i < BITMAP_SIZE(bitmask); \
i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), i + 1))
#endif /* _S390_BITOPS_H */
| 3,892 | 24.611842 | 111 |
h
|
criu
|
criu-master/include/common/arch/x86/asm/bitops.h
|
#ifndef __CR_BITOPS_H__
#define __CR_BITOPS_H__
#include <stdbool.h>
#include "common/arch/x86/asm/cmpxchg.h"
#include "common/arch/x86/asm/asm.h"
#include "common/asm/bitsperlong.h"
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)
#define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)]
#define BITMAP_SIZE(name) (sizeof(name) * CHAR_BIT)
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
/* Technically wrong, but this avoids compilation errors on some gcc
versions. */
#define BITOP_ADDR(x) "=m"(*(volatile long *)(x))
#else
#define BITOP_ADDR(x) "+m"(*(volatile long *)(x))
#endif
#define ADDR BITOP_ADDR(addr)
static inline void set_bit(long nr, volatile unsigned long *addr)
{
asm volatile(__ASM_SIZE(bts) " %1,%0" : ADDR : "Ir"(nr) : "memory");
}
static inline void change_bit(long nr, volatile unsigned long *addr)
{
asm volatile(__ASM_SIZE(btc) " %1,%0" : ADDR : "Ir"(nr));
}
static inline bool test_bit(long nr, volatile const unsigned long *addr)
{
bool oldbit;
asm volatile(__ASM_SIZE(bt) " %2,%1" CC_SET(c)
: CC_OUT(c)(oldbit)
: "m"(*(unsigned long *)addr), "Ir"(nr)
: "memory");
return oldbit;
}
static inline void clear_bit(long nr, volatile unsigned long *addr)
{
asm volatile(__ASM_SIZE(btr) " %1,%0" : ADDR : "Ir"(nr));
}
/**
* test_and_set_bit - Set a bit and return its old value
* @nr: Bit to set
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline bool test_and_set_bit(long nr, volatile unsigned long *addr)
{
bool oldbit;
asm(__ASM_SIZE(bts) " %2,%1" CC_SET(c) : CC_OUT(c)(oldbit) : "m"(*(unsigned long *)addr), "Ir"(nr) : "memory");
return oldbit;
}
/**
* __ffs - find first set bit in word
* @word: The word to search
*
* Undefined if no bit exists, so code should check against 0 first.
*/
static inline unsigned long __ffs(unsigned long word)
{
asm("bsf %1,%0" : "=r"(word) : "rm"(word));
return word;
}
#define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
/*
* Find the next set bit in a memory region.
*/
static inline unsigned long find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BITOP_WORD(offset);
unsigned long result = offset & ~(BITS_PER_LONG - 1);
unsigned long tmp;
if (offset >= size)
return size;
size -= result;
offset %= BITS_PER_LONG;
if (offset) {
tmp = *(p++);
tmp &= (~0UL << offset);
if (size < BITS_PER_LONG)
goto found_first;
if (tmp)
goto found_middle;
size -= BITS_PER_LONG;
result += BITS_PER_LONG;
}
while (size & ~(BITS_PER_LONG - 1)) {
if ((tmp = *(p++)))
goto found_middle;
result += BITS_PER_LONG;
size -= BITS_PER_LONG;
}
if (!size)
return result;
tmp = *p;
found_first:
tmp &= (~0UL >> (BITS_PER_LONG - size));
if (tmp == 0UL) /* Are any bits set? */
return result + size; /* Nope. */
found_middle:
return result + __ffs(tmp);
}
#define for_each_bit(i, bitmask) \
for (i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), 0); i < BITMAP_SIZE(bitmask); \
i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), i + 1))
#endif /* __CR_BITOPS_H__ */
| 3,322 | 24.960938 | 112 |
h
|
criu
|
criu-master/include/common/arch/x86/asm/cmpxchg.h
|
#ifndef __CR_CMPXCHG_H__
#define __CR_CMPXCHG_H__
#include <stdint.h>
#define LOCK_PREFIX "\n\tlock; "
#define __X86_CASE_B 1
#define __X86_CASE_W 2
#define __X86_CASE_L 4
#define __X86_CASE_Q 8
/*
* An exchange-type operation, which takes a value and a pointer, and
* returns the old value. Make sure you never reach non-case statement
* here, otherwise behaviour is undefined.
*/
#define __xchg_op(ptr, arg, op, lock) \
({ \
__typeof__(*(ptr)) __ret = (arg); \
switch (sizeof(*(ptr))) { \
case __X86_CASE_B: \
asm volatile(lock #op "b %b0, %1\n" : "+q"(__ret), "+m"(*(ptr)) : : "memory", "cc"); \
break; \
case __X86_CASE_W: \
asm volatile(lock #op "w %w0, %1\n" : "+r"(__ret), "+m"(*(ptr)) : : "memory", "cc"); \
break; \
case __X86_CASE_L: \
asm volatile(lock #op "l %0, %1\n" : "+r"(__ret), "+m"(*(ptr)) : : "memory", "cc"); \
break; \
case __X86_CASE_Q: \
asm volatile(lock #op "q %q0, %1\n" : "+r"(__ret), "+m"(*(ptr)) : : "memory", "cc"); \
break; \
} \
__ret; \
})
#define __xadd(ptr, inc, lock) __xchg_op((ptr), (inc), xadd, lock)
#define xadd(ptr, inc) __xadd((ptr), (inc), "lock ;")
/* Borrowed from linux kernel arch/x86/include/asm/cmpxchg.h */
/*
* Atomic compare and exchange. Compare OLD with MEM, if identical,
* store NEW in MEM. Return the initial value in MEM. Success is
* indicated by comparing RETURN with OLD.
*/
#define __raw_cmpxchg(ptr, old, new, size, lock) \
({ \
__typeof__(*(ptr)) __ret; \
__typeof__(*(ptr)) __old = (old); \
__typeof__(*(ptr)) __new = (new); \
switch (size) { \
case __X86_CASE_B: { \
volatile uint8_t *__ptr = (volatile uint8_t *)(ptr); \
asm volatile(lock "cmpxchgb %2,%1" \
: "=a"(__ret), "+m"(*__ptr) \
: "q"(__new), "0"(__old) \
: "memory"); \
break; \
} \
case __X86_CASE_W: { \
volatile uint16_t *__ptr = (volatile uint16_t *)(ptr); \
asm volatile(lock "cmpxchgw %2,%1" \
: "=a"(__ret), "+m"(*__ptr) \
: "r"(__new), "0"(__old) \
: "memory"); \
break; \
} \
case __X86_CASE_L: { \
volatile uint32_t *__ptr = (volatile uint32_t *)(ptr); \
asm volatile(lock "cmpxchgl %2,%1" \
: "=a"(__ret), "+m"(*__ptr) \
: "r"(__new), "0"(__old) \
: "memory"); \
break; \
} \
case __X86_CASE_Q: { \
volatile uint64_t *__ptr = (volatile uint64_t *)(ptr); \
asm volatile(lock "cmpxchgq %2,%1" \
: "=a"(__ret), "+m"(*__ptr) \
: "r"(__new), "0"(__old) \
: "memory"); \
break; \
} \
} \
__ret; \
})
#define __cmpxchg(ptr, old, new, size) __raw_cmpxchg((ptr), (old), (new), (size), LOCK_PREFIX)
#define cmpxchg(ptr, old, new) __cmpxchg(ptr, old, new, sizeof(*(ptr)))
#endif /* __CR_CMPXCHG_H__ */
| 5,145 | 53.744681 | 110 |
h
|
criu
|
criu-master/include/common/asm-generic/bitops.h
|
/*
* Generic bits operations.
*
* Architectures that don't want their own implementation of those,
* should include this file into the arch/$ARCH/include/asm/bitops.h
*/
#ifndef __CR_GENERIC_BITOPS_H__
#define __CR_GENERIC_BITOPS_H__
#include "common/asm/bitsperlong.h"
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_LONG)
#define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)]
#define BITMAP_SIZE(name) (sizeof(name) * CHAR_BIT)
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
/* Technically wrong, but this avoids compilation errors on some gcc
versions. */
#define BITOP_ADDR(x) "=m"(*(volatile long *)(x))
#else
#define BITOP_ADDR(x) "+m"(*(volatile long *)(x))
#endif
#define ADDR BITOP_ADDR(addr)
static inline void set_bit(int nr, volatile unsigned long *addr)
{
addr += nr / BITS_PER_LONG;
*addr |= (1UL << (nr % BITS_PER_LONG));
}
static inline void change_bit(int nr, volatile unsigned long *addr)
{
addr += nr / BITS_PER_LONG;
*addr ^= (1UL << (nr % BITS_PER_LONG));
}
static inline int test_bit(int nr, volatile const unsigned long *addr)
{
addr += nr / BITS_PER_LONG;
return (*addr & (1UL << (nr % BITS_PER_LONG))) ? -1 : 0;
}
static inline void clear_bit(int nr, volatile unsigned long *addr)
{
addr += nr / BITS_PER_LONG;
*addr &= ~(1UL << (nr % BITS_PER_LONG));
}
/**
* __ffs - find first set bit in word
* @word: The word to search
*
* Undefined if no bit exists, so code should check against 0 first.
*/
static inline unsigned long __ffs(unsigned long word)
{
return __builtin_ffsl(word) - 1;
}
#define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
/*
* Find the next set bit in a memory region.
*/
static inline unsigned long find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BITOP_WORD(offset);
unsigned long result = offset & ~(BITS_PER_LONG - 1);
unsigned long tmp;
if (offset >= size)
return size;
size -= result;
offset %= BITS_PER_LONG;
if (offset) {
tmp = *(p++);
tmp &= (~0UL << offset);
if (size < BITS_PER_LONG)
goto found_first;
if (tmp)
goto found_middle;
size -= BITS_PER_LONG;
result += BITS_PER_LONG;
}
while (size & ~(BITS_PER_LONG - 1)) {
if ((tmp = *(p++)))
goto found_middle;
result += BITS_PER_LONG;
size -= BITS_PER_LONG;
}
if (!size)
return result;
tmp = *p;
found_first:
tmp &= (~0UL >> (BITS_PER_LONG - size));
if (tmp == 0UL) /* Are any bits set? */
return result + size; /* Nope. */
found_middle:
return result + __ffs(tmp);
}
#define for_each_bit(i, bitmask) \
for (i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), 0); i < BITMAP_SIZE(bitmask); \
i = find_next_bit(bitmask, BITMAP_SIZE(bitmask), i + 1))
#endif /* __CR_GENERIC_BITOPS_H__ */
| 2,896 | 24.866071 | 110 |
h
|
criu
|
criu-master/lib/c/criu.h
|
/*
* (C) Copyright 2013 Parallels, Inc. (www.parallels.com).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, you can find it here:
* www.gnu.org/licenses/lgpl.html
*/
#ifndef __CRIU_LIB_H__
#define __CRIU_LIB_H__
#include <stdbool.h>
#include "version.h"
#include "rpc.pb-c.h"
#ifdef __GNUG__
extern "C" {
#endif
#define CRIU_LOG_UNSET (-1)
#define CRIU_LOG_MSG (0) /* Print message regardless of log level */
#define CRIU_LOG_ERROR (1) /* Errors only */
#define CRIU_LOG_WARN (2) /* Warnings */
#define CRIU_LOG_INFO (3) /* Informative */
#define CRIU_LOG_DEBUG (4) /* Debug only */
enum criu_service_comm { CRIU_COMM_SK, CRIU_COMM_FD, CRIU_COMM_BIN };
enum criu_cg_mode {
CRIU_CG_MODE_IGNORE,
CRIU_CG_MODE_NONE,
CRIU_CG_MODE_PROPS,
CRIU_CG_MODE_SOFT,
CRIU_CG_MODE_FULL,
CRIU_CG_MODE_STRICT,
CRIU_CG_MODE_DEFAULT,
};
enum criu_network_lock_method {
CRIU_NETWORK_LOCK_IPTABLES = 1,
CRIU_NETWORK_LOCK_NFTABLES = 2,
};
enum criu_pre_dump_mode { CRIU_PRE_DUMP_SPLICE = 1, CRIU_PRE_DUMP_READ = 2 };
int criu_set_service_address(const char *path);
void criu_set_service_fd(int fd);
int criu_set_service_binary(const char *path);
/*
* Set opts to defaults. _Must_ be called first before using any functions from
* the list down below. 0 on success, -1 on fail.
*/
int criu_init_opts(void);
void criu_free_opts(void);
void criu_set_pid(int pid);
void criu_set_images_dir_fd(int fd); /* must be set for dump/restore */
int criu_set_parent_images(const char *path);
void criu_set_work_dir_fd(int fd);
void criu_set_leave_running(bool leave_running);
void criu_set_ext_unix_sk(bool ext_unix_sk);
int criu_add_unix_sk(unsigned int inode);
void criu_set_tcp_established(bool tcp_established);
void criu_set_tcp_skip_in_flight(bool tcp_skip_in_flight);
void criu_set_tcp_close(bool tcp_close);
void criu_set_weak_sysctls(bool val);
void criu_set_evasive_devices(bool evasive_devices);
void criu_set_shell_job(bool shell_job);
void criu_set_skip_file_rwx_check(bool skip_file_rwx_check);
void criu_set_unprivileged(bool unprivileged);
void criu_set_orphan_pts_master(bool orphan_pts_master);
void criu_set_file_locks(bool file_locks);
void criu_set_track_mem(bool track_mem);
void criu_set_auto_dedup(bool auto_dedup);
void criu_set_force_irmap(bool force_irmap);
void criu_set_link_remap(bool link_remap);
void criu_set_log_level(int log_level);
int criu_set_log_file(const char *log_file);
void criu_set_cpu_cap(unsigned int cap);
int criu_set_root(const char *root);
void criu_set_manage_cgroups(bool manage);
void criu_set_manage_cgroups_mode(enum criu_cg_mode mode);
int criu_set_freeze_cgroup(const char *name);
int criu_set_lsm_profile(const char *name);
int criu_set_lsm_mount_context(const char *name);
void criu_set_timeout(unsigned int timeout);
void criu_set_auto_ext_mnt(bool val);
void criu_set_ext_sharing(bool val);
void criu_set_ext_masters(bool val);
int criu_set_exec_cmd(int argc, char *argv[]);
int criu_add_ext_mount(const char *key, const char *val);
int criu_add_veth_pair(const char *in, const char *out);
int criu_add_cg_root(const char *ctrl, const char *path);
int criu_add_enable_fs(const char *fs);
int criu_add_skip_mnt(const char *mnt);
void criu_set_ghost_limit(unsigned int limit);
int criu_add_irmap_path(const char *path);
int criu_add_inherit_fd(int fd, const char *key);
int criu_add_external(const char *key);
int criu_set_page_server_address_port(const char *address, int port);
int criu_set_pre_dump_mode(enum criu_pre_dump_mode mode);
void criu_set_pidfd_store_sk(int sk);
int criu_set_network_lock(enum criu_network_lock_method method);
int criu_join_ns_add(const char *ns, const char *ns_file, const char *extra_opt);
void criu_set_mntns_compat_mode(bool val);
/*
* The criu_notify_arg_t na argument is an opaque
* value that callbacks (cb-s) should pass into
* criu_notify_xxx() calls to fetch arbitrary values
* from notification. If the value is not available
* some non-existing one is reported.
*/
typedef CriuNotify *criu_notify_arg_t;
void criu_set_notify_cb(int (*cb)(char *action, criu_notify_arg_t na));
/* Get pid of root task. 0 if not available */
int criu_notify_pid(criu_notify_arg_t na);
/*
* If CRIU sends and FD in the case of 'orphan-pts-master',
* this FD can be retrieved with criu_get_orphan_pts_master_fd().
*
* If no FD has been received this will return -1.
*
* To make sure the FD returned is valid this function has to be
* called after the callback with the 'action' 'orphan-pts-master'.
*/
int criu_get_orphan_pts_master_fd(void);
/* Here is a table of return values and errno's of functions
* from the list down below.
*
* Return value errno Description
* ----------------------------------------------------------------------------
* 0 undefined Success.
*
* >0 undefined Success(criu_restore() only).
*
* -BADE rpc err (0 for now) RPC has returned fail.
*
* -ECONNREFUSED errno Unable to connect to CRIU.
*
* -ECOMM errno Unable to send/recv msg to/from CRIU.
*
* -EINVAL undefined CRIU doesn't support this type of request.
* You should probably update CRIU.
*
* -EBADMSG undefined Unexpected response from CRIU.
* You should probably update CRIU.
*/
int criu_check(void);
int criu_dump(void);
int criu_pre_dump(void);
int criu_restore(void);
int criu_restore_child(void);
/*
* Perform dumping but with preliminary iterations. Each
* time an iteration ends the ->more callback is called.
* The callback's return value is
* - positive -- one more iteration starts
* - zero -- final dump is performed and call exits
* - negative -- dump is aborted, the value is returned
* back from criu_dump_iters
*
* The @pi argument is an opaque value that caller may
* use to request pre-dump statistics (not yet implemented).
*/
typedef void *criu_predump_info;
int criu_dump_iters(int (*more)(criu_predump_info pi));
/*
* Get the version of the actual binary used for RPC.
*
* As this library is just forwarding all tasks to an
* independent (of this library) CRIU binary, the actual
* version of the CRIU binary can be different then the
* hardcoded values in the library (version.h).
* To be able to easily check the version of the CRIU binary
* the function criu_get_version() returns the version
* in the following format:
*
* (major * 10000) + (minor * 100) + sublevel
*
* If the CRIU binary has been built from a git checkout
* minor will increased by one.
*/
int criu_get_version(void);
/*
* Check if the version of the CRIU binary is at least
* 'minimum'. Version has to be in the same format as
* described for criu_get_version().
*
* Returns 1 if CRIU is at least 'minimum'.
* Returns 0 if CRIU is too old.
* Returns < 0 if there was an error.
*/
int criu_check_version(int minimum);
/*
* Same as the list above, but lets you have your very own options
* structure and lets you set individual options in it.
*/
typedef struct criu_opts criu_opts;
int criu_local_init_opts(criu_opts **opts);
void criu_local_free_opts(criu_opts *opts);
int criu_local_set_service_address(criu_opts *opts, const char *path);
void criu_local_set_service_fd(criu_opts *opts, int fd);
void criu_local_set_service_fd(criu_opts *opts, int fd);
void criu_local_set_pid(criu_opts *opts, int pid);
void criu_local_set_images_dir_fd(criu_opts *opts, int fd); /* must be set for dump/restore */
int criu_local_set_parent_images(criu_opts *opts, const char *path);
int criu_local_set_service_binary(criu_opts *opts, const char *path);
void criu_local_set_work_dir_fd(criu_opts *opts, int fd);
void criu_local_set_leave_running(criu_opts *opts, bool leave_running);
void criu_local_set_ext_unix_sk(criu_opts *opts, bool ext_unix_sk);
int criu_local_add_unix_sk(criu_opts *opts, unsigned int inode);
void criu_local_set_tcp_established(criu_opts *opts, bool tcp_established);
void criu_local_set_tcp_skip_in_flight(criu_opts *opts, bool tcp_skip_in_flight);
void criu_local_set_tcp_close(criu_opts *opts, bool tcp_close);
void criu_local_set_weak_sysctls(criu_opts *opts, bool val);
void criu_local_set_evasive_devices(criu_opts *opts, bool evasive_devices);
void criu_local_set_shell_job(criu_opts *opts, bool shell_job);
void criu_local_set_skip_file_rwx_check(criu_opts *opts, bool skip_file_rwx_check);
void criu_local_set_orphan_pts_master(criu_opts *opts, bool orphan_pts_master);
void criu_local_set_file_locks(criu_opts *opts, bool file_locks);
void criu_local_set_track_mem(criu_opts *opts, bool track_mem);
void criu_local_set_auto_dedup(criu_opts *opts, bool auto_dedup);
void criu_local_set_force_irmap(criu_opts *opts, bool force_irmap);
void criu_local_set_link_remap(criu_opts *opts, bool link_remap);
void criu_local_set_log_level(criu_opts *opts, int log_level);
int criu_local_set_log_file(criu_opts *opts, const char *log_file);
void criu_local_set_cpu_cap(criu_opts *opts, unsigned int cap);
int criu_local_set_root(criu_opts *opts, const char *root);
void criu_local_set_manage_cgroups(criu_opts *opts, bool manage);
void criu_local_set_manage_cgroups_mode(criu_opts *opts, enum criu_cg_mode mode);
int criu_local_set_freeze_cgroup(criu_opts *opts, const char *name);
int criu_local_set_lsm_profile(criu_opts *opts, const char *name);
int criu_local_set_lsm_mount_context(criu_opts *opts, const char *name);
void criu_local_set_timeout(criu_opts *opts, unsigned int timeout);
void criu_local_set_auto_ext_mnt(criu_opts *opts, bool val);
void criu_local_set_ext_sharing(criu_opts *opts, bool val);
void criu_local_set_ext_masters(criu_opts *opts, bool val);
int criu_local_set_exec_cmd(criu_opts *opts, int argc, char *argv[]);
int criu_local_add_ext_mount(criu_opts *opts, const char *key, const char *val);
int criu_local_add_veth_pair(criu_opts *opts, const char *in, const char *out);
int criu_local_add_cg_root(criu_opts *opts, const char *ctrl, const char *path);
int criu_local_add_enable_fs(criu_opts *opts, const char *fs);
int criu_local_add_skip_mnt(criu_opts *opts, const char *mnt);
void criu_local_set_ghost_limit(criu_opts *opts, unsigned int limit);
int criu_local_add_irmap_path(criu_opts *opts, const char *path);
int criu_local_add_cg_props(criu_opts *opts, const char *stream);
int criu_local_add_cg_props_file(criu_opts *opts, const char *path);
int criu_local_add_cg_dump_controller(criu_opts *opts, const char *name);
int criu_local_add_cg_yard(criu_opts *opts, const char *path);
int criu_local_add_inherit_fd(criu_opts *opts, int fd, const char *key);
int criu_local_add_external(criu_opts *opts, const char *key);
int criu_local_set_page_server_address_port(criu_opts *opts, const char *address, int port);
int criu_local_set_pre_dump_mode(criu_opts *opts, enum criu_pre_dump_mode mode);
void criu_local_set_pidfd_store_sk(criu_opts *opts, int sk);
int criu_local_set_network_lock(criu_opts *opts, enum criu_network_lock_method method);
int criu_local_join_ns_add(criu_opts *opts, const char *ns, const char *ns_file, const char *extra_opt);
void criu_local_set_mntns_compat_mode(criu_opts *opts, bool val);
void criu_local_set_notify_cb(criu_opts *opts, int (*cb)(char *action, criu_notify_arg_t na));
int criu_local_check(criu_opts *opts);
int criu_local_dump(criu_opts *opts);
int criu_local_pre_dump(criu_opts *opts);
int criu_local_restore(criu_opts *opts);
int criu_local_restore_child(criu_opts *opts);
int criu_local_dump_iters(criu_opts *opts, int (*more)(criu_predump_info pi));
int criu_local_get_version(criu_opts *opts);
int criu_local_check_version(criu_opts *opts, int minimum);
/*
* Feature checking allows the user to check if CRIU supports
* certain features. There are CRIU features which do not depend
* on the version of CRIU but on kernel features or architecture.
*
* One example is memory tracking. Memory tracking can be disabled
* in the kernel or there are architectures which do not support
* it (aarch64 for example). By using the feature check a libcriu
* user can easily query CRIU if a certain feature is available.
*
* The features which should be checked can be marked in the
* structure 'struct criu_feature_check'. Each structure member
* that is set to true will result in CRIU checking for the
* availability of that feature in the current combination of
* CRIU/kernel/architecture.
*
* Available features will be set to true when the function
* returns successfully. Missing features will be set to false.
*/
struct criu_feature_check {
bool mem_track;
bool lazy_pages;
bool pidfd_store;
};
int criu_feature_check(struct criu_feature_check *features, size_t size);
int criu_local_feature_check(criu_opts *opts, struct criu_feature_check *features, size_t size);
#ifdef __GNUG__
}
#endif
#endif /* __CRIU_LIB_H__ */
| 13,493 | 39.890909 | 104 |
h
|
criu
|
criu-master/plugins/amdgpu/amdgpu_plugin_topology.h
|
#ifndef __KFD_PLUGIN_TOPOLOGY_H__
#define __KFD_PLUGIN_TOPOLOGY_H__
#define DRM_FIRST_RENDER_NODE 128
#define DRM_LAST_RENDER_NODE 255
#define TOPO_HEAP_TYPE_PUBLIC 1 /* HSA_HEAPTYPE_FRAME_BUFFER_PUBLIC */
#define TOPO_HEAP_TYPE_PRIVATE 2 /* HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE */
#define TOPO_IOLINK_TYPE_ANY 0 /* HSA_IOLINKTYPE_UNDEFINED */
#define TOPO_IOLINK_TYPE_PCIE 2 /* HSA_IOLINKTYPE_PCIEXPRESS */
#define TOPO_IOLINK_TYPE_XGMI 11 /* HSA_IOLINK_TYPE_XGMI */
#define NODE_IS_GPU(node) ((node)->gpu_id != 0)
#define INVALID_CPU_ID 0xFFFF
/*************************************** Structures ***********************************************/
struct tp_node;
struct tp_iolink {
struct list_head listm;
uint32_t type;
uint32_t node_to_id;
struct tp_node *node_to;
struct tp_node *node_from;
bool valid; /* Set to false if target node is not accessible */
struct tp_iolink *peer; /* If link is bi-directional, peer link */
};
struct tp_node {
uint32_t id;
uint32_t gpu_id;
uint32_t cpu_cores_count;
uint32_t simd_count;
uint32_t mem_banks_count;
uint32_t caches_count;
uint32_t io_links_count;
uint32_t max_waves_per_simd;
uint32_t lds_size_in_kb;
uint32_t num_gws;
uint32_t wave_front_size;
uint32_t array_count;
uint32_t simd_arrays_per_engine;
uint32_t cu_per_simd_array;
uint32_t simd_per_cu;
uint32_t max_slots_scratch_cu;
uint32_t vendor_id;
uint32_t device_id;
uint32_t domain;
uint32_t drm_render_minor;
uint64_t hive_id;
uint32_t num_sdma_engines;
uint32_t num_sdma_xgmi_engines;
uint32_t num_sdma_queues_per_engine;
uint32_t num_cp_queues;
uint32_t fw_version;
uint32_t capability;
uint32_t sdma_fw_version;
bool vram_public;
uint64_t vram_size;
struct list_head listm_system;
struct list_head listm_p2pgroup;
struct list_head listm_mapping; /* Used only during device mapping */
uint32_t num_valid_iolinks;
struct list_head iolinks;
int drm_fd;
};
struct tp_p2pgroup {
uint32_t type;
uint32_t num_nodes;
struct list_head listm_system;
struct list_head nodes;
};
struct tp_system {
bool parsed;
uint32_t num_nodes;
struct list_head nodes;
uint32_t num_xgmi_groups;
struct list_head xgmi_groups;
};
struct id_map {
uint32_t src;
uint32_t dest;
struct list_head listm;
};
struct device_maps {
struct list_head cpu_maps; /* CPUs are mapped using node_id */
struct list_head gpu_maps;
struct list_head *tail_cpu; /* GPUs are mapped using gpu_id */
struct list_head *tail_gpu;
};
/**************************************** Functions ***********************************************/
void topology_init(struct tp_system *sys);
void topology_free(struct tp_system *topology);
int topology_parse(struct tp_system *topology, const char *msg);
int topology_determine_iolinks(struct tp_system *sys);
void topology_print(const struct tp_system *sys, const char *msg);
struct id_map *maps_add_gpu_entry(struct device_maps *maps, const uint32_t src_id, const uint32_t dest_id);
struct tp_node *sys_add_node(struct tp_system *sys, uint32_t id, uint32_t gpu_id);
struct tp_iolink *node_add_iolink(struct tp_node *node, uint32_t type, uint32_t node_to_id);
struct tp_node *sys_get_node_by_gpu_id(const struct tp_system *sys, const uint32_t gpu_id);
struct tp_node *sys_get_node_by_render_minor(const struct tp_system *sys, const int drm_render_minor);
struct tp_node *sys_get_node_by_index(const struct tp_system *sys, uint32_t index);
int node_get_drm_render_device(struct tp_node *node);
void sys_close_drm_render_devices(struct tp_system *sys);
int set_restore_gpu_maps(struct tp_system *tp_checkpoint, struct tp_system *tp_local, struct device_maps *maps);
uint32_t maps_get_dest_gpu(const struct device_maps *maps, const uint32_t src_id);
void maps_init(struct device_maps *maps);
void maps_free(struct device_maps *maps);
#endif /* __KFD_PLUGIN_TOPOLOGY_H__ */
| 3,850 | 28.623077 | 112 |
h
|
criu
|
criu-master/soccr/soccr.c
|
#include <errno.h>
#include <libnet.h>
#include <linux/sockios.h>
#include <linux/types.h>
#include <netinet/tcp.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include "soccr.h"
#ifndef SIOCOUTQNSD
/* MAO - Define SIOCOUTQNSD ioctl if we don't have it */
#define SIOCOUTQNSD 0x894B
#endif
enum {
TCPF_ESTABLISHED = (1 << 1),
TCPF_SYN_SENT = (1 << 2),
TCPF_SYN_RECV = (1 << 3),
TCPF_FIN_WAIT1 = (1 << 4),
TCPF_FIN_WAIT2 = (1 << 5),
TCPF_TIME_WAIT = (1 << 6),
TCPF_CLOSE = (1 << 7),
TCPF_CLOSE_WAIT = (1 << 8),
TCPF_LAST_ACK = (1 << 9),
TCPF_LISTEN = (1 << 10),
TCPF_CLOSING = (1 << 11),
};
/*
* The TCP transition diagram for half closed connections
*
* ------------
* FIN_WAIT1 \ FIN
* ---------
* / ACK CLOSE_WAIT
* -----------
* FIN_WAIT2
* ----------
* / FIN LAST_ACK
* -----------
* TIME_WAIT \ ACK
* ----------
* CLOSED
*
* How to get the TCP_CLOSING state
*
* ----------- ----------
* FIN_WAIT1 \/ FIN FIN_WAIT1
* ----------- ----------
* CLOSING CLOSING
* \/ ACK
* ----------- ----------
* TIME_WAIT TIME_WAIT
*/
/* Restore a fin packet in a send queue first */
#define SNDQ_FIRST_FIN (TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2 | TCPF_CLOSING)
/* Restore fin in a send queue after restoring fi in the receive queue. */
#define SNDQ_SECOND_FIN (TCPF_LAST_ACK | TCPF_CLOSE)
#define SNDQ_FIN_ACKED (TCPF_FIN_WAIT2 | TCPF_CLOSE)
#define RCVQ_FIRST_FIN (TCPF_CLOSE_WAIT | TCPF_LAST_ACK | TCPF_CLOSE)
#define RCVQ_SECOND_FIN (TCPF_CLOSING)
#define RCVQ_FIN_ACKED (TCPF_CLOSE)
static void (*log)(unsigned int loglevel, const char *format, ...) __attribute__((__format__(__printf__, 2, 3)));
static unsigned int log_level = 0;
void libsoccr_set_log(unsigned int level, void (*fn)(unsigned int level, const char *fmt, ...))
{
log_level = level;
log = fn;
}
#define loge(msg, ...) \
do { \
if (log && (log_level >= SOCCR_LOG_ERR)) \
log(SOCCR_LOG_ERR, "Error (%s:%d): " msg, __FILE__, __LINE__, ##__VA_ARGS__); \
} while (0)
#define logerr(msg, ...) loge(msg ": %s\n", ##__VA_ARGS__, strerror(errno))
#define logd(msg, ...) \
do { \
if (log && (log_level >= SOCCR_LOG_DBG)) \
log(SOCCR_LOG_DBG, "Debug: " msg, ##__VA_ARGS__); \
} while (0)
static int tcp_repair_on(int fd)
{
int ret, aux = 1;
ret = setsockopt(fd, SOL_TCP, TCP_REPAIR, &aux, sizeof(aux));
if (ret < 0)
logerr("Can't turn TCP repair mode ON");
return ret;
}
static int tcp_repair_off(int fd)
{
int aux = 0, ret;
ret = setsockopt(fd, SOL_TCP, TCP_REPAIR, &aux, sizeof(aux));
if (ret < 0)
logerr("Failed to turn off repair mode on socket");
return ret;
}
struct libsoccr_sk {
int fd;
unsigned flags;
char *recv_queue;
char *send_queue;
union libsoccr_addr *src_addr;
union libsoccr_addr *dst_addr;
};
#define SK_FLAG_FREE_RQ 0x1
#define SK_FLAG_FREE_SQ 0x2
#define SK_FLAG_FREE_SA 0x4
#define SK_FLAG_FREE_DA 0x8
struct libsoccr_sk *libsoccr_pause(int fd)
{
struct libsoccr_sk *ret;
ret = malloc(sizeof(*ret));
if (!ret) {
loge("Unable to allocate memory\n");
return NULL;
}
if (tcp_repair_on(fd) < 0) {
free(ret);
return NULL;
}
ret->flags = 0;
ret->recv_queue = NULL;
ret->send_queue = NULL;
ret->src_addr = NULL;
ret->dst_addr = NULL;
ret->fd = fd;
return ret;
}
void libsoccr_resume(struct libsoccr_sk *sk)
{
tcp_repair_off(sk->fd);
libsoccr_release(sk);
}
void libsoccr_release(struct libsoccr_sk *sk)
{
if (sk->flags & SK_FLAG_FREE_RQ)
free(sk->recv_queue);
if (sk->flags & SK_FLAG_FREE_SQ)
free(sk->send_queue);
if (sk->flags & SK_FLAG_FREE_SA)
free(sk->src_addr);
if (sk->flags & SK_FLAG_FREE_DA)
free(sk->dst_addr);
free(sk);
}
struct soccr_tcp_info {
__u8 tcpi_state;
__u8 tcpi_ca_state;
__u8 tcpi_retransmits;
__u8 tcpi_probes;
__u8 tcpi_backoff;
__u8 tcpi_options;
__u8 tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4;
};
static int refresh_sk(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, struct soccr_tcp_info *ti)
{
int size;
socklen_t olen = sizeof(*ti);
if (getsockopt(sk->fd, SOL_TCP, TCP_INFO, ti, &olen) || olen != sizeof(*ti)) {
logerr("Failed to obtain TCP_INFO");
return -1;
}
switch (ti->tcpi_state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_LAST_ACK:
case TCP_CLOSE_WAIT:
case TCP_CLOSING:
case TCP_CLOSE:
case TCP_SYN_SENT:
break;
default:
loge("Unknown state %d\n", ti->tcpi_state);
return -1;
}
data->state = ti->tcpi_state;
if (ioctl(sk->fd, SIOCOUTQ, &size) == -1) {
logerr("Unable to get size of snd queue");
return -1;
}
data->outq_len = size;
if (ioctl(sk->fd, SIOCOUTQNSD, &size) == -1) {
logerr("Unable to get size of unsent data");
return -1;
}
data->unsq_len = size;
if (data->state == TCP_CLOSE) {
/* A connection could be reset. In this case a sent queue
* may contain some data. A user can't read this data, so let's
* ignore them. Otherwise we will need to add a logic whether
* the send queue contains a fin packet or not and decide whether
* a fin or reset packet has to be sent to restore a state
*/
data->unsq_len = 0;
data->outq_len = 0;
}
/* Don't account the fin packet. It doesn't contain real data. */
if ((1 << data->state) & (SNDQ_FIRST_FIN | SNDQ_SECOND_FIN)) {
if (data->outq_len)
data->outq_len--;
data->unsq_len = data->unsq_len ? data->unsq_len - 1 : 0;
}
if (ioctl(sk->fd, SIOCINQ, &size) == -1) {
logerr("Unable to get size of recv queue");
return -1;
}
data->inq_len = size;
return 0;
}
static int get_stream_options(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, struct soccr_tcp_info *ti)
{
int ret;
socklen_t auxl;
int val;
auxl = sizeof(data->mss_clamp);
ret = getsockopt(sk->fd, SOL_TCP, TCP_MAXSEG, &data->mss_clamp, &auxl);
if (ret < 0)
goto err_sopt;
data->opt_mask = ti->tcpi_options;
if (ti->tcpi_options & TCPI_OPT_WSCALE) {
data->snd_wscale = ti->tcpi_snd_wscale;
data->rcv_wscale = ti->tcpi_rcv_wscale;
}
if (ti->tcpi_options & TCPI_OPT_TIMESTAMPS) {
auxl = sizeof(val);
ret = getsockopt(sk->fd, SOL_TCP, TCP_TIMESTAMP, &val, &auxl);
if (ret < 0)
goto err_sopt;
data->timestamp = val;
}
return 0;
err_sopt:
logerr("\tsockopt failed");
return -1;
}
static int get_window(struct libsoccr_sk *sk, struct libsoccr_sk_data *data)
{
struct tcp_repair_window opt;
socklen_t optlen = sizeof(opt);
if (getsockopt(sk->fd, SOL_TCP, TCP_REPAIR_WINDOW, &opt, &optlen)) {
/* Appeared since 4.8, but TCP_repair itself is since 3.11 */
if (errno == ENOPROTOOPT)
return 0;
logerr("Unable to get window properties");
return -1;
}
data->flags |= SOCCR_FLAGS_WINDOW;
data->snd_wl1 = opt.snd_wl1;
data->snd_wnd = opt.snd_wnd;
data->max_window = opt.max_window;
data->rcv_wnd = opt.rcv_wnd;
data->rcv_wup = opt.rcv_wup;
return 0;
}
/*
* TCP queues sequences and their relations to the code below
*
* output queue
* net <----------------------------- sk
* ^ ^ ^ seq >>
* snd_una snd_nxt write_seq
*
* input queue
* net -----------------------------> sk
* << seq ^ ^
* rcv_nxt copied_seq
*
*
* inq_len = rcv_nxt - copied_seq = SIOCINQ
* outq_len = write_seq - snd_una = SIOCOUTQ
* inq_seq = rcv_nxt
* outq_seq = write_seq
*
* On restore kernel moves the option we configure with setsockopt,
* thus we should advance them on the _len value in restore_tcp_seqs.
*
*/
static int get_queue(int sk, int queue_id, __u32 *seq, __u32 len, char **bufp)
{
int ret, aux;
socklen_t auxl;
char *buf;
aux = queue_id;
auxl = sizeof(aux);
ret = setsockopt(sk, SOL_TCP, TCP_REPAIR_QUEUE, &aux, auxl);
if (ret < 0)
goto err_sopt;
auxl = sizeof(*seq);
ret = getsockopt(sk, SOL_TCP, TCP_QUEUE_SEQ, seq, &auxl);
if (ret < 0)
goto err_sopt;
if (len) {
/*
* Try to grab one byte more from the queue to
* make sure there are len bytes for real
*/
buf = malloc(len + 1);
if (!buf) {
loge("Unable to allocate memory\n");
goto err_buf;
}
ret = recv(sk, buf, len + 1, MSG_PEEK | MSG_DONTWAIT);
if (ret != len)
goto err_recv;
} else
buf = NULL;
*bufp = buf;
return 0;
err_sopt:
logerr("\tsockopt failed");
err_buf:
return -1;
err_recv:
logerr("\trecv failed (%d, want %d)", ret, len);
free(buf);
goto err_buf;
}
/*
* This is how much data we've had in the initial libsoccr
*/
#define SOCR_DATA_MIN_SIZE (17 * sizeof(__u32))
int libsoccr_save(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size)
{
struct soccr_tcp_info ti;
if (!data || data_size < SOCR_DATA_MIN_SIZE) {
loge("Invalid input parameters\n");
return -1;
}
memset(data, 0, data_size);
if (refresh_sk(sk, data, &ti))
return -2;
if (get_stream_options(sk, data, &ti))
return -3;
if (get_window(sk, data))
return -4;
sk->flags |= SK_FLAG_FREE_SQ | SK_FLAG_FREE_RQ;
if (get_queue(sk->fd, TCP_RECV_QUEUE, &data->inq_seq, data->inq_len, &sk->recv_queue))
return -5;
if (get_queue(sk->fd, TCP_SEND_QUEUE, &data->outq_seq, data->outq_len, &sk->send_queue))
return -6;
return sizeof(struct libsoccr_sk_data);
}
#define GET_Q_FLAGS (SOCCR_MEM_EXCL)
char *libsoccr_get_queue_bytes(struct libsoccr_sk *sk, int queue_id, unsigned flags)
{
char **p, *ret;
if (flags & ~GET_Q_FLAGS)
return NULL;
switch (queue_id) {
case TCP_RECV_QUEUE:
p = &sk->recv_queue;
break;
case TCP_SEND_QUEUE:
p = &sk->send_queue;
break;
default:
return NULL;
}
ret = *p;
if (flags & SOCCR_MEM_EXCL)
*p = NULL;
return ret;
}
#define GET_SA_FLAGS (SOCCR_MEM_EXCL)
union libsoccr_addr *libsoccr_get_addr(struct libsoccr_sk *sk, int self, unsigned flags)
{
if (flags & ~GET_SA_FLAGS)
return NULL;
/* FIXME -- implemented in CRIU, makes sense to have it here too */
return NULL;
}
static int set_queue_seq(struct libsoccr_sk *sk, int queue, __u32 seq)
{
logd("\tSetting %d queue seq to %u\n", queue, seq);
if (setsockopt(sk->fd, SOL_TCP, TCP_REPAIR_QUEUE, &queue, sizeof(queue)) < 0) {
logerr("Can't set repair queue");
return -1;
}
if (setsockopt(sk->fd, SOL_TCP, TCP_QUEUE_SEQ, &seq, sizeof(seq)) < 0) {
logerr("Can't set queue seq");
return -1;
}
return 0;
}
#ifndef TCPOPT_SACK_PERM
#define TCPOPT_SACK_PERM TCPOPT_SACK_PERMITTED
#endif
static int libsoccr_set_sk_data_noq(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size)
{
struct tcp_repair_opt opts[4];
int addr_size, mstate;
int onr = 0;
__u32 seq;
if (!data || data_size < SOCR_DATA_MIN_SIZE) {
loge("Invalid input parameters\n");
return -1;
}
if (!sk->dst_addr || !sk->src_addr) {
loge("Destination or/and source addresses aren't set\n");
return -1;
}
mstate = 1 << data->state;
if (data->state == TCP_LISTEN) {
loge("Unable to handle listen sockets\n");
return -1;
}
if (sk->src_addr->sa.sa_family == AF_INET)
addr_size = sizeof(sk->src_addr->v4);
else
addr_size = sizeof(sk->src_addr->v6);
if (bind(sk->fd, &sk->src_addr->sa, addr_size)) {
logerr("Can't bind inet socket back");
return -1;
}
if (mstate & (RCVQ_FIRST_FIN | RCVQ_SECOND_FIN))
data->inq_seq--;
/* outq_seq is adjusted due to not accounting the fin packet */
if (mstate & (SNDQ_FIRST_FIN | SNDQ_SECOND_FIN))
data->outq_seq--;
if (set_queue_seq(sk, TCP_RECV_QUEUE, data->inq_seq - data->inq_len))
return -2;
seq = data->outq_seq - data->outq_len;
if (data->state == TCP_SYN_SENT)
seq--;
if (set_queue_seq(sk, TCP_SEND_QUEUE, seq))
return -3;
if (sk->dst_addr->sa.sa_family == AF_INET)
addr_size = sizeof(sk->dst_addr->v4);
else
addr_size = sizeof(sk->dst_addr->v6);
if (data->state == TCP_SYN_SENT && tcp_repair_off(sk->fd))
return -1;
if (connect(sk->fd, &sk->dst_addr->sa, addr_size) == -1 && errno != EINPROGRESS) {
logerr("Can't connect inet socket back");
return -1;
}
if (data->state == TCP_SYN_SENT && tcp_repair_on(sk->fd))
return -1;
logd("\tRestoring TCP options\n");
if (data->opt_mask & TCPI_OPT_SACK) {
logd("\t\tWill turn SAK on\n");
opts[onr].opt_code = TCPOPT_SACK_PERM;
opts[onr].opt_val = 0;
onr++;
}
if (data->opt_mask & TCPI_OPT_WSCALE) {
logd("\t\tWill set snd_wscale to %u\n", data->snd_wscale);
logd("\t\tWill set rcv_wscale to %u\n", data->rcv_wscale);
opts[onr].opt_code = TCPOPT_WINDOW;
opts[onr].opt_val = data->snd_wscale + (data->rcv_wscale << 16);
onr++;
}
if (data->opt_mask & TCPI_OPT_TIMESTAMPS) {
logd("\t\tWill turn timestamps on\n");
opts[onr].opt_code = TCPOPT_TIMESTAMP;
opts[onr].opt_val = 0;
onr++;
}
logd("Will set mss clamp to %u\n", data->mss_clamp);
opts[onr].opt_code = TCPOPT_MAXSEG;
opts[onr].opt_val = data->mss_clamp;
onr++;
if (data->state != TCP_SYN_SENT &&
setsockopt(sk->fd, SOL_TCP, TCP_REPAIR_OPTIONS, opts, onr * sizeof(struct tcp_repair_opt)) < 0) {
logerr("Can't repair options");
return -2;
}
if (data->opt_mask & TCPI_OPT_TIMESTAMPS) {
if (setsockopt(sk->fd, SOL_TCP, TCP_TIMESTAMP, &data->timestamp, sizeof(data->timestamp)) < 0) {
logerr("Can't set timestamp");
return -3;
}
}
return 0;
}
/* IPv4-Mapped IPv6 Addresses */
static int ipv6_addr_mapped(union libsoccr_addr *addr)
{
return (addr->v6.sin6_addr.s6_addr32[2] == htonl(0x0000ffff));
}
static int send_fin(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size, uint8_t flags)
{
uint32_t src_v4 = sk->src_addr->v4.sin_addr.s_addr;
uint32_t dst_v4 = sk->dst_addr->v4.sin_addr.s_addr;
int ret, exit_code = -1, family;
char errbuf[LIBNET_ERRBUF_SIZE];
int mark = SOCCR_MARK;
int libnet_type;
libnet_t *l;
family = sk->dst_addr->sa.sa_family;
if (family == AF_INET6 && ipv6_addr_mapped(sk->dst_addr)) {
/* TCP over IPv4 */
family = AF_INET;
dst_v4 = sk->dst_addr->v6.sin6_addr.s6_addr32[3];
src_v4 = sk->src_addr->v6.sin6_addr.s6_addr32[3];
}
if (family == AF_INET6)
libnet_type = LIBNET_RAW6;
else
libnet_type = LIBNET_RAW4;
l = libnet_init(libnet_type, /* injection type */
NULL, /* network interface */
errbuf); /* errbuf */
if (l == NULL) {
loge("libnet_init failed (%s)\n", errbuf);
return -1;
}
if (setsockopt(l->fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) {
logerr("Can't set SO_MARK (%d) for socket\n", mark);
goto err;
}
ret = libnet_build_tcp(ntohs(sk->dst_addr->v4.sin_port), /* source port */
ntohs(sk->src_addr->v4.sin_port), /* destination port */
data->inq_seq, /* sequence number */
data->outq_seq - data->outq_len, /* acknowledgement num */
flags, /* control flags */
data->rcv_wnd, /* window size */
0, /* checksum */
10, /* urgent pointer */
LIBNET_TCP_H + 20, /* TCP packet size */
NULL, /* payload */
0, /* payload size */
l, /* libnet handle */
0); /* libnet id */
if (ret == -1) {
loge("Can't build TCP header: %s\n", libnet_geterror(l));
goto err;
}
if (family == AF_INET6) {
struct libnet_in6_addr src, dst;
memcpy(&dst, &sk->dst_addr->v6.sin6_addr, sizeof(dst));
memcpy(&src, &sk->src_addr->v6.sin6_addr, sizeof(src));
ret = libnet_build_ipv6(0, 0, LIBNET_TCP_H, /* length */
IPPROTO_TCP, /* protocol */
64, /* hop limit */
dst, /* source IP */
src, /* destination IP */
NULL, /* payload */
0, /* payload size */
l, /* libnet handle */
0); /* libnet id */
} else if (family == AF_INET)
ret = libnet_build_ipv4(LIBNET_IPV4_H + LIBNET_TCP_H + 20, /* length */
0, /* TOS */
242, /* IP ID */
0, /* IP Frag */
64, /* TTL */
IPPROTO_TCP, /* protocol */
0, /* checksum */
dst_v4, /* source IP */
src_v4, /* destination IP */
NULL, /* payload */
0, /* payload size */
l, /* libnet handle */
0); /* libnet id */
else {
loge("Unknown socket family\n");
goto err;
}
if (ret == -1) {
loge("Can't build IP header: %s\n", libnet_geterror(l));
goto err;
}
ret = libnet_write(l);
if (ret == -1) {
loge("Unable to send a fin packet: %s\n", libnet_geterror(l));
goto err;
}
exit_code = 0;
err:
libnet_destroy(l);
return exit_code;
}
static int restore_fin_in_snd_queue(int sk, int acked)
{
int queue = TCP_SEND_QUEUE;
int ret;
/*
* If TCP_SEND_QUEUE is set, a fin packet will be
* restored as a sent packet.
*/
if (acked && setsockopt(sk, SOL_TCP, TCP_REPAIR_QUEUE, &queue, sizeof(queue)) < 0) {
logerr("Can't set repair queue");
return -1;
}
ret = shutdown(sk, SHUT_WR);
if (ret < 0)
logerr("Unable to shut down a socket");
queue = TCP_NO_QUEUE;
if (acked && setsockopt(sk, SOL_TCP, TCP_REPAIR_QUEUE, &queue, sizeof(queue)) < 0) {
logerr("Can't set repair queue");
return -1;
}
return ret;
}
static int libsoccr_restore_queue(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size, int queue,
char *buf);
int libsoccr_restore(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size)
{
int mstate = 1 << data->state;
if (libsoccr_set_sk_data_noq(sk, data, data_size))
return -1;
if (libsoccr_restore_queue(sk, data, sizeof(*data), TCP_RECV_QUEUE, sk->recv_queue))
return -1;
if (libsoccr_restore_queue(sk, data, sizeof(*data), TCP_SEND_QUEUE, sk->send_queue))
return -1;
if (data->flags & SOCCR_FLAGS_WINDOW) {
struct tcp_repair_window wopt = {
.snd_wl1 = data->snd_wl1,
.snd_wnd = data->snd_wnd,
.max_window = data->max_window,
.rcv_wnd = data->rcv_wnd,
.rcv_wup = data->rcv_wup,
};
if (mstate & (RCVQ_FIRST_FIN | RCVQ_SECOND_FIN)) {
wopt.rcv_wup--;
wopt.rcv_wnd++;
}
if (setsockopt(sk->fd, SOL_TCP, TCP_REPAIR_WINDOW, &wopt, sizeof(wopt))) {
logerr("Unable to set window parameters");
return -1;
}
}
/*
* To restore a half closed sockets, fin packets has to be restored in
* recv and send queues. Here shutdown() is used to restore a fin
* packet in the send queue and a fake fin packet is send to restore it
* in the recv queue.
*/
if (mstate & SNDQ_FIRST_FIN)
restore_fin_in_snd_queue(sk->fd, mstate & SNDQ_FIN_ACKED);
/* Send a fin packet to the socket to restore it in a receive queue. */
if (mstate & (RCVQ_FIRST_FIN | RCVQ_SECOND_FIN))
if (send_fin(sk, data, data_size, TH_ACK | TH_FIN) < 0)
return -1;
if (mstate & SNDQ_SECOND_FIN)
restore_fin_in_snd_queue(sk->fd, mstate & SNDQ_FIN_ACKED);
if (mstate & RCVQ_FIN_ACKED)
data->inq_seq++;
if (mstate & SNDQ_FIN_ACKED) {
data->outq_seq++;
if (send_fin(sk, data, data_size, TH_ACK) < 0)
return -1;
}
return 0;
}
static int __send_queue(struct libsoccr_sk *sk, int queue, char *buf, __u32 len)
{
int ret, err = -1, max_chunk;
int off;
max_chunk = len;
off = 0;
do {
int chunk = len;
if (chunk > max_chunk)
chunk = max_chunk;
ret = send(sk->fd, buf + off, chunk, 0);
if (ret <= 0) {
if (max_chunk > 1024) {
/*
* Kernel not only refuses the whole chunk,
* but refuses to split it into pieces too.
*
* When restoring recv queue in repair mode
* kernel doesn't try hard and just allocates
* a linear skb with the size we pass to the
* system call. Thus, if the size is too big
* for slab allocator, the send just fails
* with ENOMEM.
*
* In any case -- try smaller chunk, hopefully
* there's still enough memory in the system.
*/
max_chunk >>= 1;
continue;
}
logerr("Can't restore %d queue data (%d), want (%d:%d:%d)", queue, ret, chunk, len, max_chunk);
goto err;
}
off += ret;
len -= ret;
} while (len);
err = 0;
err:
return err;
}
static int send_queue(struct libsoccr_sk *sk, int queue, char *buf, __u32 len)
{
logd("\tRestoring TCP %d queue data %u bytes\n", queue, len);
if (setsockopt(sk->fd, SOL_TCP, TCP_REPAIR_QUEUE, &queue, sizeof(queue)) < 0) {
logerr("Can't set repair queue");
return -1;
}
return __send_queue(sk, queue, buf, len);
}
static int libsoccr_restore_queue(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size, int queue,
char *buf)
{
if (!buf)
return 0;
if (!data || data_size < SOCR_DATA_MIN_SIZE)
return -1;
if (queue == TCP_RECV_QUEUE) {
if (!data->inq_len)
return 0;
return send_queue(sk, TCP_RECV_QUEUE, buf, data->inq_len);
}
if (queue == TCP_SEND_QUEUE) {
__u32 len, ulen;
/*
* All data in a write buffer can be divided on two parts sent
* but not yet acknowledged data and unsent data.
* The TCP stack must know which data have been sent, because
* acknowledgment can be received for them. These data must be
* restored in repair mode.
*/
ulen = data->unsq_len;
len = data->outq_len - ulen;
if (len && send_queue(sk, TCP_SEND_QUEUE, buf, len))
return -2;
if (ulen) {
/*
* The second part of data have never been sent to outside, so
* they can be restored without any tricks.
*/
tcp_repair_off(sk->fd);
if (__send_queue(sk, TCP_SEND_QUEUE, buf + len, ulen))
return -3;
if (tcp_repair_on(sk->fd))
return -4;
}
return 0;
}
return -5;
}
#define SET_Q_FLAGS (SOCCR_MEM_EXCL)
int libsoccr_set_queue_bytes(struct libsoccr_sk *sk, int queue_id, char *bytes, unsigned flags)
{
if (flags & ~SET_Q_FLAGS)
return -1;
switch (queue_id) {
case TCP_RECV_QUEUE:
sk->recv_queue = bytes;
if (flags & SOCCR_MEM_EXCL)
sk->flags |= SK_FLAG_FREE_RQ;
return 0;
case TCP_SEND_QUEUE:
sk->send_queue = bytes;
if (flags & SOCCR_MEM_EXCL)
sk->flags |= SK_FLAG_FREE_SQ;
return 0;
}
return -1;
}
#define SET_SA_FLAGS (SOCCR_MEM_EXCL)
int libsoccr_set_addr(struct libsoccr_sk *sk, int self, union libsoccr_addr *addr, unsigned flags)
{
if (flags & ~SET_SA_FLAGS)
return -1;
if (self) {
sk->src_addr = addr;
if (flags & SOCCR_MEM_EXCL)
sk->flags |= SK_FLAG_FREE_SA;
} else {
sk->dst_addr = addr;
if (flags & SOCCR_MEM_EXCL)
sk->flags |= SK_FLAG_FREE_DA;
}
return 0;
}
| 22,423 | 23.085929 | 119 |
c
|
criu
|
criu-master/soccr/soccr.h
|
#ifndef __LIBSOCCR_H__
#define __LIBSOCCR_H__
#include <netinet/in.h> /* sockaddr_in, sockaddr_in6 */
#include <netinet/tcp.h> /* TCP_REPAIR_WINDOW, TCP_TIMESTAMP */
#include <stdint.h> /* uint32_t */
#include <sys/socket.h> /* sockaddr */
#include "common/config.h"
/* All packets with this mark have not to be blocked. */
#define SOCCR_MARK 0xC114
#ifndef CONFIG_HAS_TCP_REPAIR_WINDOW
struct tcp_repair_window {
uint32_t snd_wl1;
uint32_t snd_wnd;
uint32_t max_window;
uint32_t rcv_wnd;
uint32_t rcv_wup;
};
#endif
#ifndef CONFIG_HAS_TCP_REPAIR
/*
* It's been reported that both tcp_repair_opt
* and TCP_ enum already shipped in netinet/tcp.h
* system header by some distros thus we need a
* test if we can use predefined ones or provide
* our own.
*/
struct tcp_repair_opt {
uint32_t opt_code;
uint32_t opt_val;
};
enum {
TCP_NO_QUEUE,
TCP_RECV_QUEUE,
TCP_SEND_QUEUE,
TCP_QUEUES_NR,
};
#endif
#ifndef TCP_TIMESTAMP
#define TCP_TIMESTAMP 24
#endif
#ifndef TCP_REPAIR_WINDOW
#define TCP_REPAIR_WINDOW 29
#endif
void libsoccr_set_log(unsigned int level, void (*fn)(unsigned int level, const char *fmt, ...));
#define SOCCR_LOG_ERR 1
#define SOCCR_LOG_DBG 2
/*
* An opaque handler for C/R-ing a TCP socket.
*/
struct libsoccr_sk;
union libsoccr_addr {
struct sockaddr sa;
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
/*
* Connection info that should be saved after fetching from the
* socket and given back into the library in two steps (see below).
*/
struct libsoccr_sk_data {
uint32_t state;
uint32_t inq_len;
uint32_t inq_seq;
uint32_t outq_len;
uint32_t outq_seq;
uint32_t unsq_len;
uint32_t opt_mask;
uint32_t mss_clamp;
uint32_t snd_wscale;
uint32_t rcv_wscale;
uint32_t timestamp;
uint32_t flags; /* SOCCR_FLAGS_... below */
uint32_t snd_wl1;
uint32_t snd_wnd;
uint32_t max_window;
uint32_t rcv_wnd;
uint32_t rcv_wup;
};
/*
* The flags below denote which data on libsoccr_sk_data was get
* from the kernel and is required for restore. Not present data
* is zeroified by the library.
*
* Ideally the caller should carry the whole _data structure between
* calls, but for optimization purposes it may analyze the flags
* field and drop the unneeded bits.
*/
/*
* Window parameters. Mark snd_wl1, snd_wnd, max_window, rcv_wnd
* and rcv_wup fields.
*/
#define SOCCR_FLAGS_WINDOW 0x1
/*
* These two calls pause and resume the socket for and after C/R
* The first one returns an opaque handle that is to be used by all
* the subsequent calls.
*
* For now the library only supports ESTABLISHED sockets. The caller
* should check the socket is supported before calling the library.
*
* Before doing socket C/R make sure no packets can reach the socket
* you're working with, nor any packet can leave the node from this
* socket. This can be done by using netfilter DROP target (of by
* DOWN-ing an interface in case of containers).
*/
struct libsoccr_sk *libsoccr_pause(int fd);
void libsoccr_resume(struct libsoccr_sk *sk);
/* This one is like _resume, but doesn't turn repair off on socket. */
void libsoccr_release(struct libsoccr_sk *sk);
/*
* Flags for calls below
*/
/*
* Memory given to or taken from library is in exclusive ownership
* of the resulting owner. I.e. -- when taken by caller from library,
* the former will free() one, when given to the library, the latter
* is to free() it.
*/
#define SOCCR_MEM_EXCL 0x1
/*
* CHECKPOINTING calls
*
* Roughly the checkpoint steps for sockets in supported states are
*
* h = libsoccr_pause(sk);
* libsoccr_save(h, &data, sizeof(data))
* inq = libsoccr_get_queue_bytes(h, TCP_RECV_QUEUE, 0)
* outq = libsoccr_get_queue_bytes(h, TCP_SEND_QUEUE, 0)
* getsocname(sk, &name, ...)
* getpeername(sk, &peer, ...)
*
* save_all_bytes(h, inq, outq, name, peer)
*
* Resuming the socket afterwards effectively obsoletes the saved
* info, as the connection resumes and old saved bytes become
* outdated.
*
* Please note, that getsocname() and getpeername() are standard glibc
* calls, not the libsoccr's ones.
*/
/*
* Fills in the libsoccr_sk_data structure with connection info. The
* data_size shows the size of a buffer. The returned value is the
* amount of bytes put into data (the rest is zeroed with memcpy).
*/
int libsoccr_save(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size);
/*
* Get a pointer on the contents of queues. The amount of bytes is
* determined from the filled libsoccr_sk_data by queue_id.
*
* For TCP_RECV_QUEUE the length is .inq_len
* For TCP_SEND_QUEUE the length is .outq_len
*
* For any other queues returns NULL.
*
* The steal argument means that the caller grabs the buffer from
* library and should free() it himself. Otherwise the buffer can
* be claimed again and will be free by library upon _resume call.
*/
char *libsoccr_get_queue_bytes(struct libsoccr_sk *sk, int queue_id, unsigned flags);
/*
* Returns filled libsoccr_addr for a socket. This value is also required
* on restore, but addresses may be obtained from somewhere else, these
* are just common sockaddr-s.
*/
union libsoccr_addr *libsoccr_get_addr(struct libsoccr_sk *sk, int self, unsigned flags);
/*
* RESTORING calls
*
* The restoring of a socket is like below
*
* get_all_bytes(h, inq, outq, name, peer)
*
* sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
*
* h = libsoccr_pause(sk)
* libsoccr_set_queue_bytes(h, TCP_SEND_QUEUE, outq);
* libsoccr_set_queue_bytes(h, TCP_RECV_QUEUE, inq);
* libsoccr_set_addr(h, 1, src_addr);
* libsoccr_set_addr(h, 0, dst_addr);
* libsoccr_restore(h, &data, sizeof(data))
*
* libsoccr_resume(h)
*
* Only after this the packets path from and to the socket can be
* enabled back.
*/
/*
* Set a pointer on the send/recv queue data.
* If flags have SOCCR_MEM_EXCL, the buffer is stolen by the library and is
* free()-ed after libsoccr_resume().
*/
int libsoccr_set_queue_bytes(struct libsoccr_sk *sk, int queue_id, char *bytes, unsigned flags);
/*
* Set a pointer on the libsoccr_addr for src/dst.
* If flags have SOCCR_MEM_EXCL, the buffer is stolen by the library and is
* fre()-ed after libsoccr_resume().
*/
int libsoccr_set_addr(struct libsoccr_sk *sk, int self, union libsoccr_addr *, unsigned flags);
/*
* Performs restore actions on a socket
*/
int libsoccr_restore(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, unsigned data_size);
#endif
| 6,454 | 26.58547 | 96 |
h
|
criu
|
criu-master/soccr/test/tcp-constructor.c
|
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/socket.h>
#include <netinet/tcp.h>
#include <string.h>
#include <getopt.h>
#include <stdlib.h>
#include "soccr/soccr.h"
#define pr_perror(fmt, ...) \
({ \
fprintf(stderr, "%s:%d: " fmt " : %m\n", __func__, __LINE__, ##__VA_ARGS__); \
1; \
})
struct tcp {
char *addr;
uint32_t port;
uint32_t seq;
uint16_t mss_clamp;
uint16_t wscale;
};
static void usage(void)
{
printf("Usage: --addr ADDR -port PORT --seq SEQ --next --addr ADDR -port PORT --seq SEQ -- CMD ...\n"
"\t Describe a source side of a connection, then set the --next option\n"
"\t and describe a destination side.\n"
"\t --reverse - swap source and destination sides\n"
"\t The idea is that the same command line is execute on both sides,\n"
"\t but the --reverse is added to one of them.\n"
"\n"
"\t CMD ... - a user command to handle a socket, which is the descriptor 3.\n"
"\n"
"\t It prints the \"start\" on stdout when a socket is created and\n"
"\t resumes it when you write \"start\" to stdin.\n");
}
int main(int argc, char **argv)
{
static const char short_opts[] = "";
static struct option long_opts[] = {
{ "addr", required_argument, 0, 'a' }, { "port", required_argument, 0, 'p' },
{ "seq", required_argument, 0, 's' }, { "next", no_argument, 0, 'n' },
{ "reverse", no_argument, 0, 'r' }, {},
};
struct tcp tcp[2] = { { "127.0.0.1", 12345, 5000000, 1460, 7 }, { "127.0.0.1", 54321, 6000000, 1460, 7 } };
int sk, yes = 1, val, idx, opt, i, src = 0, dst = 1;
union libsoccr_addr src_addr, dst_addr;
struct libsoccr_sk_data data = {};
struct libsoccr_sk *so;
char buf[1024];
i = 0;
while (1) {
idx = -1;
opt = getopt_long(argc, argv, short_opts, long_opts, &idx);
if (opt == -1)
break;
switch (opt) {
case 'a':
tcp[i].addr = optarg;
break;
case 'p':
tcp[i].port = atol(optarg);
break;
case 's':
tcp[i].seq = atol(optarg);
break;
case 'n':
i++;
if (i > 1)
return pr_perror("--next is used twice or more");
break;
case 'r':
src = 1;
dst = 0;
break;
default:
usage();
return 3;
}
}
if (i != 1)
return pr_perror("--next is required");
if (optind == argc) {
usage();
return 1;
}
for (i = 0; i < 2; i++)
fprintf(stderr, "%s:%d:%d\n", tcp[i].addr, tcp[i].port, tcp[i].seq);
data.state = TCP_ESTABLISHED;
data.inq_seq = tcp[dst].seq;
data.outq_seq = tcp[src].seq;
sk = socket(AF_INET, SOCK_STREAM, 0);
if (sk < 0)
return pr_perror("socket");
so = libsoccr_pause(sk);
if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
return pr_perror("setsockopt");
src_addr.v4.sin_family = AF_INET;
src_addr.v4.sin_port = htons(tcp[src].port);
if (inet_pton(AF_INET, tcp[src].addr, &src_addr.v4.sin_addr) != 1)
return pr_perror("inet_pton");
dst_addr.v4.sin_family = AF_INET;
dst_addr.v4.sin_port = htons(tcp[dst].port);
if (inet_pton(AF_INET, tcp[dst].addr, &(dst_addr.v4.sin_addr)) != 1)
return pr_perror("inet_pton");
libsoccr_set_addr(so, 1, &src_addr, 0);
libsoccr_set_addr(so, 0, &dst_addr, 0);
data.snd_wscale = tcp[src].wscale;
data.rcv_wscale = tcp[dst].wscale;
data.mss_clamp = tcp[src].mss_clamp;
data.opt_mask = TCPI_OPT_WSCALE | TCPOPT_MAXSEG;
if (libsoccr_restore(so, &data, sizeof(data)))
return 1;
/* Let's go */
if (write(STDOUT_FILENO, "start", 5) != 5)
return pr_perror("write");
if (read(STDIN_FILENO, buf, 5) != 5)
return pr_perror("read");
val = 0;
if (setsockopt(sk, SOL_TCP, TCP_REPAIR, &val, sizeof(val)))
return pr_perror("TCP_REPAIR");
execv(argv[optind], argv + optind);
return pr_perror("Unable to exec %s", argv[optind]);
}
| 4,008 | 25.90604 | 108 |
c
|
criu
|
criu-master/test/zdtm_ct.c
|
#include <sched.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/mount.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/utsname.h>
#ifndef CLONE_NEWTIME
#define CLONE_NEWTIME 0x00000080 /* New time namespace */
#endif
static inline int _settime(clockid_t clk_id, time_t offset)
{
int fd, len;
char buf[4096];
if (clk_id == CLOCK_MONOTONIC_COARSE || clk_id == CLOCK_MONOTONIC_RAW)
clk_id = CLOCK_MONOTONIC;
len = snprintf(buf, sizeof(buf), "%d %ld 0", clk_id, offset);
fd = open("/proc/self/timens_offsets", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "/proc/self/timens_offsets: %m");
return -1;
}
if (write(fd, buf, len) != len) {
fprintf(stderr, "/proc/self/timens_offsets: %m");
return -1;
}
close(fd);
return 0;
}
static int create_timens(void)
{
struct utsname buf;
unsigned major, minor;
int fd, ret;
/*
* Before the 5.11 kernel, there is a known issue.
* start_time in /proc/pid/stat is printed in the host time
* namespace, but /proc/uptime is shown in the current time
* namespace, so criu can't compare them to detect tasks that
* reuse old pids.
*/
ret = uname(&buf);
if (ret)
return -1;
if (sscanf(buf.release, "%u.%u", &major, &minor) != 2)
return -1;
if ((major < 5) || (major == 5 && minor < 11)) {
fprintf(stderr, "timens isn't supported on %s\n", buf.release);
return 0;
}
if (unshare(CLONE_NEWTIME)) {
if (errno == EINVAL) {
fprintf(stderr, "timens isn't supported\n");
return 0;
} else {
fprintf(stderr, "unshare(CLONE_NEWTIME) failed: %m");
exit(1);
}
}
if (_settime(CLOCK_MONOTONIC, 110 * 24 * 60 * 60))
exit(1);
if (_settime(CLOCK_BOOTTIME, 40 * 24 * 60 * 60))
exit(1);
fd = open("/proc/self/ns/time_for_children", O_RDONLY);
if (fd < 0)
exit(1);
if (setns(fd, 0))
exit(1);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
uid_t uid;
pid_t pid;
int status;
uid = getuid();
/*
* pidns is used to avoid conflicts
* mntns is used to mount /proc
* net is used to avoid conflicts of parasite sockets
*/
if (!uid)
if (unshare(CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWIPC))
return 1;
pid = fork();
if (pid == 0) {
if (!uid) {
if (create_timens())
exit(1);
if (mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL)) {
fprintf(stderr, "mount(/, S_REC | MS_SLAVE)): %m");
return 1;
}
umount2("/proc", MNT_DETACH);
umount2("/dev/pts", MNT_DETACH);
if (mount("zdtm_proc", "/proc", "proc", 0, NULL)) {
fprintf(stderr, "mount(/proc): %m");
return 1;
}
if (mount("zdtm_devpts", "/dev/pts", "devpts", 0, "newinstance,ptmxmode=0666")) {
fprintf(stderr, "mount(pts): %m");
return 1;
}
if (mount("zdtm_binfmt", "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, NULL)) {
fprintf(stderr, "mount(binfmt_misc): %m");
return 1;
}
if (mount("/dev/pts/ptmx", "/dev/ptmx", NULL, MS_BIND, NULL)) {
fprintf(stderr, "mount(ptmx): %m");
return 1;
}
if (system("ip link set up dev lo"))
return 1;
}
execv(argv[1], argv + 1);
fprintf(stderr, "execve: %m");
return 1;
}
if (waitpid(pid, &status, 0) != pid) {
fprintf(stderr, "waitpid: %m");
return 1;
}
if (WIFEXITED(status))
return WEXITSTATUS(status);
else if (WIFSIGNALED(status))
kill(getpid(), WTERMSIG(status));
else
fprintf(stderr, "Unexpected exit status: %x\n", status);
return 1;
}
| 3,500 | 21.018868 | 84 |
c
|
criu
|
criu-master/test/compel/handle_binary.c
|
#include <string.h>
#include "uapi/piegen-err.h"
#include "piegen.h"
#include "arch_test_handle_binary.h"
extern int launch_test(void *mem, int expected_ret, const char *test_fmt, ...);
extern const size_t test_elf_buf_size;
static uintptr_t elf_addr;
static const char *test_bitness;
#define ASSERT(expected, fmt, ...) launch_test((void *)elf_addr, expected, fmt " %s", ##__VA_ARGS__, test_bitness)
static const unsigned int sections_nr = 1;
static void set_elf_hdr_relocatable(Ehdr_t *hdr)
{
hdr->e_type = ET_REL;
hdr->e_version = EV_CURRENT;
}
static int test_add_strings_section(Ehdr_t *hdr)
{
Shdr_t *sec_strings_hdr;
uintptr_t sections_table = elf_addr + hdr->e_shoff;
size_t sections_table_size = sections_nr * sizeof(hdr->e_shentsize);
hdr->e_shnum = sections_nr;
hdr->e_shstrndx = sections_nr; /* off-by-one */
if (ASSERT(-E_NO_STR_SEC, "strings section's header oob of section table"))
return -1;
hdr->e_shstrndx = 0;
sec_strings_hdr = (void *)sections_table;
sec_strings_hdr->sh_offset = (Off_t)-1;
if (ASSERT(-E_NO_STR_SEC, "strings section oob"))
return -1;
/* Put strings just right after sections table. */
sec_strings_hdr->sh_offset = sections_table - elf_addr + sections_table_size;
return 0;
}
static int test_prepare_section_table(Ehdr_t *hdr)
{
hdr->e_shoff = (Off_t)test_elf_buf_size;
if (ASSERT(-E_NO_STR_SEC, "section table start oob"))
return -1;
/* Lets put sections table right after ELF header. */
hdr->e_shoff = (Off_t)sizeof(Ehdr_t);
hdr->e_shentsize = (Half_t)sizeof(Shdr_t);
hdr->e_shnum = (Half_t)-1;
if (ASSERT(-E_NO_STR_SEC, "too many sections in table"))
return -1;
if (test_add_strings_section(hdr))
return -1;
return 0;
}
static int test_prepare_elf_header(void *elf)
{
memset(elf, 0, sizeof(Ehdr_t));
if (ASSERT(-E_NOT_ELF, "zero ELF header"))
return -1;
arch_test_set_elf_hdr_ident(elf);
if (ASSERT(-E_NOT_ELF, "unsupported ELF header"))
return -1;
arch_test_set_elf_hdr_machine(elf);
if (ASSERT(-E_NOT_ELF, "non-relocatable ELF header"))
return -1;
set_elf_hdr_relocatable(elf);
if (test_prepare_section_table(elf))
return -1;
return 0;
}
int __run_tests(void *mem, const char *msg)
{
elf_addr = (uintptr_t)mem;
test_bitness = msg;
if (test_prepare_elf_header(mem))
return 1;
return 0;
}
| 2,308 | 23.052083 | 114 |
c
|
criu
|
criu-master/test/compel/main.c
|
/*
* Test for handle_binary().
* In this test ELF binary file is constructed from
* header up to sections and relocations.
* On each stage it tests non-valid ELF binaries to be parsed.
* For passing test, handle_binary should return errors for all
* non-valid binaries and handle all relocations.
*
* Test author: Dmitry Safonov <[email protected]>
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include "piegen.h"
#include "arch_test_handle_binary.h"
/* size of buffer with formed ELF file */
const size_t test_elf_buf_size = 4096;
extern int handle_binary(void *mem, size_t size);
extern void run_tests(void *mem);
int launch_test(void *mem, int expected_ret, const char *test_fmt, ...)
{
static unsigned test_nr = 1;
int ret = handle_binary(mem, test_elf_buf_size);
va_list params;
va_start(params, test_fmt);
if (ret != expected_ret) {
printf("not ok %u - ", test_nr);
vprintf(test_fmt, params);
printf(", expected %d but ret is %d\n", expected_ret, ret);
} else {
printf("ok %u - ", test_nr);
vprintf(test_fmt, params);
putchar('\n');
}
va_end(params);
test_nr++;
fflush(stdout);
return ret != expected_ret;
}
int main(int argc, char **argv)
{
void *elf_buf = malloc(test_elf_buf_size);
int ret;
ret = arch_run_tests(elf_buf);
free(elf_buf);
return ret;
}
| 1,348 | 22.258621 | 71 |
c
|
criu
|
criu-master/test/compel/arch/aarch64/include/arch_test_handle_binary.h
|
#ifndef __ARCH_TEST_HANDLE_BINARY__
#define __ARCH_TEST_HANDLE_BINARY__
#include <string.h>
#include "uapi/elf64-types.h"
#define arch_run_tests(mem) __run_tests(mem, "")
extern int __run_tests(void *mem, const char *msg);
static __maybe_unused void arch_test_set_elf_hdr_ident(void *mem)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
memcpy(mem, elf_ident_64_le, sizeof(elf_ident_64_le));
#else
memcpy(mem, elf_ident_64_be, sizeof(elf_ident_64_be));
#endif
}
static __maybe_unused void arch_test_set_elf_hdr_machine(Ehdr_t *hdr)
{
hdr->e_machine = EM_AARCH64;
}
#endif /* __ARCH_TEST_HANDLE_BINARY__ */
| 614 | 23.6 | 69 |
h
|
criu
|
criu-master/test/compel/arch/ppc64/include/arch_test_handle_binary.h
|
#ifndef __ARCH_TEST_HANDLE_BINARY__
#define __ARCH_TEST_HANDLE_BINARY__
#include <string.h>
#include "uapi/elf64-types.h"
#define arch_run_tests(mem) __run_tests(mem, "")
extern int __run_tests(void *mem, const char *msg);
static __maybe_unused void arch_test_set_elf_hdr_ident(void *mem)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
memcpy(mem, elf_ident_64_le, sizeof(elf_ident_64_le));
#else
memcpy(mem, elf_ident_64_be, sizeof(elf_ident_64_be));
#endif
}
static __maybe_unused void arch_test_set_elf_hdr_machine(Ehdr_t *hdr)
{
hdr->e_machine = EM_PPC64;
}
#endif /* __ARCH_TEST_HANDLE_BINARY__ */
| 612 | 23.52 | 69 |
h
|
criu
|
criu-master/test/compel/arch/x86/include/arch_test_handle_binary.h
|
#ifndef __ARCH_TEST_HANDLE_BINARY__
#define __ARCH_TEST_HANDLE_BINARY__
#include <string.h>
#ifdef CONFIG_X86_64
#include "uapi/elf64-types.h"
#define __run_tests run_tests_64
static __maybe_unused void arch_test_set_elf_hdr_ident(void *mem)
{
memcpy(mem, elf_ident_64_le, sizeof(elf_ident_64_le));
}
static __maybe_unused void arch_test_set_elf_hdr_machine(Ehdr_t *hdr)
{
hdr->e_machine = EM_X86_64;
}
#else /* !CONFIG_X86_64 */
#include "uapi/elf32-types.h"
#define __run_tests run_tests_32
static __maybe_unused void arch_test_set_elf_hdr_ident(void *mem)
{
memcpy(mem, elf_ident_32, sizeof(elf_ident_32));
}
static __maybe_unused void arch_test_set_elf_hdr_machine(Ehdr_t *hdr)
{
hdr->e_machine = EM_386;
}
#endif /* CONFIG_X86_32 */
extern int run_tests_64(void *mem, const char *msg);
extern int run_tests_32(void *mem, const char *msg);
static __maybe_unused int arch_run_tests(void *mem)
{
int ret;
ret = run_tests_64(mem, "(64-bit ELF)");
ret += run_tests_32(mem, "(32-bit ELF)");
return ret;
}
#endif /* __ARCH_TEST_HANDLE_BINARY__ */
| 1,066 | 20.34 | 69 |
h
|
criu
|
criu-master/test/others/app-emu/make/tmpl.c
|
int foo(int a, int b)
{
#define A0(a, b) ((a) + (b))
#define A1(a, b) ((a) > (b)) ? A0((a) - (b), (b)) : A0((b) - (a), (a))
#define A2(a, b) ((a) > (b)) ? A1((a) - (b), (b)) : A1((b) - (a), (a))
#define A3(a, b) ((a) > (b)) ? A2((a) - (b), (b)) : A2((b) - (a), (a))
#define A4(a, b) ((a) > (b)) ? A3((a) - (b), (b)) : A3((b) - (a), (a))
#define A5(a, b) ((a) > (b)) ? A4((a) - (b), (b)) : A4((b) - (a), (a))
#define A6(a, b) ((a) > (b)) ? A5((a) - (b), (b)) : A5((b) - (a), (a))
#define A7(a, b) ((a) > (b)) ? A6((a) - (b), (b)) : A6((b) - (a), (a))
#define A8(a, b) ((a) > (b)) ? A7((a) - (b), (b)) : A7((b) - (a), (a))
#define A9(a, b) ((a) > (b)) ? A8((a) - (b), (b)) : A8((b) - (a), (a))
#define A10(a, b) ((a) > (b)) ? A9((a) - (b), (b)) : A9((b) - (a), (a))
#define A11(a, b) ((a) > (b)) ? A10((a) - (b), (b)) : A10((b) - (a), (a))
return A10(a, b);
}
| 869 | 50.176471 | 73 |
c
|
criu
|
criu-master/test/others/bers/bers.c
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <limits.h>
#include <stdbool.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <syscall.h>
#define min(x, y) \
({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void)(&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; \
})
#define max(x, y) \
({ \
typeof(x) _max1 = (x); \
typeof(y) _max2 = (y); \
(void)(&_max1 == &_max2); \
_max1 > _max2 ? _max1 : _max2; \
})
#define MAX_CHUNK 4096
#define PAGE_SIZE 4096
#define pr_info(fmt, ...) printf("%8d: " fmt, sys_gettid(), ##__VA_ARGS__)
#define pr_err(fmt, ...) printf("%8d: Error (%s:%d): " fmt, sys_gettid(), __FILE__, __LINE__, ##__VA_ARGS__)
#define pr_perror(fmt, ...) pr_err(fmt ": %m\n", ##__VA_ARGS__)
#define pr_msg(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define pr_trace(fmt, ...) printf("%8d: %s: " fmt, sys_gettid(), __func__, ##__VA_ARGS__)
enum {
MEM_FILL_MODE_NONE = 0,
MEM_FILL_MODE_ALL = 1,
MEM_FILL_MODE_LIGHT = 2,
MEM_FILL_MODE_DIRTIFY = 3,
};
typedef struct {
pthread_mutex_t mutex;
pthread_mutexattr_t mutex_attr;
size_t opt_tasks;
size_t opt_files;
size_t opt_file_size;
int prev_fd[MAX_CHUNK];
size_t opt_mem;
size_t opt_mem_chunks;
size_t opt_mem_chunk_size;
int opt_mem_fill_mode;
int opt_mem_cycle_mode;
unsigned int opt_refresh_time;
char *opt_work_dir;
int work_dir_fd;
DIR *work_dir;
pid_t err_pid;
int err_no;
unsigned long prev_map[MAX_CHUNK];
} shared_data_t;
static shared_data_t *shared;
static int sys_gettid(void)
{
return syscall(__NR_gettid);
}
static void dirtify_memory(unsigned long *chunks, size_t nr_chunks, size_t chunk_size, int mode, const size_t nr_pages)
{
size_t i;
pr_trace("filling memory\n");
switch (mode) {
case MEM_FILL_MODE_LIGHT:
*((unsigned long *)chunks[0]) = -1ul;
break;
case MEM_FILL_MODE_ALL:
for (i = 0; i < nr_chunks; i++)
memset((void *)chunks[i], (char)i, chunk_size);
break;
case MEM_FILL_MODE_DIRTIFY:
for (i = 0; i < nr_chunks; i++)
*((unsigned long *)chunks[i]) = -1ul;
break;
}
}
static void dirtify_files(int *fd, size_t nr_files, size_t size)
{
size_t buf[8192];
size_t i;
/*
* Note we don't write any _sane_ data here, the only
* important thing is I/O activity by self.
*/
for (i = 0; i < nr_files; i++) {
size_t c = min(size, sizeof(buf));
size_t left = size;
while (left > 0) {
write(fd[i], buf, c);
left -= c;
c = min(left, sizeof(buf));
}
}
}
static int create_files(shared_data_t *shared, int *fd, size_t nr_files)
{
char path[PATH_MAX];
size_t i;
memset(fd, 0xff, sizeof(*fd) * MAX_CHUNK);
pr_info("\tCreating %lu files\n", shared->opt_files);
for (i = 0; i < shared->opt_files; i++) {
if (shared->prev_fd[i] != -1) {
close(shared->prev_fd[i]);
shared->prev_fd[i] = -1;
}
snprintf(path, sizeof(path), "%08d-%04d-temp", sys_gettid(), i);
fd[i] = openat(shared->work_dir_fd, path, O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd[i] < 0) {
pr_perror("Can't open %s/%s", shared->opt_work_dir, path);
shared->err_pid = sys_gettid();
shared->err_no = -errno;
return -1;
}
shared->prev_fd[i] = fd[i];
}
return 0;
}
static void work_on_fork(shared_data_t *shared)
{
const size_t nr_pages = shared->opt_mem_chunk_size / PAGE_SIZE;
unsigned long chunks[MAX_CHUNK] = {};
int fd[MAX_CHUNK];
size_t i;
void *mem;
pr_trace("locking\n");
pthread_mutex_lock(&shared->mutex);
pr_trace("init\n");
pr_info("\tCreating %lu mmaps each %lu K\n", shared->opt_mem_chunks, shared->opt_mem_chunk_size >> 10);
for (i = 0; i < shared->opt_mem_chunks; i++) {
if (shared->prev_map[i]) {
munmap((void *)shared->prev_map[i], shared->opt_mem_chunk_size);
shared->prev_map[i] = 0;
}
/* If we won't change proto here, the kernel might merge close areas */
mem = mmap(NULL, shared->opt_mem_chunk_size, PROT_READ | PROT_WRITE | ((i % 2) ? PROT_EXEC : 0),
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (mem != (void *)MAP_FAILED) {
shared->prev_map[i] = (unsigned long)mem;
chunks[i] = (unsigned long)mem;
pr_info("\t\tMap at %lx\n", (unsigned long)mem);
} else {
pr_info("\t\tCan't map\n");
shared->err_pid = sys_gettid();
shared->err_no = -errno;
exit(1);
}
}
if (shared->opt_mem_fill_mode)
dirtify_memory(chunks, shared->opt_mem_chunks, shared->opt_mem_chunk_size, shared->opt_mem_fill_mode,
nr_pages);
if (create_files(shared, fd, shared->opt_files))
exit(1);
if (shared->opt_file_size)
dirtify_files(fd, shared->opt_files, shared->opt_file_size);
pr_trace("releasing\n");
pthread_mutex_unlock(&shared->mutex);
while (1) {
sleep(shared->opt_refresh_time);
if (shared->opt_mem_cycle_mode)
dirtify_memory(chunks, shared->opt_mem_chunks, shared->opt_mem_chunk_size,
shared->opt_mem_cycle_mode, nr_pages);
if (shared->opt_file_size)
dirtify_files(fd, shared->opt_files, shared->opt_file_size);
}
}
static int parse_mem_mode(int *mode, char *opt)
{
if (!strcmp(opt, "all")) {
*mode = MEM_FILL_MODE_ALL;
} else if (!strcmp(opt, "light")) {
*mode = MEM_FILL_MODE_LIGHT;
} else if (!strcmp(opt, "dirtify")) {
*mode = MEM_FILL_MODE_DIRTIFY;
} else {
pr_err("Unrecognized option %s\n", opt);
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
/* a - 97, z - 122, A - 65, 90 */
static const char short_opts[] = "t:d:f:m:c:h";
static struct option long_opts[] = {
{ "tasks", required_argument, 0, 't' },
{ "dir", required_argument, 0, 'd' },
{ "files", required_argument, 0, 'f' },
{ "memory", required_argument, 0, 'm' },
{ "mem-chunks", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "mem-fill", required_argument, 0, 10 },
{ "mem-cycle", required_argument, 0, 11 },
{ "refresh", required_argument, 0, 12 },
{ "file-size", required_argument, 0, 13 },
{},
};
char workdir[PATH_MAX];
int opt, idx, pidfd;
char pidbuf[32];
pid_t pid;
size_t i;
shared = (void *)mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if ((void *)shared == MAP_FAILED) {
pr_err("Failed to setup shared data\n");
exit(1);
}
pthread_mutexattr_init(&shared->mutex_attr);
pthread_mutexattr_setpshared(&shared->mutex_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&shared->mutex, &shared->mutex_attr);
/*
* Default options.
*/
shared->opt_mem_chunks = 1;
shared->opt_refresh_time = 1;
shared->opt_tasks = 1;
shared->opt_mem = 1 << 20ul;
memset(shared->prev_fd, 0xff, sizeof(shared->prev_fd));
while (1) {
idx = -1;
opt = getopt_long(argc, argv, short_opts, long_opts, &idx);
if (opt == -1)
break;
switch (opt) {
case 't':
shared->opt_tasks = (size_t)atol(optarg);
break;
case 'f':
shared->opt_files = (size_t)atol(optarg);
break;
case 'm':
/* In megabytes */
shared->opt_mem = (size_t)atol(optarg) << 20ul;
break;
case 'c':
shared->opt_mem_chunks = (size_t)atol(optarg);
break;
case 'd':
shared->opt_work_dir = optarg;
break;
case 'h':
goto usage;
break;
case 10:
if (parse_mem_mode(&shared->opt_mem_fill_mode, optarg))
goto usage;
case 11:
if (parse_mem_mode(&shared->opt_mem_cycle_mode, optarg))
goto usage;
break;
case 12:
shared->opt_refresh_time = (unsigned int)atoi(optarg);
break;
case 13:
shared->opt_file_size = (size_t)atol(optarg);
}
}
if (!shared->opt_work_dir) {
shared->opt_work_dir = getcwd(workdir, sizeof(workdir));
if (!shared->opt_work_dir) {
pr_perror("Can't fetch current working dir");
exit(1);
}
shared->opt_work_dir = workdir;
}
if (shared->opt_mem_chunks > MAX_CHUNK)
shared->opt_mem_chunks = MAX_CHUNK;
if (shared->opt_files > MAX_CHUNK)
shared->opt_files = MAX_CHUNK;
shared->work_dir = opendir(shared->opt_work_dir);
if (!shared->work_dir) {
pr_perror("Can't open working dir `%s'", shared->opt_work_dir);
exit(1);
}
shared->work_dir_fd = dirfd(shared->work_dir);
shared->opt_mem_chunk_size = shared->opt_mem / shared->opt_mem_chunks;
if (shared->opt_mem_chunk_size && shared->opt_mem_chunk_size < PAGE_SIZE) {
pr_err("Memory chunk size is too small, provide at least %lu M of memory\n",
(shared->opt_mem_chunks * PAGE_SIZE) >> 20ul);
exit(1);
}
for (i = 0; i < shared->opt_tasks; i++) {
if (shared->err_no)
goto err_child;
pid = fork();
if (pid < 0) {
pr_perror("Can't fork");
exit(1);
} else if (pid == 0) {
work_on_fork(shared);
}
}
/*
* Once everything is done and we're in cycle,
* create pidfile and go to sleep...
*/
pid = sys_gettid();
pidfd = openat(shared->work_dir_fd, "bers.pid", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (pidfd < 0) {
pr_perror("Can't open pidfile");
exit(1);
}
snprintf(pidbuf, sizeof(pidbuf), "%d", sys_gettid());
write(pidfd, pidbuf, strlen(pidbuf));
close(pidfd);
pidfd = -1;
/*
* Endless!
*/
while (!shared->err_no)
sleep(1);
err_child:
pr_err("Child %d exited with %d\n", shared->err_pid, shared->err_no);
return shared->err_no;
usage:
pr_msg("bers [options]\n");
pr_msg(" -t|--tasks <num> create <num> of tasks\n");
pr_msg(" -d|--dir <dir> use directory <dir> for temporary files\n");
pr_msg(" -f|--files <num> create <num> files for each task\n");
pr_msg(" -m|--memory <num> allocate <num> megabytes for each task\n");
pr_msg(" --memory-chunks <num> split memory to <num> equal parts\n");
pr_msg(" --mem-fill <mode> fill memory with data dependin on <mode>:\n");
pr_msg(" all fill every byte of memory\n");
pr_msg(" light fill first bytes of every page\n");
pr_msg(" dirtify fill every page\n");
pr_msg(" --mem-cycle <mode> same as --mem-fill but for cycling\n");
pr_msg(" --refresh <second> refresh loading of every task each <second>\n");
pr_msg(" --file-size <bytes> write <bytes> of data into each file on every refresh cycle\n");
return 1;
}
| 10,367 | 24.663366 | 119 |
c
|
criu
|
criu-master/test/others/libcriu/test_feature_check.c
|
#include "criu.h"
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "lib.h"
int main(int argc, char **argv)
{
int ret;
char *env;
bool mem_track = 0;
bool lazy_pages = 0;
bool pidfd_store = 0;
struct criu_feature_check features = {
.mem_track = true,
.lazy_pages = true,
.pidfd_store = true,
};
printf("--- Start feature check ---\n");
criu_init_opts();
criu_set_service_binary(argv[1]);
env = getenv("CRIU_FEATURE_MEM_TRACK");
if (env) {
mem_track = true;
}
env = getenv("CRIU_FEATURE_LAZY_PAGES");
if (env) {
lazy_pages = true;
}
env = getenv("CRIU_FEATURE_PIDFD_STORE");
if (env) {
pidfd_store = true;
}
ret = criu_feature_check(&features, sizeof(features) + 1);
printf(" `- passing too large structure to libcriu should return -1: %d\n", ret);
if (ret != -1)
return -1;
ret = criu_feature_check(&features, sizeof(features));
if (ret < 0) {
what_err_ret_mean(ret);
return ret;
}
printf(" `- mem_track : %d - expected : %d\n", features.mem_track, mem_track);
if (features.mem_track != mem_track)
return -1;
printf(" `- lazy_pages : %d - expected : %d\n", features.lazy_pages, lazy_pages);
if (features.lazy_pages != lazy_pages)
return -1;
printf(" `- pidfd_store: %d - expected : %d\n", features.pidfd_store, pidfd_store);
if (features.pidfd_store != pidfd_store)
return -1;
return 0;
}
| 1,483 | 21.484848 | 86 |
c
|
criu
|
criu-master/test/others/pipes/pipe.c
|
/*
* A simple demo/test program using criu's --inherit-fd command line
* option to restore a process with (1) an external pipe and (2) a
* new log file.
*
* Note that it's possible to restore the process without --inherit-fd,
* but when it reads from or writes to the pipe, it will get a broken
* pipe signal.
*
* Also note that changing the log file during restore has nothing to do
* with the pipe. It's just a nice feature for cases where it's desirable
* to have a restored process use a different file then the original one.
*
* The parent process spawns a child that will write messages to its
* parent through a pipe. After a couple of messages, parent invokes
* criu to checkpoint the child. Since the child exits after checkpoint,
* its pipe will be broken. Parent sets up a new pipe and invokes criu
* to restore the child using the new pipe (instead of the old one).
* The restored child exits after writing a couple more messages.
*
* To make sure that fd clashes are correctly handled during restore,
* child can optionally open a regular file and move it to a clashing fd.
*
* Make sure CRIU_BINARY defined below points to the right criu.
*
* $ cc -Wall -o pipe pipe.c
* $ sudo ./pipe -v
*
* The following should all succeed:
*
* $ sudo ./pipe -q && echo OK
* $ sudo ./pipe -qc && echo OK
* $ sudo ./pipe -qcl && echo OK
* $ sudo ./pipe -qd && echo OK
* $ sudo ./pipe -qdc && echo OK
* $ sudo ./pipe -qdcl && echo OK
*
* The following should all fail:
*
* $ sudo ./pipe -qn || echo $?
* $ sudo ./pipe -qo || echo $?
* $ sudo ./pipe -qr || echo $?
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/prctl.h>
typedef void (*sighandler_t)(int);
typedef unsigned long ulong;
/* colors */
#define CS_PARENT "\033[00;32m"
#define CS_CHILD "\033[00;33m"
#define CS_DUMP "\033[00;34m"
#define CS_RESTORE "\033[00;35m"
#define CE "\033[0m"
#define die(fmt, ...) \
do { \
if (!qflag) \
fprintf(stderr, fmt ": %m\n", __VA_ARGS__); \
if (getpid() == parent_pid) { \
(void)kill(0, 9); \
exit(1); \
} \
_exit(1); \
} while (0)
#define READ_FD 0 /* pipe read fd */
#define WRITE_FD 1 /* pipe write fd */
#define CLASH_FD 3 /* force inherit fd clash */
#define MAX_FORKS 3 /* child, checkpoint, restore */
#define CRIU_BINARY "../../../criu/criu"
#define IMG_DIR "images"
#define DUMP_LOG_FILE "dump.log"
#define RESTORE_LOG_FILE "restore.log"
#define RESTORE_PID_FILE "restore.pid"
#define INHERIT_FD_OPTION "--inherit-fd"
#define OLD_LOG_FILE "/tmp/oldlog"
#define NEW_LOG_FILE "/tmp/newlog"
/*
* Command line options (see usage()).
*/
char *cli_flags = "cdhlnoqrv";
int cflag;
int dflag;
int lflag;
int nflag;
int oflag;
int qflag;
int rflag;
int vflag;
char pid_number[8];
char inh_pipe_opt[16];
char inh_pipe_arg[64];
char inh_file_opt[16];
char inh_file_arg[64];
char *dump_argv[] = { "criu", "dump", "-D", IMG_DIR, "-o", DUMP_LOG_FILE, "-v4", "-t", pid_number, NULL };
char *restore_argv[] = {
"criu", "restore", "-d", "-D", IMG_DIR, "-o", RESTORE_LOG_FILE,
"--pidfile", RESTORE_PID_FILE, "-v4", inh_pipe_opt, inh_pipe_arg, inh_file_opt, inh_file_arg,
NULL
};
int max_msgs;
int max_forks;
int parent_pid;
int child_pid;
int criu_dump_pid;
int criu_restore_pid;
/* prototypes */
void chld_handler(int signum);
int parent(int *pipefd);
int child(int *pipefd, int dupfd, int newfd);
void checkpoint_child(int child_pid, int *pipefd);
void restore_child(int *new_pipefd, char *old_pipe_name);
void write_to_fd(int fd, char *name, int i, int newline);
void ls_proc_fd(int fd);
char *pipe_name(int fd);
char *who(pid_t pid);
void pipe_safe(int pipefd[2]);
pid_t fork_safe(void);
void signal_safe(int signum, sighandler_t handler);
int open_safe(char *pathname, int flags);
void close_safe(int fd);
void write_safe(int fd, char *buf, int count);
int read_safe(int fd, char *buf, int count);
int dup_safe(int oldfd);
void move_fd(int oldfd, int newfd);
void mkdir_safe(char *dirname, int mode);
void unlink_safe(char *pathname);
void execv_safe(char *path, char *argv[], int ls);
pid_t waitpid_safe(pid_t pid, int *status, int options, int id);
void prctl_safe(int option, ulong arg2, ulong arg3, ulong arg4, ulong arg5);
int dup2_safe(int oldfd, int newfd);
void usage(char *cmd)
{
printf("Usage: %s [%s]\n", cmd, cli_flags);
printf("-c\tcause a clash during restore by opening %s as fd %d\n", OLD_LOG_FILE, CLASH_FD);
printf("-d\tdup the pipe and write to it\n");
printf("-l\tchange log file from %s to %s during restore\n", OLD_LOG_FILE, NEW_LOG_FILE);
printf("\n");
printf("The following flags should cause restore failure\n");
printf("-n\tdo not use the %s option\n", INHERIT_FD_OPTION);
printf("-o\topen the pipe via /proc/<pid>/fd and write to it\n");
printf("-r\tspecify read end of pipe during restore\n");
printf("\n");
printf("Miscellaneous flags\n");
printf("-h\tprint this help and exit\n");
printf("-q\tquiet mode, don't print anything\n");
printf("-v\tverbose mode (list contents of /proc/<pid>/fd)\n");
}
int main(int argc, char *argv[])
{
int ret;
int opt;
int pipefd[2];
max_msgs = 4;
while ((opt = getopt(argc, argv, cli_flags)) != -1) {
switch (opt) {
case 'c':
cflag++;
break;
case 'd':
dflag++;
max_msgs += 4;
break;
case 'h':
usage(argv[0]);
return 0;
case 'l':
lflag++;
break;
case 'n':
nflag++;
break;
case 'o':
oflag++;
max_msgs += 4;
break;
case 'q':
qflag++;
vflag = 0;
break;
case 'r':
rflag++;
break;
case 'v':
vflag++;
qflag = 0;
break;
default:
usage(argv[0]);
return 1;
}
}
setbuf(stdout, NULL);
setbuf(stderr, NULL);
mkdir_safe(IMG_DIR, 0700);
pipe_safe(pipefd);
child_pid = fork_safe();
if (child_pid > 0) {
parent_pid = getpid();
signal_safe(SIGCHLD, chld_handler);
prctl_safe(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
close_safe(pipefd[WRITE_FD]);
ret = parent(pipefd);
} else {
/* child */
int dupfd = -1;
int openfd = -1;
int logfd, flags;
child_pid = getpid();
close_safe(pipefd[READ_FD]);
setsid();
logfd = open_safe(OLD_LOG_FILE, O_WRONLY | O_APPEND | O_CREAT);
dup2_safe(logfd, 1);
dup2_safe(logfd, 2);
close(logfd);
close(0);
/* open a regular file and move it to CLASH_FD */
if (cflag)
move_fd(open_safe(OLD_LOG_FILE, O_WRONLY | O_APPEND | O_CREAT), CLASH_FD);
fcntl(pipefd[WRITE_FD], F_SETFL, O_NONBLOCK | O_WRONLY);
/* open additional descriptors on the pipe and use them all */
if (dflag)
dupfd = dup_safe(pipefd[WRITE_FD]);
if (oflag) {
char buf[128];
snprintf(buf, sizeof buf, "/proc/self/fd/%d", pipefd[WRITE_FD]);
openfd = open_safe(buf, O_WRONLY);
}
ret = child(pipefd, dupfd, openfd);
flags = fcntl(pipefd[WRITE_FD], F_GETFL, 0);
if ((flags & O_NONBLOCK) == 0) {
printf("Unexpected flags %x\n", flags);
ret = -1;
}
}
return ret;
}
/*
* Parent reads message from its pipe with the child.
* After a couple of messages, it checkpoints the child
* which causes the child to exit. Parent then creates
* a new pipe and restores the child.
*/
int parent(int *pipefd)
{
char buf[32];
char old_pipe[32];
int nread;
nread = 0;
while (max_forks <= MAX_FORKS) {
if (read_safe(pipefd[READ_FD], buf, sizeof buf) == 0)
continue;
nread++;
if (vflag && nread == 1)
ls_proc_fd(-1);
if (!qflag) {
printf("%s read %s from %s\n", who(0), buf, pipe_name(pipefd[READ_FD]));
}
if (nread == (max_msgs / 2)) {
checkpoint_child(child_pid, pipefd);
if (!nflag) {
/* save the old pipe's name before closing it */
snprintf(old_pipe, sizeof old_pipe, "%s", pipe_name(pipefd[READ_FD]));
close_safe(pipefd[READ_FD]);
/* create a new one */
if (!qflag)
printf("%s creating a new pipe\n", who(0));
pipe_safe(pipefd);
}
restore_child(pipefd, old_pipe);
}
}
return 0;
}
/*
* Child sends a total of max_messages messages to its
* parent, half before checkpoint and half after restore.
*/
int child(int *pipefd, int dupfd, int openfd)
{
int i;
int fd;
int num_wfds;
struct timespec req = { 1, 0 };
/*
* Count the number of pipe descriptors we'll be
* writing to. At least 1 (for pipefd[WRITE_FD])
* and at most 3.
*/
num_wfds = 1;
if (dupfd >= 0)
num_wfds++;
if (openfd >= 0)
num_wfds++;
for (i = 0; i < max_msgs; i++) {
/* print first time and after checkpoint */
if (vflag && (i == 0 || i == (max_msgs / 2)))
ls_proc_fd(-1);
switch (i % num_wfds) {
case 0:
fd = pipefd[WRITE_FD];
break;
case 1:
fd = dflag ? dupfd : openfd;
break;
case 2:
fd = openfd;
break;
}
write_to_fd(fd, pipe_name(pipefd[WRITE_FD]), i + 1, 0);
if (cflag)
write_to_fd(CLASH_FD, "log file", i + 1, 1);
/*
* Since sleep will be interrupted by C/R, make sure
* to sleep an entire second to minimize the chance of
* writing before criu restore has exited. If criu is
* still around and we write to a broken pipe, we'll be
* killed but SIGCHLD will be delivered to criu instead
* of parent.
*/
while (nanosleep(&req, NULL))
;
if (!qflag)
printf("\n");
}
return 0;
}
void chld_handler(int signum)
{
int status;
pid_t pid;
pid = waitpid_safe(-1, &status, WNOHANG, 1);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
if (pid == child_pid) {
if (!qflag) {
printf("%s %s exited with status %d\n", who(0), who(pid), status);
}
/* if child exited successfully, we're done */
if (status == 0)
exit(0);
/* checkpoint kills the child */
if (status != 9)
exit(status);
}
}
void checkpoint_child(int child_pid, int *pipefd)
{
/* prepare -t <pid> */
snprintf(pid_number, sizeof pid_number, "%d", child_pid);
criu_dump_pid = fork_safe();
if (criu_dump_pid > 0) {
int status;
pid_t pid;
pid = waitpid_safe(criu_dump_pid, &status, 0, 2);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
if (!qflag) {
printf("%s %s exited with status %d\n", who(0), who(pid), status);
}
if (status)
exit(status);
} else {
close(pipefd[READ_FD]);
criu_dump_pid = getpid();
execv_safe(CRIU_BINARY, dump_argv, 0);
}
}
void restore_child(int *new_pipefd, char *old_pipe_name)
{
char buf[64];
criu_restore_pid = fork_safe();
if (criu_restore_pid > 0) {
int status;
pid_t pid;
if (!nflag)
close_safe(new_pipefd[WRITE_FD]);
pid = waitpid_safe(criu_restore_pid, &status, 0, 3);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
if (!qflag) {
printf("%s %s exited with status %d\n", who(0), who(pid), status);
}
if (status)
exit(status);
} else {
criu_restore_pid = getpid();
if (!nflag) {
/*
* We should close the read descriptor of the new pipe
* and use its write descriptor to call criu restore.
* But if rflag was set (for testing purposes), use the
* read descriptor which should cause the application to
* fail.
*
* Regardless of read or write descriptor, move it to a
* clashing fd to test inherit fd clash resolve code.
*/
if (rflag)
move_fd(new_pipefd[READ_FD], CLASH_FD);
else {
close_safe(new_pipefd[READ_FD]);
move_fd(new_pipefd[WRITE_FD], CLASH_FD);
}
/* --inherit-fd fd[CLASH_FD]:pipe[xxxxxx] */
snprintf(inh_pipe_opt, sizeof inh_pipe_opt, "%s", INHERIT_FD_OPTION);
snprintf(inh_pipe_arg, sizeof inh_pipe_arg, "fd[%d]:%s", CLASH_FD, old_pipe_name);
if (lflag) {
/* create a new log file to replace the old one */
int filefd = open_safe(NEW_LOG_FILE, O_WRONLY | O_APPEND | O_CREAT);
/* --inherit-fd fd[x]:tmp/oldlog */
snprintf(inh_file_opt, sizeof inh_file_opt, "%s", INHERIT_FD_OPTION);
snprintf(inh_file_arg, sizeof inh_file_arg, "fd[%d]:%s", filefd, OLD_LOG_FILE + 1);
restore_argv[12] = inh_file_opt;
} else
restore_argv[12] = NULL;
restore_argv[10] = inh_pipe_opt;
} else
restore_argv[10] = NULL;
snprintf(buf, sizeof buf, "%s/%s", IMG_DIR, RESTORE_PID_FILE);
unlink_safe(buf);
execv_safe(CRIU_BINARY, restore_argv, 1);
}
}
void write_to_fd(int fd, char *name, int i, int newline)
{
int n;
char buf[16]; /* fit "hello d\n" for small d */
n = snprintf(buf, sizeof buf, "hello %d", i);
if (!qflag)
printf("%s writing %s to %s via fd %d\n", who(0), buf, name, fd);
if (newline) {
buf[n++] = '\n';
buf[n] = '\0';
}
write_safe(fd, buf, strlen(buf));
}
void ls_proc_fd(int fd)
{
char cmd[128];
if (qflag)
return;
if (fd == -1)
snprintf(cmd, sizeof cmd, "ls -l /proc/%d/fd", getpid());
else
snprintf(cmd, sizeof cmd, "ls -l /proc/%d/fd/%d", getpid(), fd);
printf("%s %s\n", who(0), cmd);
system(cmd);
}
char *pipe_name(int fd)
{
static char pipe_name[64];
char path[64];
snprintf(path, sizeof path, "/proc/self/fd/%d", fd);
if (readlink(path, pipe_name, sizeof pipe_name) == -1)
die("readlink: path=%s", path);
return pipe_name;
}
/*
* Use two buffers to support two calls to
* this function in a printf argument list.
*/
char *who(pid_t pid)
{
static char pidstr1[64];
static char pidstr2[64];
static char *cp;
char *np;
char *ep;
int p;
p = pid ? pid : getpid();
if (p == parent_pid) {
np = "parent";
ep = CS_PARENT;
} else if (p == child_pid) {
np = "child";
ep = CS_CHILD;
} else if (p == criu_dump_pid) {
np = "dump";
ep = CS_DUMP;
} else if (p == criu_restore_pid) {
np = "restore";
ep = CS_RESTORE;
} else
np = "???";
cp = (cp == pidstr1) ? pidstr2 : pidstr1;
snprintf(cp, sizeof pidstr1, "%s[%s %d]", pid ? "" : ep, np, p);
return cp;
}
void pipe_safe(int pipefd[2])
{
if (pipe(pipefd) == -1)
die("pipe: %p", pipefd);
}
pid_t fork_safe(void)
{
pid_t pid;
if ((pid = fork()) == -1)
die("fork: pid=%d", pid);
max_forks++;
return pid;
}
void signal_safe(int signum, sighandler_t handler)
{
if (signal(signum, handler) == SIG_ERR)
die("signal: signum=%d", signum);
}
int open_safe(char *pathname, int flags)
{
int fd;
if ((fd = open(pathname, flags, 0777)) == -1)
die("open: pathname=%s", pathname);
return fd;
}
void close_safe(int fd)
{
if (close(fd) == -1)
die("close: fd=%d", fd);
}
void write_safe(int fd, char *buf, int count)
{
if (write(fd, buf, count) != count) {
die("write: fd=%d buf=\"%s\" count=%d errno=%d", fd, buf, count, errno);
}
}
int read_safe(int fd, char *buf, int count)
{
int n;
if ((n = read(fd, buf, count)) < 0)
die("read: fd=%d count=%d", fd, count);
buf[n] = '\0';
return n;
}
int dup_safe(int oldfd)
{
int newfd;
if ((newfd = dup(oldfd)) == -1)
die("dup: oldfd=%d", oldfd);
return newfd;
}
int dup2_safe(int oldfd, int newfd)
{
if (dup2(oldfd, newfd) != newfd)
die("dup2: oldfd=%d newfd=%d", oldfd, newfd);
return newfd;
}
void move_fd(int oldfd, int newfd)
{
if (oldfd != newfd) {
dup2_safe(oldfd, newfd);
close_safe(oldfd);
}
}
void mkdir_safe(char *dirname, int mode)
{
if (mkdir(dirname, mode) == -1 && errno != EEXIST)
die("mkdir dirname=%s mode=0x%x\n", dirname, mode);
}
void unlink_safe(char *pathname)
{
if (unlink(pathname) == -1 && errno != ENOENT) {
die("unlink: pathname=%s\n", pathname);
}
}
void execv_safe(char *path, char *argv[], int ls)
{
int i;
struct timespec req = { 0, 1000000 };
if (!qflag) {
printf("\n%s ", who(0));
for (i = 0; argv[i] != NULL; i++)
printf("%s ", argv[i]);
printf("\n");
}
/* give parent a chance to wait for us */
while (nanosleep(&req, NULL))
;
if (vflag && ls)
ls_proc_fd(-1);
execv(path, argv);
die("execv: path=%s", path);
}
pid_t waitpid_safe(pid_t pid, int *status, int options, int id)
{
pid_t p;
p = waitpid(pid, status, options);
if (p == -1)
fprintf(stderr, "waitpid pid=%d id=%d %m\n", pid, id);
return p;
}
void prctl_safe(int option, ulong arg2, ulong arg3, ulong arg4, ulong arg5)
{
if (prctl(option, arg2, arg3, arg4, arg5) == -1)
die("prctl: option=0x%x", option);
}
| 16,461 | 22.450142 | 106 |
c
|
criu
|
criu-master/test/others/socketpairs/socketpair.c
|
/*
* A simple demo/test program using criu's --inherit-fd command line
* option to restore a process with an external unix socket.
* Extending inherit's logic to unix sockets created by socketpair(..) syscall.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/socket.h>
typedef void (*sighandler_t)(int);
typedef unsigned long ulong;
/* colors */
#define CS_PARENT "\033[00;32m"
#define CS_CHILD "\033[00;33m"
#define CS_DUMP "\033[00;34m"
#define CS_RESTORE "\033[00;35m"
#define CE "\033[0m"
#define die(fmt, ...) \
do { \
fprintf(stderr, fmt ": %m\n", __VA_ARGS__); \
if (getpid() == parent_pid) { \
(void)kill(0, 9); \
exit(1); \
} \
_exit(1); \
} while (0)
#define READ_FD 0 /* pipe read fd */
#define WRITE_FD 1 /* pipe write fd */
#define CLASH_FD 3 /* force inherit fd clash */
#define MAX_FORKS 3 /* child, checkpoint, restore */
#define CRIU_BINARY "../../../criu/criu"
#define IMG_DIR "images"
#define DUMP_LOG_FILE "dump.log"
#define RESTORE_LOG_FILE "restore.log"
#define RESTORE_PID_FILE "restore.pid"
#define INHERIT_FD_OPTION "--inherit-fd"
#define OLD_LOG_FILE "/tmp/oldlog"
#define NEW_LOG_FILE "/tmp/newlog"
/*
* Command line options (see usage()).
*/
char *cli_flags = "hm:nv";
int max_msgs = 10;
int vflag;
int nflag;
char pid_number[8];
char inh_unixsk_opt[16];
char inh_unixsk_arg[64];
char external_sk_ino[32];
char *dump_argv[] = {
"criu", "dump", "-D", IMG_DIR, "-o", DUMP_LOG_FILE, "-v4", external_sk_ino, "-t", pid_number, NULL
};
char *restore_argv[] = { "criu", "restore", "-d", "-D", IMG_DIR, "-o", RESTORE_LOG_FILE,
"--pidfile", RESTORE_PID_FILE, "-v4", "-x", inh_unixsk_opt, inh_unixsk_arg, NULL };
int max_forks;
int parent_pid;
int child_pid;
int criu_dump_pid;
int criu_restore_pid;
/* prototypes */
void chld_handler(int signum);
int parent(int *socketfd, const char *ino_child_sk);
int child(int *socketfd, int dupfd, int newfd);
void checkpoint_child(int child_pid, int *old_socket_namefd);
void restore_child(int *new_socketfd, const char *old_socket_name);
void write_to_fd(int fd, char *name, int i, int newline);
void ls_proc_fd(int fd);
char *socket_name(int fd);
ino_t socket_inode(int fd);
char *who(pid_t pid);
void socketpair_safe(int socketfd[2]);
pid_t fork_safe(void);
void signal_safe(int signum, sighandler_t handler);
int open_safe(char *pathname, int flags);
void close_safe(int fd);
void write_safe(int fd, char *buf, int count);
int read_safe(int fd, char *buf, int count);
int dup_safe(int oldfd);
void move_fd(int oldfd, int newfd);
void mkdir_safe(char *dirname, int mode);
void unlink_safe(char *pathname);
void execv_safe(char *path, char *argv[], int ls);
pid_t waitpid_safe(pid_t pid, int *status, int options, int id);
void prctl_safe(int option, ulong arg2, ulong arg3, ulong arg4, ulong arg5);
int dup2_safe(int oldfd, int newfd);
void usage(char *cmd)
{
printf("Usage: %s [%s]\n", cmd, cli_flags);
printf("-h\tprint this help and exit\n");
printf("-m\tcount of send messages (by default 10 will send from child) \n");
printf("-n\tdo not use the %s option\n", INHERIT_FD_OPTION);
printf("-v\tverbose mode (list contents of /proc/<pid>/fd)\n");
}
int main(int argc, char *argv[])
{
int ret;
int opt;
int socketfd[2];
while ((opt = getopt(argc, argv, cli_flags)) != -1) {
switch (opt) {
case 'h':
usage(argv[0]);
return 0;
case 'm':
max_msgs = atoi(optarg);
break;
case 'n':
nflag++;
break;
case 'v':
vflag++;
break;
case '?':
if ('m' == optopt)
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
usage(argv[0]);
return 1;
}
}
setbuf(stdout, NULL);
setbuf(stderr, NULL);
mkdir_safe(IMG_DIR, 0700);
socketpair_safe(socketfd);
child_pid = fork_safe();
if (child_pid > 0) {
parent_pid = getpid();
signal_safe(SIGCHLD, chld_handler);
prctl_safe(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
snprintf(external_sk_ino, sizeof(external_sk_ino), "--ext-unix-sk=%u",
(unsigned int)socket_inode(socketfd[WRITE_FD]));
char unix_sk_ino[32] = { 0 };
strcpy(unix_sk_ino, socket_name(socketfd[WRITE_FD]));
close_safe(socketfd[WRITE_FD]);
ret = parent(socketfd, unix_sk_ino);
} else {
/* child */
int dupfd = -1;
int openfd = -1;
int logfd;
child_pid = getpid();
close_safe(socketfd[READ_FD]);
setsid();
logfd = open_safe(OLD_LOG_FILE, O_WRONLY | O_APPEND | O_CREAT);
dup2_safe(logfd, 1);
dup2_safe(logfd, 2);
close(logfd);
close(0);
ret = child(socketfd, dupfd, openfd);
}
return ret;
}
/*
* Parent reads message from its pipe with the child.
* After a couple of messages, it checkpoints the child
* which causes the child to exit. Parent then creates
* a new pipe and restores the child.
*/
int parent(int *socketfd, const char *ino_child_sk)
{
char buf[32];
int nread;
nread = 0;
while (max_forks <= MAX_FORKS) {
if (read_safe(socketfd[READ_FD], buf, sizeof buf) == 0)
continue;
nread++;
if (vflag && nread == 1)
ls_proc_fd(-1);
printf("%s read %s from %s\n", who(0), buf, socket_name(socketfd[READ_FD]));
if (nread == (max_msgs / 2)) {
checkpoint_child(child_pid, socketfd);
if (!nflag) {
close_safe(socketfd[READ_FD]);
/* create a new one */
printf("%s creating a new socket\n", who(0));
socketpair_safe(socketfd);
}
restore_child(socketfd, ino_child_sk);
}
}
return 0;
}
/*
* Child sends a total of max_messages messages to its
* parent, half before checkpoint and half after restore.
*/
int child(int *socketfd, int dupfd, int openfd)
{
int i;
int fd;
int num_wfds;
struct timespec req = { 1, 0 };
/*
* Count the number of pipe descriptors we'll be
* writing to. At least 1 (for socketfd[WRITE_FD])
* and at most 3.
*/
num_wfds = 1;
if (dupfd >= 0)
num_wfds++;
if (openfd >= 0)
num_wfds++;
for (i = 0; i < max_msgs; i++) {
/* print first time and after checkpoint */
if (vflag && (i == 0 || i == (max_msgs / 2)))
ls_proc_fd(-1);
switch (i % num_wfds) {
case 0:
fd = socketfd[WRITE_FD];
break;
case 1:
fd = openfd;
break;
case 2:
fd = openfd;
break;
}
write_to_fd(fd, socket_name(socketfd[WRITE_FD]), i + 1, 0);
/*
* Since sleep will be interrupted by C/R, make sure
* to sleep an entire second to minimize the chance of
* writing before criu restore has exited. If criu is
* still around and we write to a broken pipe, we'll be
* killed but SIGCHLD will be delivered to criu instead
* of parent.
*/
while (nanosleep(&req, NULL))
;
printf("\n");
}
return 0;
}
void chld_handler(int signum)
{
int status;
pid_t pid;
pid = waitpid_safe(-1, &status, WNOHANG, 1);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
if (pid == child_pid) {
printf("%s %s exited with status %d\n", who(0), who(pid), status);
/* if child exited successfully, we're done */
if (status == 0)
exit(0);
/* checkpoint kills the child */
if (status != 9)
exit(status);
}
}
void checkpoint_child(int child_pid, int *socketfd)
{
/* prepare -t <pid> */
snprintf(pid_number, sizeof pid_number, "%d", child_pid);
criu_dump_pid = fork_safe();
if (criu_dump_pid > 0) {
int status;
pid_t pid;
pid = waitpid_safe(criu_dump_pid, &status, 0, 2);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
printf("%s %s exited with status %d\n", who(0), who(pid), status);
if (status)
exit(status);
} else {
close(socketfd[READ_FD]);
criu_dump_pid = getpid();
execv_safe(CRIU_BINARY, dump_argv, 0);
}
}
void restore_child(int *new_socketfd, const char *old_sock_name)
{
char buf[64];
criu_restore_pid = fork_safe();
if (criu_restore_pid > 0) {
int status;
pid_t pid;
if (!nflag)
close_safe(new_socketfd[WRITE_FD]);
pid = waitpid_safe(criu_restore_pid, &status, 0, 3);
if (WIFEXITED(status))
status = WEXITSTATUS(status);
printf("%s %s exited with status %d\n", who(0), who(pid), status);
if (status)
exit(status);
} else {
criu_restore_pid = getpid();
if (!nflag) {
close_safe(new_socketfd[READ_FD]);
move_fd(new_socketfd[WRITE_FD], CLASH_FD);
/* --inherit-fd fd[CLASH_FD]:socket[xxxxxx] */
snprintf(inh_unixsk_opt, sizeof inh_unixsk_opt, "%s", INHERIT_FD_OPTION);
snprintf(inh_unixsk_arg, sizeof inh_unixsk_arg, "fd[%d]:%s", CLASH_FD, old_sock_name);
restore_argv[11] = inh_unixsk_opt;
restore_argv[13] = NULL;
} else
restore_argv[11] = NULL;
snprintf(buf, sizeof buf, "%s/%s", IMG_DIR, RESTORE_PID_FILE);
unlink_safe(buf);
execv_safe(CRIU_BINARY, restore_argv, 1);
}
}
void write_to_fd(int fd, char *name, int i, int newline)
{
int n;
char buf[16]; /* fit "hello d\n" for small d */
n = snprintf(buf, sizeof buf, "hello %d", i);
printf("%s writing %s to %s via fd %d\n", who(0), buf, name, fd);
if (newline) {
buf[n++] = '\n';
buf[n] = '\0';
}
write_safe(fd, buf, strlen(buf));
}
void ls_proc_fd(int fd)
{
char cmd[128];
if (fd == -1)
snprintf(cmd, sizeof cmd, "ls -l /proc/%d/fd", getpid());
else
snprintf(cmd, sizeof cmd, "ls -l /proc/%d/fd/%d", getpid(), fd);
printf("%s %s\n", who(0), cmd);
system(cmd);
}
char *socket_name(int fd)
{
static char sock_name[64];
char path[64];
snprintf(path, sizeof path, "/proc/self/fd/%d", fd);
if (readlink(path, sock_name, sizeof sock_name) == -1)
die("readlink: path=%s", path);
return sock_name;
}
ino_t socket_inode(int fd)
{
struct stat sbuf;
if (fstat(fd, &sbuf) == -1)
die("fstat: fd=%i", fd);
return sbuf.st_ino;
}
/*
* Use two buffers to support two calls to
* this function in a printf argument list.
*/
char *who(pid_t pid)
{
static char pidstr1[64];
static char pidstr2[64];
static char *cp;
char *np;
char *ep;
int p;
p = pid ? pid : getpid();
if (p == parent_pid) {
np = "parent";
ep = CS_PARENT;
} else if (p == child_pid) {
np = "child";
ep = CS_CHILD;
} else if (p == criu_dump_pid) {
np = "dump";
ep = CS_DUMP;
} else if (p == criu_restore_pid) {
np = "restore";
ep = CS_RESTORE;
} else
np = "???";
cp = (cp == pidstr1) ? pidstr2 : pidstr1;
snprintf(cp, sizeof pidstr1, "%s[%s %d]", pid ? "" : ep, np, p);
return cp;
}
void socketpair_safe(int socketfd[2])
{
if (socketpair(AF_UNIX, SOCK_STREAM, 0, socketfd) == -1)
die("socketpair %p", socketfd);
}
pid_t fork_safe(void)
{
pid_t pid;
if ((pid = fork()) == -1)
die("fork: pid=%d", pid);
max_forks++;
return pid;
}
void signal_safe(int signum, sighandler_t handler)
{
if (signal(signum, handler) == SIG_ERR)
die("signal: signum=%d", signum);
}
int open_safe(char *pathname, int flags)
{
int fd;
if ((fd = open(pathname, flags, 0777)) == -1)
die("open: pathname=%s", pathname);
return fd;
}
void close_safe(int fd)
{
if (close(fd) == -1)
die("close: fd=%d", fd);
}
void write_safe(int fd, char *buf, int count)
{
if (write(fd, buf, count) != count) {
die("write: fd=%d buf=\"%s\" count=%d errno=%d", fd, buf, count, errno);
}
}
int read_safe(int fd, char *buf, int count)
{
int n;
if ((n = read(fd, buf, count)) < 0)
die("read: fd=%d count=%d", fd, count);
buf[n] = '\0';
return n;
}
int dup_safe(int oldfd)
{
int newfd;
if ((newfd = dup(oldfd)) == -1)
die("dup: oldfd=%d", oldfd);
return newfd;
}
int dup2_safe(int oldfd, int newfd)
{
if (dup2(oldfd, newfd) != newfd)
die("dup2: oldfd=%d newfd=%d", oldfd, newfd);
return newfd;
}
void move_fd(int oldfd, int newfd)
{
if (oldfd != newfd) {
dup2_safe(oldfd, newfd);
close_safe(oldfd);
}
}
void mkdir_safe(char *dirname, int mode)
{
if (mkdir(dirname, mode) == -1 && errno != EEXIST)
die("mkdir dirname=%s mode=0x%x\n", dirname, mode);
}
void unlink_safe(char *pathname)
{
if (unlink(pathname) == -1 && errno != ENOENT) {
die("unlink: pathname=%s\n", pathname);
}
}
void execv_safe(char *path, char *argv[], int ls)
{
int i;
struct timespec req = { 0, 1000000 };
printf("\n%s ", who(0));
for (i = 0; argv[i] != NULL; i++)
printf("%s ", argv[i]);
printf("\n");
/* give parent a chance to wait for us */
while (nanosleep(&req, NULL))
;
if (vflag && ls)
ls_proc_fd(-1);
execv(path, argv);
die("execv: path=%s", path);
}
pid_t waitpid_safe(pid_t pid, int *status, int options, int id)
{
pid_t p;
p = waitpid(pid, status, options);
if (p == -1)
fprintf(stderr, "waitpid pid=%d id=%d %m\n", pid, id);
return p;
}
void prctl_safe(int option, ulong arg2, ulong arg3, ulong arg4, ulong arg5)
{
if (prctl(option, arg2, arg3, arg4, arg5) == -1)
die("prctl: option=0x%x", option);
}
| 13,128 | 21.481164 | 104 |
c
|
criu
|
criu-master/test/zdtm/lib/bpfmap_zdtm.c
|
#include "bpfmap_zdtm.h"
int parse_bpfmap_fdinfo(int fd, struct bpfmap_fdinfo_obj *obj, uint32_t expected_to_meet)
{
uint32_t met = 0;
char str[512];
FILE *f;
sprintf(str, "/proc/self/fdinfo/%d", fd);
f = fopen(str, "r");
if (!f) {
pr_perror("Can't open fdinfo to parse");
return -1;
}
while (fgets(str, sizeof(str), f)) {
if (fdinfo_field(str, "map_type")) {
if (sscanf(str, "map_type: %u", &obj->map_type) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "key_size")) {
if (sscanf(str, "key_size: %u", &obj->key_size) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "value_size")) {
if (sscanf(str, "value_size: %u", &obj->value_size) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "max_entries")) {
if (sscanf(str, "max_entries: %u", &obj->max_entries) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "map_flags")) {
if (sscanf(str, "map_flags: %" PRIx32 "", &obj->map_flags) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "memlock")) {
if (sscanf(str, "memlock: %" PRIu64 "", &obj->memlock) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "map_id")) {
if (sscanf(str, "map_id: %u", &obj->map_id) != 1)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "frozen")) {
if (sscanf(str, "frozen: %d", &obj->frozen) != 1)
goto parse_err;
met++;
continue;
}
}
if (expected_to_meet != met) {
pr_err("Expected to meet %d entries but got %d\n", expected_to_meet, met);
return -1;
}
fclose(f);
return 0;
parse_err:
pr_perror("Can't parse '%s'", str);
fclose(f);
return -1;
}
int cmp_bpf_map_info(struct bpf_map_info *old, struct bpf_map_info *new)
{
/*
* We skip the check for old->id and new->id because every time a new BPF
* map is created, it is internally allocated a new map id. Therefore,
* the new BPF map created by CRIU (during restore) will have a different
* map id than the old one
*/
if ((old->type != new->type) || (old->key_size != new->key_size) || (old->value_size != new->value_size) ||
(old->max_entries != new->max_entries) || (old->map_flags != new->map_flags) ||
(old->ifindex != new->ifindex) || (old->netns_dev != new->netns_dev) ||
(old->netns_ino != new->netns_ino) || (old->btf_id != new->btf_id) ||
(old->btf_key_type_id != new->btf_key_type_id) || (old->btf_value_type_id != new->btf_value_type_id))
return -1;
if (strcmp(old->name, new->name) != 0)
return -1;
return 0;
}
int cmp_bpfmap_fdinfo(struct bpfmap_fdinfo_obj *old, struct bpfmap_fdinfo_obj *new)
{
/*
* We skip the check for old->map_id and new->map_id because every time a
* new BPF map is created, it is internally allocated a new map id. Therefore,
* the new BPF map created by CRIU (during restore) will have a different map
* id than the old one
*/
if ((old->map_type != new->map_type) || (old->key_size != new->key_size) ||
(old->value_size != new->value_size) || (old->max_entries != new->max_entries) ||
(old->map_flags != new->map_flags) || (old->memlock != new->memlock) || (old->frozen != new->frozen))
return -1;
return 0;
}
| 3,252 | 26.803419 | 108 |
c
|
criu
|
criu-master/test/zdtm/lib/bpfmap_zdtm.h
|
#include <bpf/bpf.h>
#include <inttypes.h>
#include "zdtmtst.h"
#define fdinfo_field(str, field) !strncmp(str, field ":", sizeof(field))
struct bpfmap_fdinfo_obj {
uint32_t map_type;
uint32_t key_size;
uint32_t value_size;
uint32_t max_entries;
uint32_t map_flags;
uint64_t memlock;
uint32_t map_id;
uint32_t frozen;
};
extern int parse_bpfmap_fdinfo(int, struct bpfmap_fdinfo_obj *, uint32_t);
extern int cmp_bpf_map_info(struct bpf_map_info *, struct bpf_map_info *);
extern int cmp_bpfmap_fdinfo(struct bpfmap_fdinfo_obj *, struct bpfmap_fdinfo_obj *);
| 567 | 26.047619 | 85 |
h
|
criu
|
criu-master/test/zdtm/lib/cpuid.h
|
#ifndef ZDTM_CPUID_H__
#define ZDTM_CPUID_H__
/*
* Adopted from linux kernel code.
*/
static inline void native_cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx)
{
/* ecx is often an input as well as an output. */
asm volatile("cpuid" : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx) : "0"(*eax), "2"(*ecx) : "memory");
}
static inline void cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx)
{
*eax = op;
*ecx = 0;
native_cpuid(eax, ebx, ecx, edx);
}
static inline void cpuid_count(unsigned int op, unsigned int count, unsigned int *eax, unsigned int *ebx,
unsigned int *ecx, unsigned int *edx)
{
*eax = op;
*ecx = count;
native_cpuid(eax, ebx, ecx, edx);
}
#endif /* ZDTM_CPUID_H__ */
| 791 | 25.4 | 117 |
h
|
criu
|
criu-master/test/zdtm/lib/fs.h
|
#ifndef ZDTM_FS_H_
#define ZDTM_FS_H_
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
#endif
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <limits.h>
#define KDEV_MINORBITS 20
#define KDEV_MINORMASK ((1UL << KDEV_MINORBITS) - 1)
#define MKKDEV(ma, mi) (((ma) << KDEV_MINORBITS) | (mi))
static inline unsigned int kdev_major(unsigned int kdev)
{
return kdev >> KDEV_MINORBITS;
}
static inline unsigned int kdev_minor(unsigned int kdev)
{
return kdev & KDEV_MINORMASK;
}
static inline dev_t kdev_to_odev(unsigned int kdev)
{
/*
* New kernels encode devices in a new form.
* See kernel's fs/stat.c for details, there
* choose_32_64 helpers which are the key.
*/
unsigned major = kdev_major(kdev);
unsigned minor = kdev_minor(kdev);
return makedev(major, minor);
}
typedef struct {
int mnt_id;
int parent_mnt_id;
unsigned int s_dev;
char root[PATH_MAX];
char mountpoint[PATH_MAX];
char fsname[64];
} mnt_info_t;
extern mnt_info_t *mnt_info_alloc(void);
extern void mnt_info_free(mnt_info_t **m);
extern mnt_info_t *get_cwd_mnt_info(void);
/*
* get_cwd_check_perm is called to check that cwd is actually usable for a calling
* process.
*
* Example output of a stat command on a '/root' path shows file access bits:
* > stat /root
* File: ‘/root’
* ...
* Access: (0550/dr-xr-x---) Uid: ( 0/root) Gid: ( 0/root)
* ^- no 'x' bit for other
*
* Here we can see that '/root' dir (that often can be part of cwd path) does not
* allow non-root user and non-root group to list contents of this directory.
* Calling process matching 'other' access category may succeed getting cwd path, but will
* fail performing further filesystem operations based on this path with confusing errors.
*
* This function calls get_current_dir_name and explicitly checks that bit 'x' is enabled for
* a calling process and logs the error.
*
* If check passes, stores get_current_dir's result in *result and returns 0
* If check fails, stores 0 in *result and returns -1
*/
extern int get_cwd_check_perm(char **result);
#endif /* ZDTM_FS_H_ */
| 2,101 | 25.948718 | 93 |
h
|
criu
|
criu-master/test/zdtm/lib/list.h
|
#ifndef __ZDTM_LIST_H__
#define __ZDTM_LIST_H__
/*
* Double linked lists.
*/
#include <stddef.h>
#include "zdtmtst.h"
#define POISON_POINTER_DELTA 0
#define LIST_POISON1 ((void *)0x00100100 + POISON_POINTER_DELTA)
#define LIST_POISON2 ((void *)0x00200200 + POISON_POINTER_DELTA)
struct list_head {
struct list_head *prev, *next;
};
#define LIST_HEAD_INIT(name) \
{ \
&(name), &(name) \
}
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
next->prev = prev;
prev->next = next;
}
static inline void __list_del_entry(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
}
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
static inline void list_replace(struct list_head *old, struct list_head *new)
{
new->next = old->next;
new->next->prev = new;
new->prev = old->prev;
new->prev->next = new;
}
static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
list_replace(old, new);
INIT_LIST_HEAD(old);
}
static inline void list_del_init(struct list_head *entry)
{
__list_del_entry(entry);
INIT_LIST_HEAD(entry);
}
static inline void list_move(struct list_head *list, struct list_head *head)
{
__list_del_entry(list);
list_add(list, head);
}
static inline void list_move_tail(struct list_head *list, struct list_head *head)
{
__list_del_entry(list);
list_add_tail(list, head);
}
static inline int list_is_last(const struct list_head *list, const struct list_head *head)
{
return list->next == head;
}
static inline int list_is_first(const struct list_head *list, const struct list_head *head)
{
return list->prev == head;
}
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}
static inline int list_empty_careful(const struct list_head *head)
{
struct list_head *next = head->next;
return (next == head) && (next == head->prev);
}
static inline void list_rotate_left(struct list_head *head)
{
struct list_head *first;
if (!list_empty(head)) {
first = head->next;
list_move_tail(first, head);
}
}
static inline int list_is_singular(const struct list_head *head)
{
return !list_empty(head) && (head->next == head->prev);
}
static inline void __list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
struct list_head *new_first = entry->next;
list->next = head->next;
list->next->prev = list;
list->prev = entry;
entry->next = list;
head->next = new_first;
new_first->prev = head;
}
static inline void list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
if (list_empty(head))
return;
if (list_is_singular(head) && (head->next != entry && head != entry))
return;
if (entry == head)
INIT_LIST_HEAD(list);
else
__list_cut_position(list, head, entry);
}
static inline void __list_splice(const struct list_head *list, struct list_head *prev, struct list_head *next)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
first->prev = prev;
prev->next = first;
last->next = next;
next->prev = last;
}
static inline void list_splice(const struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head, head->next);
}
static inline void list_splice_tail(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head->prev, head);
}
static inline void list_splice_init(struct list_head *list, struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head, head->next);
INIT_LIST_HEAD(list);
}
}
static inline void list_splice_tail_init(struct list_head *list, struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head->prev, head);
INIT_LIST_HEAD(list);
}
}
#define list_entry(ptr, type, member) container_of(ptr, type, member)
#define list_first_entry(ptr, type, member) list_entry((ptr)->next, type, member)
#define list_for_each(pos, head) for (pos = (head)->next; pos != (head); pos = pos->next)
#define list_for_each_prev(pos, head) for (pos = (head)->prev; pos != (head); pos = pos->prev)
#define list_for_each_safe(pos, n, head) for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
#define list_for_each_prev_safe(pos, n, head) \
for (pos = (head)->prev, n = pos->prev; pos != (head); pos = n, n = pos->prev)
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_reverse(pos, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
#define list_prepare_entry(pos, head, member) ((pos) ?: list_entry(head, typeof(*pos), member))
#define list_for_each_entry_continue(pos, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_continue_reverse(pos, head, member) \
for (pos = list_entry(pos->member.prev, typeof(*pos), member); &pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))
#define list_for_each_entry_from(pos, head, member) \
for (; &pos->member != (head); pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_continue(pos, n, head, member) \
for (pos = list_entry(pos->member.next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_from(pos, n, head, member) \
for (n = list_entry(pos->member.next, typeof(*pos), member); &pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_reverse(pos, n, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member), \
n = list_entry(pos->member.prev, typeof(*pos), member); \
&pos->member != (head); pos = n, n = list_entry(n->member.prev, typeof(*n), member))
#define list_safe_reset_next(pos, n, member) n = list_entry(pos->member.next, typeof(*pos), member)
/*
* Double linked lists with a single pointer list head.
*/
struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next, **pprev;
};
#define HLIST_HEAD_INIT \
{ \
.first = NULL \
}
#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL }
#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
static inline void INIT_HLIST_NODE(struct hlist_node *h)
{
h->next = NULL;
h->pprev = NULL;
}
static inline int hlist_unhashed(const struct hlist_node *h)
{
return !h->pprev;
}
static inline int hlist_empty(const struct hlist_head *h)
{
return !h->first;
}
static inline void __hlist_del(struct hlist_node *n)
{
struct hlist_node *next = n->next;
struct hlist_node **pprev = n->pprev;
*pprev = next;
if (next)
next->pprev = pprev;
}
static inline void hlist_del(struct hlist_node *n)
{
__hlist_del(n);
n->next = LIST_POISON1;
n->pprev = LIST_POISON2;
}
static inline void hlist_del_init(struct hlist_node *n)
{
if (!hlist_unhashed(n)) {
__hlist_del(n);
INIT_HLIST_NODE(n);
}
}
static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
struct hlist_node *first = h->first;
n->next = first;
if (first)
first->pprev = &n->next;
h->first = n;
n->pprev = &h->first;
}
/* next must be != NULL */
static inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next)
{
n->pprev = next->pprev;
n->next = next;
next->pprev = &n->next;
*(n->pprev) = n;
}
static inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next)
{
next->next = n->next;
n->next = next;
next->pprev = &n->next;
if (next->next)
next->next->pprev = &next->next;
}
/* after that we'll appear to be on some hlist and hlist_del will work */
static inline void hlist_add_fake(struct hlist_node *n)
{
n->pprev = &n->next;
}
/*
* Move a list from one list head to another. Fixup the pprev
* reference of the first entry if it exists.
*/
static inline void hlist_move_list(struct hlist_head *old, struct hlist_head *new)
{
new->first = old->first;
if (new->first)
new->first->pprev = &new->first;
old->first = NULL;
}
#define hlist_entry(ptr, type, member) container_of(ptr, type, member)
#define hlist_for_each(pos, head) for (pos = (head)->first; pos; pos = pos->next)
#define hlist_for_each_safe(pos, n, head) \
for (pos = (head)->first; pos && ({ \
n = pos->next; \
1; \
}); \
pos = n)
#define hlist_entry_safe(ptr, type, member) (ptr) ? hlist_entry(ptr, type, member) : NULL
#define hlist_for_each_entry(pos, head, member) \
for (pos = hlist_entry_safe((head)->first, typeof(*(pos)), member); pos; \
pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_continue(pos, member) \
for (pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member); pos; \
pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_from(pos, member) \
for (; pos; pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
#define hlist_for_each_entry_safe(pos, n, head, member) \
for (pos = hlist_entry_safe((head)->first, typeof(*pos), member); pos && ({ \
n = pos->member.next; \
1; \
}); \
pos = hlist_entry_safe(n, typeof(*pos), member))
#endif /* __ZDTM_LIST_H__ */
| 11,164 | 27.628205 | 119 |
h
|
criu
|
criu-master/test/zdtm/lib/lock.h
|
#ifndef CR_LOCK_H_
#define CR_LOCK_H_
#include <stdint.h>
#include <linux/futex.h>
#include <linux/unistd.h>
#include <sys/time.h>
#include <limits.h>
#include <errno.h>
#include "asm/atomic.h"
#define BUG_ON(condition) \
do { \
if ((condition)) { \
raise(SIGABRT); \
*(volatile unsigned long *)NULL = 0xdead0000 + __LINE__; \
} \
} while (0)
typedef struct {
uint32_t raw;
} futex_t;
#define FUTEX_ABORT_FLAG (0x80000000)
#define FUTEX_ABORT_RAW (-1U)
static inline int sys_futex(uint32_t *uaddr, int op, uint32_t val, const struct timespec *timeout, uint32_t *uaddr2,
uint32_t val3)
{
return syscall(__NR_futex, uaddr, op, val, timeout, uaddr2, val3);
}
/* Get current futex @f value */
static inline uint32_t futex_get(futex_t *f)
{
return atomic_get(&f->raw);
}
/* Set futex @f value to @v */
static inline void futex_set(futex_t *f, uint32_t v)
{
atomic_set(&f->raw, v);
}
/* Set futex @f to @v and wake up all waiters */
static inline void futex_add_and_wake(futex_t *f, uint32_t v)
{
atomic_add(v, &f->raw);
BUG_ON(sys_futex(&f->raw, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
#define futex_init(f) futex_set(f, 0)
/* Wait on futex @__f value @__v become in condition @__c */
#define futex_wait_if_cond(__f, __v, __cond) \
do { \
int ret; \
uint32_t tmp; \
\
while (1) { \
tmp = (__f)->raw; \
if ((tmp & FUTEX_ABORT_FLAG) || (tmp __cond(__v))) \
break; \
ret = sys_futex(&(__f)->raw, FUTEX_WAIT, tmp, NULL, NULL, 0); \
if (ret < 0 && (errno == EAGAIN || errno == EINTR)) \
continue; \
BUG_ON(ret < 0 && errno != EWOULDBLOCK); \
} \
} while (0)
/* Set futex @f to @v and wake up all waiters */
static inline void futex_set_and_wake(futex_t *f, uint32_t v)
{
atomic_set(&f->raw, v);
BUG_ON(sys_futex(&f->raw, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Mark futex @f as wait abort needed and wake up all waiters */
static inline void futex_abort_and_wake(futex_t *f)
{
futex_set_and_wake(f, FUTEX_ABORT_RAW);
}
/* Decrement futex @f value and wake up all waiters */
static inline void futex_dec_and_wake(futex_t *f)
{
atomic_dec(&f->raw);
BUG_ON(sys_futex(&f->raw, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Increment futex @f value and wake up all waiters */
static inline void futex_inc_and_wake(futex_t *f)
{
atomic_inc(&f->raw);
BUG_ON(sys_futex(&f->raw, FUTEX_WAKE, INT_MAX, NULL, NULL, 0) < 0);
}
/* Plain increment futex @f value */
static inline void futex_inc(futex_t *f)
{
atomic_inc(&f->raw);
}
/* Plain decrement futex @f value */
static inline void futex_dec(futex_t *f)
{
atomic_dec(&f->raw);
}
/* Wait until futex @f value become @v */
static inline void futex_wait_until(futex_t *f, uint32_t v)
{
futex_wait_if_cond(f, v, ==);
}
/* Wait while futex @f value is greater than @v */
static inline void futex_wait_while_gt(futex_t *f, uint32_t v)
{
futex_wait_if_cond(f, v, <=);
}
/* Wait while futex @f value is less than @v */
static inline void futex_wait_while_lt(futex_t *f, uint32_t v)
{
futex_wait_if_cond(f, v, >=);
}
/* Wait while futex @f value is @v */
static inline uint32_t futex_wait_while(futex_t *f, uint32_t v)
{
while (f->raw == v) {
int ret = sys_futex(&f->raw, FUTEX_WAIT, v, NULL, NULL, 0);
if (ret < 0 && (errno == EAGAIN || errno == EINTR))
continue;
BUG_ON(ret < 0 && errno != EWOULDBLOCK);
}
return f->raw;
}
typedef struct {
uint32_t raw;
} mutex_t;
static void inline mutex_init(mutex_t *m)
{
uint32_t c = 0;
atomic_set(&m->raw, c);
}
static void inline mutex_lock(mutex_t *m)
{
uint32_t c;
int ret;
while ((c = atomic_inc(&m->raw)) != 0) {
ret = sys_futex(&m->raw, FUTEX_WAIT, c + 1, NULL, NULL, 0);
if (ret < 0)
pr_perror("futex");
BUG_ON(ret < 0 && errno != EWOULDBLOCK);
}
}
static void inline mutex_unlock(mutex_t *m)
{
uint32_t c = 0;
atomic_set(&m->raw, c);
BUG_ON(sys_futex(&m->raw, FUTEX_WAKE, 1, NULL, NULL, 0) < 0);
}
#endif /* CR_LOCK_H_ */
| 4,825 | 27.388235 | 116 |
h
|
criu
|
criu-master/test/zdtm/lib/mountinfo.c
|
#include <stdio.h>
#include <string.h>
#include "mountinfo.h"
#include "fs.h"
#include "xmalloc.h"
/*
* mountinfo contains mangled paths. space, tab and back slash were replaced
* with usual octal escape. This function replaces these symbols back.
*/
static void cure_path(char *path)
{
int i, len, off = 0;
if (strchr(path, '\\') == NULL) /* fast path */
return;
len = strlen(path);
for (i = 0; i < len; i++) {
if (!strncmp(path + i, "\\040", 4)) {
path[i - off] = ' ';
goto replace;
} else if (!strncmp(path + i, "\\011", 4)) {
path[i - off] = '\t';
goto replace;
} else if (!strncmp(path + i, "\\134", 4)) {
path[i - off] = '\\';
goto replace;
}
if (off)
path[i - off] = path[i];
continue;
replace:
off += 3;
i += 3;
}
path[len - off] = 0;
}
static struct mountinfo_zdtm *mountinfo_zdtm_alloc(struct mntns_zdtm *mntns)
{
struct mountinfo_zdtm *new;
new = xzalloc(sizeof(struct mountinfo_zdtm));
if (new)
list_add_tail(&new->list, &mntns->mountinfo_list);
return new;
}
static void mountinfo_zdtm_free(struct mountinfo_zdtm *mountinfo)
{
list_del(&mountinfo->list);
xfree(mountinfo->mountpoint);
xfree(mountinfo->root);
xfree(mountinfo->fstype);
xfree(mountinfo);
}
static void mountinfo_zdtm_free_all(struct mntns_zdtm *mntns)
{
struct mountinfo_zdtm *mountinfo, *tmp;
list_for_each_entry_safe(mountinfo, tmp, &mntns->mountinfo_list, list)
mountinfo_zdtm_free(mountinfo);
}
#define BUF_SIZE 4096
char buf[BUF_SIZE];
int mntns_parse_mountinfo(struct mntns_zdtm *mntns)
{
FILE *f;
int ret;
INIT_LIST_HEAD(&mntns->mountinfo_list);
f = fopen("/proc/self/mountinfo", "r");
if (!f) {
pr_perror("Failed to open mountinfo");
return -1;
}
while (fgets(buf, BUF_SIZE, f)) {
struct mountinfo_zdtm *new;
unsigned int kmaj, kmin;
char *str, *hyphen, *shared, *master;
int n;
new = mountinfo_zdtm_alloc(mntns);
if (!new) {
pr_perror("Failed to alloc mountinfo_zdtm");
goto free;
}
ret = sscanf(buf, "%i %i %u:%u %ms %ms %*s %n", &new->mnt_id, &new->parent_mnt_id, &kmaj, &kmin,
&new->root, &new->mountpoint, &n);
if (ret != 6) {
pr_perror("Failed to parse mountinfo line \"%s\"", buf);
goto free;
}
cure_path(new->root);
cure_path(new->mountpoint);
new->s_dev = MKKDEV(kmaj, kmin);
str = buf + n;
hyphen = strstr(buf, " - ");
if (!hyphen) {
pr_perror("Failed to find \" - \" in mountinfo line \"%s\"", buf);
goto free;
}
*hyphen++ = '\0';
shared = strstr(str, "shared:");
if (shared)
new->shared_id = atoi(shared + 7);
master = strstr(str, "master:");
if (master)
new->master_id = atoi(master + 7);
ret = sscanf(hyphen, "- %ms", &new->fstype);
if (ret != 1) {
pr_perror("Failed to parse fstype in mountinfo tail \"%s\"", hyphen);
goto free;
}
}
fclose(f);
return 0;
free:
mountinfo_zdtm_free_all(mntns);
fclose(f);
return -1;
}
static struct mountinfo_topology *mountinfo_topology_alloc(struct mntns_zdtm *mntns, struct mountinfo_zdtm *mountinfo)
{
struct mountinfo_topology *new;
new = xzalloc(sizeof(struct mountinfo_topology));
if (new) {
new->mountinfo = mountinfo;
new->topology_id = -1;
INIT_LIST_HEAD(&new->children);
INIT_LIST_HEAD(&new->siblings);
list_add_tail(&new->list, &mntns->topology_list);
INIT_LIST_HEAD(&new->sharing_list);
}
return new;
}
static void mountinfo_topology_free(struct mountinfo_topology *topology)
{
list_del(&topology->list);
xfree(topology);
}
static void mountinfo_topology_free_all(struct mntns_zdtm *mntns)
{
struct mountinfo_topology *topology, *tmp;
list_for_each_entry_safe(topology, tmp, &mntns->topology_list, list)
mountinfo_topology_free(topology);
}
static struct mountinfo_topology *mountinfo_topology_lookup_parent(struct mntns_zdtm *mntns,
struct mountinfo_topology *topology)
{
struct mountinfo_topology *parent;
list_for_each_entry(parent, &mntns->topology_list, list) {
if (parent->mountinfo->mnt_id == topology->mountinfo->parent_mnt_id)
return parent;
}
return NULL;
}
static struct mountinfo_topology *mt_subtree_next(struct mountinfo_topology *mt, struct mountinfo_topology *root)
{
if (!list_empty(&mt->children))
return list_entry(mt->children.next, struct mountinfo_topology, siblings);
while (mt->parent && mt != root) {
if (mt->siblings.next == &mt->parent->children)
mt = mt->parent;
else
return list_entry(mt->siblings.next, struct mountinfo_topology, siblings);
}
return NULL;
}
static void __mt_resort_siblings(struct mountinfo_topology *parent)
{
LIST_HEAD(list);
while (!list_empty(&parent->children)) {
struct mountinfo_topology *m, *p;
m = list_first_entry(&parent->children, struct mountinfo_topology, siblings);
list_del(&m->siblings);
list_for_each_entry(p, &list, siblings)
if (strcmp(p->mountinfo->mountpoint, m->mountinfo->mountpoint) < 0)
break;
list_add_tail(&m->siblings, &p->siblings);
}
list_splice(&list, &parent->children);
}
static void mntns_mt_resort_siblings(struct mntns_zdtm *mntns)
{
struct mountinfo_topology *mt = mntns->tree;
LIST_HEAD(mtlist);
int i = 0;
while (1) {
/* Assign topology id to mt in dfs order */
mt->topology_id = i++;
list_move_tail(&mt->list, &mtlist);
__mt_resort_siblings(mt);
mt = mt_subtree_next(mt, mntns->tree);
if (!mt)
break;
}
/* Update mntns->topology_list in dfs order */
list_splice(&mtlist, &mntns->topology_list);
}
static struct sharing_group *sharing_group_find_or_alloc(struct mntns_zdtm *mntns, int shared_id, int master_id,
unsigned int s_dev)
{
struct sharing_group *sg;
list_for_each_entry(sg, &mntns->sharing_groups_list, list) {
if ((sg->shared_id == shared_id) && (sg->master_id == master_id)) {
if (sg->s_dev != s_dev) {
pr_err("Sharing/devid inconsistency\n");
return NULL;
}
return sg;
}
}
sg = xzalloc(sizeof(struct sharing_group));
if (!sg)
return NULL;
sg->shared_id = shared_id;
sg->master_id = master_id;
sg->s_dev = s_dev;
sg->topology_id = -1;
INIT_LIST_HEAD(&sg->children);
INIT_LIST_HEAD(&sg->siblings);
INIT_LIST_HEAD(&sg->mounts_list);
list_add_tail(&sg->list, &mntns->sharing_groups_list);
return sg;
}
static void sharing_group_free(struct sharing_group *sg)
{
list_del(&sg->list);
xfree(sg);
}
static void sharing_group_free_all(struct mntns_zdtm *mntns)
{
struct sharing_group *sg, *tmp;
list_for_each_entry_safe(sg, tmp, &mntns->sharing_groups_list, list)
sharing_group_free(sg);
}
static struct sharing_group *sharing_group_lookup_parent(struct mntns_zdtm *mntns, struct sharing_group *sg)
{
struct sharing_group *parent;
list_for_each_entry(parent, &mntns->sharing_groups_list, list) {
if (parent->shared_id == sg->master_id)
return parent;
}
/* Create "external" sharing */
parent = sharing_group_find_or_alloc(mntns, sg->master_id, 0, sg->s_dev);
if (parent)
return parent;
return NULL;
}
static int mntns_build_tree(struct mntns_zdtm *mntns)
{
struct mountinfo_topology *topology, *parent, *tree = NULL;
struct mountinfo_zdtm *mountinfo;
struct sharing_group *sg, *sg_parent;
INIT_LIST_HEAD(&mntns->topology_list);
/* Prealloc mount tree */
list_for_each_entry(mountinfo, &mntns->mountinfo_list, list) {
topology = mountinfo_topology_alloc(mntns, mountinfo);
if (!topology)
goto err;
}
/* Build mount tree */
list_for_each_entry(topology, &mntns->topology_list, list) {
parent = mountinfo_topology_lookup_parent(mntns, topology);
if (!parent) {
if (tree) {
pr_err("Bad mount tree with too roots %d and %d\n", tree->mountinfo->mnt_id,
parent->mountinfo->mnt_id);
goto err;
}
tree = topology;
} else {
topology->parent = parent;
list_add_tail(&topology->siblings, &parent->children);
}
}
mntns->tree = tree;
/* Sort mounts by mountpoint */
mntns_mt_resort_siblings(mntns);
INIT_LIST_HEAD(&mntns->sharing_groups_list);
/* Prealloc sharing groups */
list_for_each_entry(topology, &mntns->topology_list, list) {
if (!topology->mountinfo->shared_id && !topology->mountinfo->master_id)
continue;
/*
* Due to mntns->topology_list is sorted in dfs order
* sharing groups are also sorted the same
*/
sg = sharing_group_find_or_alloc(mntns, topology->mountinfo->shared_id, topology->mountinfo->master_id,
topology->mountinfo->s_dev);
if (!sg)
goto err;
list_add_tail(&topology->sharing_list, &sg->mounts_list);
topology->sharing = sg;
/* Set sharing group topology id to minimal topology id of it's mounts */
if (sg->topology_id == -1 || topology->topology_id < sg->topology_id)
sg->topology_id = topology->topology_id;
}
/* Build sharing group trees */
list_for_each_entry(sg, &mntns->sharing_groups_list, list) {
if (sg->master_id) {
sg_parent = sharing_group_lookup_parent(mntns, sg);
sg->parent = sg_parent;
list_add(&sg->siblings, &sg_parent->children);
}
}
return 0;
err:
mountinfo_topology_free_all(mntns);
sharing_group_free_all(mntns);
return -1;
}
static int mountinfo_topology_list_compare(struct mntns_zdtm *mntns_a, struct mntns_zdtm *mntns_b)
{
struct mountinfo_topology *topology_a, *topology_b;
topology_a = list_first_entry(&mntns_a->topology_list, struct mountinfo_topology, list);
topology_b = list_first_entry(&mntns_b->topology_list, struct mountinfo_topology, list);
while (&topology_a->list != &mntns_a->topology_list && &topology_b->list != &mntns_b->topology_list) {
if (topology_a->topology_id != topology_b->topology_id) {
pr_err("Mounts %d and %d have different topology id %d and %d\n", topology_a->mountinfo->mnt_id,
topology_b->mountinfo->mnt_id, topology_a->topology_id, topology_b->topology_id);
return -1;
}
if (topology_a->parent && topology_b->parent) {
if (topology_a->parent->topology_id != topology_b->parent->topology_id) {
pr_err("Mounts %d and %d have different parent topology id %d and %d\n",
topology_a->mountinfo->mnt_id, topology_b->mountinfo->mnt_id,
topology_a->parent->topology_id, topology_b->parent->topology_id);
return -1;
}
} else if (topology_a->parent || topology_b->parent) {
pr_err("One of mounts %d and %d has parent and other doesn't\n", topology_a->mountinfo->mnt_id,
topology_b->mountinfo->mnt_id);
return -1;
}
if (topology_a->sharing && topology_b->sharing) {
if (topology_a->sharing->topology_id != topology_b->sharing->topology_id) {
pr_err("Mounts %d and %d have different sharing topology id %d and %d\n",
topology_a->mountinfo->mnt_id, topology_b->mountinfo->mnt_id,
topology_a->sharing->topology_id, topology_b->sharing->topology_id);
return -1;
}
} else if (topology_a->sharing || topology_b->sharing) {
pr_err("One of mounts %d and %d has sharing and other doesn't\n", topology_a->mountinfo->mnt_id,
topology_b->mountinfo->mnt_id);
return -1;
}
topology_a = list_entry(topology_a->list.next, struct mountinfo_topology, list);
topology_b = list_entry(topology_b->list.next, struct mountinfo_topology, list);
}
if (&topology_a->list != &mntns_a->topology_list || &topology_b->list != &mntns_b->topology_list) {
pr_err("Mount tree topology length mismatch\n");
return -1;
}
return 0;
}
static int sharing_group_list_compare(struct mntns_zdtm *mntns_a, struct mntns_zdtm *mntns_b)
{
struct sharing_group *sg_a, *sg_b;
sg_a = list_first_entry(&mntns_a->sharing_groups_list, struct sharing_group, list);
sg_b = list_first_entry(&mntns_b->sharing_groups_list, struct sharing_group, list);
while (&sg_a->list != &mntns_a->sharing_groups_list && &sg_b->list != &mntns_b->sharing_groups_list) {
if (sg_a->topology_id != sg_b->topology_id) {
pr_err("Sharings (%d,%d) and (%d,%d) have different sharing topology id %d and %d\n",
sg_a->shared_id, sg_a->master_id, sg_b->shared_id, sg_b->master_id, sg_a->topology_id,
sg_b->topology_id);
return -1;
}
if (sg_a->parent && sg_b->parent) {
if (sg_a->parent->topology_id != sg_b->parent->topology_id) {
pr_err("Sharings (%d,%d) and (%d,%d) have different parent topology id %d and %d\n",
sg_a->shared_id, sg_a->master_id, sg_b->shared_id, sg_b->master_id,
sg_a->parent->topology_id, sg_b->parent->topology_id);
return -1;
}
} else if (sg_a->parent || sg_b->parent) {
pr_err("One of sharings (%d,%d) and (%d,%d) has parent and other doesn't\n", sg_a->shared_id,
sg_a->master_id, sg_b->shared_id, sg_b->master_id);
return -1;
}
sg_a = list_entry(sg_a->list.next, struct sharing_group, list);
sg_b = list_entry(sg_b->list.next, struct sharing_group, list);
}
if (&sg_a->list != &mntns_a->sharing_groups_list || &sg_b->list != &mntns_b->sharing_groups_list) {
pr_err("Mount tree sharing topology length mismatch\n");
return -1;
}
return 0;
}
int mntns_compare(struct mntns_zdtm *mntns_a, struct mntns_zdtm *mntns_b)
{
if (mntns_build_tree(mntns_a)) {
pr_err("Failed to build first mountinfo topology tree\n");
return -1;
}
if (mntns_build_tree(mntns_b)) {
pr_err("Failed to build second mountinfo topology tree\n");
return -1;
}
if (mountinfo_topology_list_compare(mntns_a, mntns_b))
return -1;
if (sharing_group_list_compare(mntns_a, mntns_b))
return -1;
return 0;
}
void mntns_free_all(struct mntns_zdtm *mntns)
{
mountinfo_zdtm_free_all(mntns);
mountinfo_topology_free_all(mntns);
sharing_group_free_all(mntns);
}
| 13,482 | 26.460285 | 118 |
c
|
criu
|
criu-master/test/zdtm/lib/mountinfo.h
|
#ifndef __ZDTM_MOUNTINFO__
#define __ZDTM_MOUNTINFO__
#include "list.h"
struct mountinfo_zdtm {
int mnt_id;
int parent_mnt_id;
char *mountpoint;
char *root;
unsigned int s_dev;
int shared_id;
int master_id;
char *fstype;
/* list of all mounts */
struct list_head list;
};
struct mntns_zdtm {
struct list_head mountinfo_list;
struct list_head topology_list;
struct mountinfo_topology *tree;
struct list_head sharing_groups_list;
};
#define MNTNS_ZDTM_INIT(name) \
{ \
.mountinfo_list = LIST_HEAD_INIT(name.mountinfo_list), \
.topology_list = LIST_HEAD_INIT(name.topology_list), \
.sharing_groups_list = LIST_HEAD_INIT(name.sharing_groups_list), \
}
#define MNTNS_ZDTM(name) struct mntns_zdtm name = MNTNS_ZDTM_INIT(name)
struct sharing_group {
int shared_id;
int master_id;
unsigned int s_dev;
struct sharing_group *parent;
struct list_head children;
struct list_head siblings;
int topology_id;
struct list_head mounts_list;
struct list_head list;
};
struct mountinfo_topology {
struct mountinfo_zdtm *mountinfo;
struct mountinfo_topology *parent;
struct list_head children;
struct list_head siblings;
int topology_id;
struct sharing_group *sharing;
struct list_head sharing_list;
struct list_head list;
};
extern int mntns_parse_mountinfo(struct mntns_zdtm *mntns);
extern void mntns_free_all(struct mntns_zdtm *mntns);
extern int mntns_compare(struct mntns_zdtm *mntns_a, struct mntns_zdtm *mntns_b);
#endif
| 1,609 | 21.676056 | 82 |
h
|
criu
|
criu-master/test/zdtm/lib/ns.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <grp.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <sys/mount.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <signal.h>
#include <sched.h>
#include <sys/socket.h>
#include <time.h>
#include <sys/prctl.h>
#include "zdtmtst.h"
#include "ns.h"
int criu_status_in = -1, criu_status_in_peer = -1, criu_status_out = -1;
extern int pivot_root(const char *new_root, const char *put_old);
static int prepare_mntns(void)
{
int dfd, ret;
char *root, *criu_path;
char path[PATH_MAX];
root = getenv("ZDTM_ROOT");
if (!root) {
fprintf(stderr, "ZDTM_ROOT isn't set\n");
return -1;
}
/*
* In a new userns all mounts are locked to protect what is
* under them. So we need to create another mount for the
* new root.
*/
if (mount(root, root, NULL, MS_SLAVE, NULL)) {
fprintf(stderr, "Can't bind-mount root: %m\n");
return -1;
}
if (mount(root, root, NULL, MS_BIND | MS_REC, NULL)) {
fprintf(stderr, "Can't bind-mount root: %m\n");
return -1;
}
criu_path = getenv("ZDTM_CRIU");
if (criu_path) {
snprintf(path, sizeof(path), "%s%s", root, criu_path);
if (mount(criu_path, path, NULL, MS_BIND, NULL) || mount(NULL, path, NULL, MS_PRIVATE, NULL)) {
pr_perror("Unable to mount %s", path);
return -1;
}
}
/* Move current working directory to the new root */
ret = readlink("/proc/self/cwd", path, sizeof(path) - 1);
if (ret < 0)
return -1;
path[ret] = 0;
dfd = open(path, O_RDONLY | O_DIRECTORY);
if (dfd == -1) {
fprintf(stderr, "open(.) failed: %m\n");
return -1;
}
if (chdir(root)) {
fprintf(stderr, "chdir(%s) failed: %m\n", root);
return -1;
}
if (mkdir("old", 0777) && errno != EEXIST) {
fprintf(stderr, "mkdir(old) failed: %m\n");
return -1;
}
if (pivot_root(".", "./old")) {
fprintf(stderr, "pivot_root(., ./old) failed: %m\n");
return -1;
}
if (mount("./old", "./old", NULL, MS_SLAVE | MS_REC, NULL)) {
fprintf(stderr, "Can't bind-mount root: %m\n");
return -1;
}
/*
* proc and sysfs can be mounted in an unprivileged namespace,
* if they are already mounted when the user namespace is created.
* So ./old must be umounted after mounting /proc and /sys.
*/
if (mount("proc", "/proc", "proc", MS_MGC_VAL | MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL)) {
fprintf(stderr, "mount(/proc) failed: %m\n");
return -1;
}
if (mount("zdtm_run", "/run", "tmpfs", 0, NULL)) {
fprintf(stderr, "Unable to mount /run: %m\n");
return -1;
}
if (umount2("./old", MNT_DETACH)) {
fprintf(stderr, "umount(./old) failed: %m\n");
return -1;
}
if (mount("pts", "/dev/pts", "devpts", MS_MGC_VAL, "mode=666,ptmxmode=666,newinstance")) {
fprintf(stderr, "mount(/dev/pts) failed: %m\n");
return -1;
}
/*
* If CONFIG_DEVPTS_MULTIPLE_INSTANCES=n, then /dev/pts/ptmx
* does not exist. Fall back to creating the device with
* mknod() in that case.
*/
if (access("/dev/pts/ptmx", F_OK) == 0) {
if (symlink("pts/ptmx", "/dev/ptmx") && errno != EEXIST) {
fprintf(stderr, "symlink(/dev/ptmx) failed: %m\n");
return -1;
}
} else {
if (mknod("/dev/ptmx", 0666 | S_IFCHR, makedev(5, 2)) == 0) {
chmod("/dev/ptmx", 0666);
} else if (errno != EEXIST) {
fprintf(stderr, "mknod(/dev/ptmx) failed: %m\n");
return -1;
}
}
if (fchdir(dfd)) {
fprintf(stderr, "fchdir() failed: %m\n");
return -1;
}
close(dfd);
return 0;
}
static int prepare_namespaces(void)
{
if (setuid(0) || setgid(0) || setgroups(0, NULL)) {
fprintf(stderr, "set*id failed: %m\n");
return -1;
}
system("ip link set up dev lo");
if (prepare_mntns())
return -1;
return 0;
}
#define NS_STACK_SIZE 4096
/* All arguments should be above stack, because it grows down */
struct ns_exec_args {
char stack[NS_STACK_SIZE] __stack_aligned__;
char stack_ptr[0];
int argc;
char **argv;
int status_pipe[2];
};
static void ns_sig_hand(int signo)
{
int status, len = 0;
pid_t pid;
char buf[128] = "";
if (signo == SIGTERM) {
futex_set_and_wake(&sig_received, signo);
len = snprintf(buf, sizeof(buf), "Time to stop and check\n");
goto write_out;
}
while (1) {
pid = waitpid(-1, &status, WNOHANG);
if (pid == 0)
return;
if (pid == -1) {
if (errno == ECHILD) {
if (futex_get(&sig_received))
return;
futex_set_and_wake(&sig_received, signo);
len = snprintf(buf, sizeof(buf), "All test processes exited\n");
} else {
len = snprintf(buf, sizeof(buf), "wait() failed: %m\n");
}
goto write_out;
}
if (status)
fprintf(stderr, "%d return %d\n", pid, status);
}
return;
write_out:
/* fprintf can't be used in a sighandler due to glibc locks */
write(STDERR_FILENO, buf, MIN(len, sizeof(buf)));
}
#ifndef CLONE_NEWTIME
#define CLONE_NEWTIME 0x00000080 /* New time namespace */
#endif
static inline int _settime(clockid_t clk_id, time_t offset)
{
int fd, len;
char buf[4096];
if (clk_id == CLOCK_MONOTONIC_COARSE || clk_id == CLOCK_MONOTONIC_RAW)
clk_id = CLOCK_MONOTONIC;
len = snprintf(buf, sizeof(buf), "%d %ld 0", clk_id, offset);
fd = open("/proc/self/timens_offsets", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open(/proc/self/timens_offsets): %m");
return -1;
}
if (write(fd, buf, len) != len) {
fprintf(stderr, "write(/proc/self/timens_offsets): %m");
return -1;
}
if (close(fd)) {
fprintf(stderr, "close(/proc/self/timens_offsets): %m");
return -1;
}
return 0;
}
#define STATUS_FD 255
static int ns_exec(void *_arg)
{
struct ns_exec_args *args = (struct ns_exec_args *)_arg;
char buf[4096];
int ret;
close(args->status_pipe[0]);
setsid();
prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
ret = dup2(args->status_pipe[1], STATUS_FD);
if (ret < 0) {
fprintf(stderr, "dup2() failed: %m\n");
return -1;
}
close(args->status_pipe[1]);
read(STATUS_FD, buf, sizeof(buf));
shutdown(STATUS_FD, SHUT_RD);
if (prepare_namespaces())
return -1;
setenv("ZDTM_NEWNS", "2", 1);
execvp(args->argv[0], args->argv);
fprintf(stderr, "exec(%s) failed: %m\n", args->argv[0]);
return -1;
}
static int create_timens(void)
{
int fd;
if (unshare(CLONE_NEWTIME)) {
if (errno == EINVAL) {
fprintf(stderr, "timens isn't supported\n");
return 0;
} else {
fprintf(stderr, "unshare(CLONE_NEWTIME) failed: %m");
exit(1);
}
}
if (_settime(CLOCK_MONOTONIC, 10 * 24 * 60 * 60))
exit(1);
if (_settime(CLOCK_BOOTTIME, 20 * 24 * 60 * 60))
exit(1);
fd = open("/proc/self/ns/time_for_children", O_RDONLY);
if (fd < 0)
exit(1);
if (setns(fd, 0))
exit(1);
close(fd);
return 0;
}
int ns_init(int argc, char **argv)
{
struct sigaction sa = {
.sa_handler = ns_sig_hand,
.sa_flags = SA_RESTART,
};
int ret, fd, status_pipe = STATUS_FD;
char buf[128], *x;
pid_t pid;
bool reap;
ret = fcntl(status_pipe, F_SETFD, FD_CLOEXEC);
if (ret == -1) {
fprintf(stderr, "fcntl failed %m\n");
exit(1);
}
if (create_timens())
exit(1);
if (init_notify()) {
fprintf(stderr, "Can't init pre-dump notification: %m");
exit(1);
}
reap = getenv("ZDTM_NOREAP") == NULL;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGTERM);
if (reap)
sigaddset(&sa.sa_mask, SIGCHLD);
if (sigaction(SIGTERM, &sa, NULL)) {
fprintf(stderr, "Can't set SIGTERM handler: %m\n");
exit(1);
}
x = malloc(strlen(pidfile) + 3);
sprintf(x, "%sns", pidfile);
pidfile = x;
/* Start test */
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork() failed: %m\n");
exit(1);
} else if (pid == 0) {
close(status_pipe);
unsetenv("ZDTM_NEWNS");
return 0; /* Continue normal test startup */
}
ret = -1;
if (waitpid(pid, &ret, 0) < 0)
fprintf(stderr, "waitpid() failed: %m\n");
else if (ret)
fprintf(stderr, "The test returned non-zero code %d\n", ret);
if (reap && sigaction(SIGCHLD, &sa, NULL)) {
fprintf(stderr, "Can't set SIGCHLD handler: %m\n");
exit(1);
}
while (reap && 1) {
int status;
pid = waitpid(-1, &status, WNOHANG);
if (pid == 0)
break;
if (pid < 0) {
fprintf(stderr, "waitpid() failed: %m\n");
exit(1);
}
if (status)
fprintf(stderr, "%d return %d\n", pid, status);
}
/* Daemonize */
write(status_pipe, &ret, sizeof(ret));
close(status_pipe);
if (ret)
exit(ret);
/* suspend/resume */
test_waitsig();
fd = open(pidfile, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "open(%s) failed: %m\n", pidfile);
exit(1);
}
ret = read(fd, buf, sizeof(buf) - 1);
if (ret == -1) {
fprintf(stderr, "read() failed: %m\n");
exit(1);
}
buf[ret] = '\0';
pid = atoi(buf);
fprintf(stderr, "kill(%d, SIGTERM)\n", pid);
if (pid > 0)
kill(pid, SIGTERM);
ret = 0;
if (reap) {
while (true) {
pid_t child;
ret = -1;
child = waitpid(-1, &ret, 0);
if (child < 0) {
fprintf(stderr, "Unable to wait a test process: %m");
exit(1);
}
if (child == pid) {
fprintf(stderr, "The test returned 0x%x", ret);
exit(!(ret == 0));
}
if (ret)
fprintf(stderr, "The %d process exited with 0x%x", child, ret);
}
} else {
waitpid(pid, NULL, 0);
}
exit(1);
}
#define UID_MAP "0 20000 20000\n100000 200000 50000"
#define GID_MAP "0 400000 50000\n50000 500000 100000"
void ns_create(int argc, char **argv)
{
pid_t pid;
int ret, status;
struct ns_exec_args args;
int flags;
char *pidf;
args.argc = argc;
args.argv = argv;
ret = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, args.status_pipe);
if (ret) {
fprintf(stderr, "Pipe() failed %m\n");
exit(1);
}
flags = CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWNET | CLONE_NEWIPC | SIGCHLD;
if (getenv("ZDTM_USERNS"))
flags |= CLONE_NEWUSER;
pid = clone(ns_exec, args.stack_ptr, flags, &args);
if (pid < 0) {
fprintf(stderr, "clone() failed: %m\n");
exit(1);
}
close(args.status_pipe[1]);
if (flags & CLONE_NEWUSER) {
char pname[PATH_MAX];
int fd;
snprintf(pname, sizeof(pname), "/proc/%d/uid_map", pid);
fd = open(pname, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open(%s): %m\n", pname);
exit(1);
}
if (write(fd, UID_MAP, sizeof(UID_MAP)) < 0) {
fprintf(stderr, "write(" UID_MAP "): %m\n");
exit(1);
}
close(fd);
snprintf(pname, sizeof(pname), "/proc/%d/gid_map", pid);
fd = open(pname, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open(%s): %m\n", pname);
exit(1);
}
if (write(fd, GID_MAP, sizeof(GID_MAP)) < 0) {
fprintf(stderr, "write(" GID_MAP "): %m\n");
exit(1);
}
close(fd);
}
shutdown(args.status_pipe[0], SHUT_WR);
pidf = pidfile;
pidfile = malloc(strlen(pidfile) + 13);
sprintf(pidfile, "%s%s", pidf, INPROGRESS);
if (write_pidfile(pid)) {
fprintf(stderr, "Preparations fail\n");
exit(1);
}
status = 1;
ret = read(args.status_pipe[0], &status, sizeof(status));
if (ret != sizeof(status) || status) {
fprintf(stderr, "The test failed (%d, %d)\n", ret, status);
exit(1);
}
ret = read(args.status_pipe[0], &status, sizeof(status));
if (ret != 0) {
fprintf(stderr, "Unexpected message from test\n");
exit(1);
}
unlink(pidfile);
pidfile = pidf;
if (write_pidfile(pid))
exit(1);
exit(0);
}
| 11,154 | 20.493256 | 97 |
c
|
criu
|
criu-master/test/zdtm/lib/tcp.c
|
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include "zdtmtst.h"
union sockaddr_inet {
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
int tcp_init_server(int family, int *port)
{
struct zdtm_tcp_opts opts = {
.reuseaddr = true,
.reuseport = false,
};
return tcp_init_server_with_opts(family, port, &opts);
}
int tcp_init_server_with_opts(int family, int *port, struct zdtm_tcp_opts *opts)
{
union sockaddr_inet addr;
int sock;
int yes = 1, ret;
memset(&addr, 0, sizeof(addr));
if (family == AF_INET) {
addr.v4.sin_family = family;
inet_pton(family, "0.0.0.0", &(addr.v4.sin_addr));
} else if (family == AF_INET6) {
addr.v6.sin6_family = family;
inet_pton(family, "::0", &(addr.v6.sin6_addr));
} else
return -1;
sock = socket(family, SOCK_STREAM | opts->flags, IPPROTO_TCP);
if (sock == -1) {
pr_perror("socket() failed");
return -1;
}
if (opts->reuseport && setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(int)) == -1) {
pr_perror("setsockopt(SO_REUSEPORT) failed");
return -1;
}
if (opts->reuseaddr && setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
pr_perror("setsockopt(SO_REUSEATTR) failed");
return -1;
}
while (1) {
if (family == AF_INET)
addr.v4.sin_port = htons(*port);
else if (family == AF_INET6)
addr.v6.sin6_port = htons(*port);
ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
/* criu doesn't restore sock opts, so we need this hack */
if (ret == -1 && errno == EADDRINUSE) {
test_msg("The port %d is already in use.\n", *port);
(*port)++;
continue;
}
break;
}
if (ret == -1) {
pr_perror("bind() failed");
return -1;
}
if (listen(sock, 1) == -1) {
pr_perror("listen() failed");
return -1;
}
return sock;
}
int tcp_accept_server(int sock)
{
struct sockaddr_in maddr;
int sock2;
socklen_t addrlen;
#ifdef DEBUG
test_msg("Waiting for connection..........\n");
#endif
addrlen = sizeof(maddr);
sock2 = accept(sock, (struct sockaddr *)&maddr, &addrlen);
if (sock2 == -1) {
pr_perror("accept() failed");
return -1;
}
#ifdef DEBUG
test_msg("Connection!!\n");
#endif
return sock2;
}
int tcp_init_client(int family, char *servIP, unsigned short servPort)
{
int sock;
if ((sock = socket(family, SOCK_STREAM, IPPROTO_TCP)) < 0) {
pr_perror("can't create socket");
return -1;
}
return tcp_init_client_with_fd(sock, family, servIP, servPort);
}
int tcp_init_client_with_fd(int sock, int family, char *servIP, unsigned short servPort)
{
union sockaddr_inet servAddr;
/* Construct the server address structure */
memset(&servAddr, 0, sizeof(servAddr));
if (family == AF_INET) {
servAddr.v4.sin_family = AF_INET;
servAddr.v4.sin_port = htons(servPort);
inet_pton(AF_INET, servIP, &servAddr.v4.sin_addr);
} else {
servAddr.v6.sin6_family = AF_INET6;
servAddr.v6.sin6_port = htons(servPort);
inet_pton(AF_INET6, servIP, &servAddr.v6.sin6_addr);
}
if (connect(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) {
pr_perror("can't connect to server");
return -1;
}
return sock;
}
| 3,142 | 21.775362 | 94 |
c
|
criu
|
criu-master/test/zdtm/lib/xmalloc.h
|
#ifndef __ZDTM_XMALLOC_H__
#define __ZDTM_XMALLOC_H__
#include <stdlib.h>
#include <string.h>
#ifndef pr_err
#error "Macro pr_err is needed."
#endif
#define __xalloc(op, size, ...) \
({ \
void *___p = op(__VA_ARGS__); \
if (!___p) \
pr_err("%s: Can't allocate %li bytes\n", __func__, (long)(size)); \
___p; \
})
#define xstrdup(str) __xalloc(strdup, strlen(str) + 1, str)
#define xmalloc(size) __xalloc(malloc, size, size)
#define xzalloc(size) __xalloc(calloc, size, 1, size)
#define xrealloc(p, size) __xalloc(realloc, size, p, size)
#define xfree(p) free(p)
#define xrealloc_safe(pptr, size) \
({ \
int __ret = -1; \
void *new = xrealloc(*pptr, size); \
if (new) { \
*pptr = new; \
__ret = 0; \
} \
__ret; \
})
#define xmemdup(ptr, size) \
({ \
void *new = xmalloc(size); \
if (new) \
memcpy(new, ptr, size); \
new; \
})
#define memzero_p(p) memset(p, 0, sizeof(*p))
#define memzero(p, size) memset(p, 0, size)
/*
* Helper for allocating trees with single xmalloc.
* This one advances the void *pointer on s bytes and
* returns the previous value. Use like this
*
* m = xmalloc(total_size);
* a = xptr_pull(&m, tree_root_t);
* a->b = xptr_pull(&m, leaf_a_t);
* a->c = xptr_pull(&m, leaf_c_t);
* ...
*/
static inline void *xptr_pull_s(void **m, size_t s)
{
void *ret = (*m);
(*m) += s;
return ret;
}
#define xptr_pull(m, type) xptr_pull_s(m, sizeof(type))
#endif /* __CR_XMALLOC_H__ */
| 2,075 | 29.086957 | 91 |
h
|
criu
|
criu-master/test/zdtm/lib/zdtmtst.h
|
#ifndef _VIMITESU_H_
#define _VIMITESU_H_
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#define INPROGRESS ".inprogress"
#ifndef PAGE_SIZE
#define PAGE_SIZE (unsigned int)(sysconf(_SC_PAGESIZE))
#endif
#ifndef PR_SET_CHILD_SUBREAPER
#define PR_SET_CHILD_SUBREAPER 36
#endif
/* set up test */
extern void test_ext_init(int argc, char **argv);
extern void test_init(int argc, char **argv);
#ifndef CLONE_NEWUTS
#define CLONE_NEWUTS 0x04000000
#endif
#ifndef CLONE_NEWIPC
#define CLONE_NEWIPC 0x08000000
#endif
#define TEST_MSG_BUFFER_SIZE 2048
/*wrapper for fork: init log offset*/
#define test_fork() test_fork_id(-1)
extern int test_fork_id(int id);
/* finish setting up the test, write out pid file, and go to background */
extern void test_daemon(void);
/* store a message to a static buffer */
extern void test_msg(const char *format, ...) __attribute__((__format__(__printf__, 1, 2)));
/* tell if SIGTERM hasn't been received yet */
extern int test_go(void);
/* sleep until SIGTERM is delivered */
extern void test_waitsig(void);
/* sleep until zdtm notifies about predump */
extern int test_wait_pre_dump(void);
/* notify zdtm that we finished action after predump */
extern int test_wait_pre_dump_ack(void);
#include <stdint.h>
/* generate data with crc32 at the end of the buffer */
extern void datagen(uint8_t *buffer, unsigned length, uint32_t *crc);
/* generate data without crc32 at the end of the buffer */
extern void datagen2(uint8_t *buffer, unsigned length, uint32_t *crc);
/* check the data buffer against its crc32 */
extern int datachk(const uint8_t *buffer, unsigned length, uint32_t *crc);
/* calculate crc for the data buffer*/
extern int datasum(const uint8_t *buffer, unsigned length, uint32_t *crc);
/* streaming helpers */
extern int set_nonblock(int fd, int on);
extern int pipe_in2out(int infd, int outfd, uint8_t *buffer, int length);
extern int read_data(int fd, unsigned char *buf, int len);
extern int write_data(int fd, const unsigned char *buf, int len);
/* command line args */
struct long_opt {
const char *name;
const char *type;
const char *doc;
int is_required;
int (*parse_opt)(char *arg, void *value);
void *value;
struct long_opt *next;
};
extern void __push_opt(struct long_opt *opt);
#define TEST_OPTION(name, type, doc, is_required) \
param_check_##type(name, &(name)); \
static struct long_opt __long_opt_##name = { #name, #type, doc, is_required, parse_opt_##type, &name }; \
static void __init_opt_##name(void) __attribute__((constructor)); \
static void __init_opt_##name(void) \
{ \
(void)__check_##name; \
__push_opt(&__long_opt_##name); \
}
#define __param_check(name, p, type) \
static inline type *__check_##name(void) \
{ \
return (p); \
}
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
extern void parseargs(int, char **);
extern int parse_opt_bool(char *param, void *arg);
#define param_check_bool(name, p) __param_check(name, p, int)
extern int parse_opt_int(char *param, void *arg);
#define param_check_int(name, p) __param_check(name, p, int)
extern int parse_opt_uint(char *param, void *arg);
#define param_check_uint(name, p) __param_check(name, p, unsigned int)
extern int parse_opt_long(char *param, void *arg);
#define param_check_long(name, p) __param_check(name, p, long)
extern int parse_opt_ulong(char *param, void *arg);
#define param_check_ulong(name, p) __param_check(name, p, unsigned long)
extern int parse_opt_string(char *param, void *arg);
#define param_check_string(name, p) __param_check(name, p, char *)
extern int write_pidfile(int pid);
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define __stringify_1(x) #x
#define __stringify(x) __stringify_1(x)
/*
* Macro to define stack alignment.
* aarch64 requires stack to be aligned to 16 bytes.
*/
#define __stack_aligned__ __attribute__((aligned(16)))
/* message helpers */
extern int test_log_init(const char *outfile, const char *suffix);
extern int zdtm_seccomp;
#define pr_err(format, arg...) \
({ \
test_msg("ERR: %s:%d: " format, __FILE__, __LINE__, ##arg); \
1; \
})
#define pr_perror(format, arg...) \
({ \
test_msg("ERR: %s:%d: " format " (errno = %d (%s))\n", __FILE__, __LINE__, ##arg, errno, \
strerror(errno)); \
1; \
})
#define fail(format, arg...) \
({ \
test_msg("FAIL: %s:%d: " format " (errno = %d (%s))\n", __FILE__, __LINE__, ##arg, errno, \
strerror(errno)); \
1; \
})
#define skip(format, arg...) test_msg("SKIP: %s:%d: " format "\n", __FILE__, __LINE__, ##arg)
#define pass() test_msg("PASS\n")
typedef struct {
unsigned long seed;
int pipes[2];
} task_waiter_t;
extern void task_waiter_init(task_waiter_t *t);
extern void task_waiter_fini(task_waiter_t *t);
extern void task_waiter_wait4(task_waiter_t *t, unsigned int lockid);
extern void task_waiter_complete(task_waiter_t *t, unsigned int lockid);
extern void task_waiter_complete_current(task_waiter_t *t);
extern int tcp_init_server(int family, int *port);
extern int tcp_accept_server(int sock);
extern int tcp_init_client(int family, char *servIP, unsigned short servPort);
extern int tcp_init_client_with_fd(int sock, int family, char *servIP, unsigned short servPort);
struct sockaddr_un;
extern int unix_fill_sock_name(struct sockaddr_un *name, char *relFilename);
struct zdtm_tcp_opts {
bool reuseaddr;
bool reuseport;
int flags;
};
extern const char *test_author;
extern const char *test_doc;
extern int tcp_init_server_with_opts(int family, int *port, struct zdtm_tcp_opts *opts);
extern pid_t sys_clone_unified(unsigned long flags, void *child_stack, void *parent_tid, void *child_tid,
unsigned long newtls);
extern dev_t get_mapping_dev(void *addr);
#define ssprintf(s, fmt, ...) \
({ \
int ___ret; \
\
___ret = snprintf(s, sizeof(s), fmt, ##__VA_ARGS__); \
if (___ret >= sizeof(s)) \
abort(); \
___ret; \
})
#ifndef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(expression) \
(__extension__({ \
long int __result; \
do \
__result = (long int)(expression); \
while (__result < 0 && errno == EINTR); \
__result; \
}))
#endif
#define cleanup_close __attribute__((cleanup(cleanup_closep)))
#define cleanup_free __attribute__((cleanup(cleanup_freep)))
static inline void cleanup_freep(void *p)
{
void **pp = (void **)p;
free(*pp);
}
static inline void cleanup_closep(void *p)
{
int *pp = (int *)p;
if (*pp >= 0)
TEMP_FAILURE_RETRY(close(*pp));
}
extern int write_value(const char *path, const char *value);
extern int read_value(const char *path, char *value, int size);
#define container_of(ptr, type, member) \
({ \
const typeof(((type *)0)->member) *__mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); \
})
#endif /* _VIMITESU_H_ */
| 8,675 | 36.886463 | 113 |
h
|
criu
|
criu-master/test/zdtm/lib/arch/mips/include/asm/atomic.h
|
#ifndef __CR_ATOMIC_H__
#define __CR_ATOMIC_H__
//#include <linux/types.h>
//#include "common/compiler.h"
//#include "common/arch/mips/asm/utils.h"
//#include "common/arch/mips/asm/cmpxchg.h"
typedef uint32_t atomic_t;
/* typedef struct { */
/* int counter; */
/* }atomic_t; */
#define __WEAK_LLSC_MB " sync \n"
#define smp_llsc_mb() __asm__ __volatile__(__WEAK_LLSC_MB : : : "memory")
#define smp_mb__before_llsc() smp_llsc_mb()
#define smp_mb__before_atomic() smp_mb__before_llsc()
#define smp_mb__after_atomic() smp_llsc_mb()
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define atomic_get(v) (*(volatile int *)v)
#define atomic_set(v, i) ((*v) = (i))
//#define atomic_get atomic_read
/*
* atomic_add - add integer to atomic variable
* @i: integer value to add
* @v: pointer of type atomic_t
*
* Atomically adds @i to @v.
*/
static __inline__ void atomic_add(int i, atomic_t *v)
{
int temp;
do {
__asm__ __volatile__(" .set mips3 \n"
" ll %0, %1 # atomic_add \n"
" addu %0, %2 \n"
" sc %0, %1 \n"
" .set mips0 \n"
: "=&r"(temp), "+m"(*v)
: "Ir"(i));
} while (unlikely(!temp));
}
/*
* atomic_sub - subtract the atomic variable
* @i: integer value to subtract
* @v: pointer of type atomic_t
*
* Atomically subtracts @i from @v.
*/
static __inline__ void atomic_sub(int i, atomic_t *v)
{
int temp;
do {
__asm__ __volatile__(" .set mips3 \n"
" ll %0, %1 # atomic_sub \n"
" subu %0, %2 \n"
" sc %0, %1 \n"
" .set mips0 \n"
: "=&r"(temp), "+m"(*v)
: "Ir"(i));
} while (unlikely(!temp));
}
/*
* Same as above, but return the result value
*/
static __inline__ int atomic_add_return(int i, atomic_t *v)
{
int result;
int temp;
smp_mb__before_llsc();
do {
__asm__ __volatile__(" .set mips3 \n"
" ll %1, %2 # atomic_add_return \n"
" addu %0, %1, %3 \n"
" sc %0, %2 \n"
" .set mips0 \n"
: "=&r"(result), "=&r"(temp), "+m"(*v)
: "Ir"(i));
} while (unlikely(!result));
result = temp + i;
smp_llsc_mb();
return result;
}
static __inline__ int atomic_sub_return(int i, atomic_t *v)
{
int result;
int temp;
smp_mb__before_llsc();
do {
__asm__ __volatile__(" .set mips3 \n"
" ll %1, %2 # atomic_sub_return \n"
" subu %0, %1, %3 \n"
" sc %0, %2 \n"
" .set mips0 \n"
: "=&r"(result), "=&r"(temp), "+m"(*v)
: "Ir"(i));
} while (unlikely(!result));
result = temp - i;
smp_llsc_mb();
return result;
}
#define atomic_cmpxchg(v, o, n) (cmpxchg(&((v)->counter), (o), (n)))
#define atomic_dec_return(v) atomic_sub_return(1, (v))
#define atomic_inc_return(v) atomic_add_return(1, (v))
static inline unsigned int atomic_inc(atomic_t *v)
{
return atomic_add_return(1, v) - 1;
}
static inline unsigned int atomic_dec(atomic_t *v)
{
return atomic_sub_return(1, v) + 1;
}
#endif /* __CR_ATOMIC_H__ */
| 3,059 | 21.014388 | 73 |
h
|
criu
|
criu-master/test/zdtm/lib/arch/ppc64/include/asm/atomic.h
|
#ifndef __CR_ATOMIC_H__
#define __CR_ATOMIC_H__
/*
* PowerPC atomic operations
*
* Copied from kernel header file arch/powerpc/include/asm/atomic.h
*/
typedef uint32_t atomic_t;
#define PPC_ATOMIC_ENTRY_BARRIER "lwsync \n"
#define PPC_ATOMIC_EXIT_BARRIER "sync \n"
#define ATOMIC_INIT(i) \
{ \
(i) \
}
static __inline__ int atomic_get(const atomic_t *v)
{
int t;
__asm__ __volatile__("lwz%U1%X1 %0,%1" : "=r"(t) : "m"(*v));
return t;
}
static __inline__ void atomic_set(atomic_t *v, int i)
{
__asm__ __volatile__("stw%U0%X0 %1,%0" : "=m"(*v) : "r"(i));
}
#define ATOMIC_OP(op, asm_op) \
static __inline__ void atomic_##op(int a, atomic_t *v) \
{ \
int t; \
\
__asm__ __volatile__("1: lwarx %0,0,%3 # atomic_" #op "\n" #asm_op " %0,%2,%0\n" \
" stwcx. %0,0,%3 \n" \
" bne- 1b\n" \
: "=&r"(t), "+m"(*v) \
: "r"(a), "r"(v) \
: "cc"); \
}
ATOMIC_OP(add, add)
ATOMIC_OP(sub, subf)
#undef ATOMIC_OP
static __inline__ int atomic_inc_return(atomic_t *v)
{
int t;
__asm__ __volatile__(PPC_ATOMIC_ENTRY_BARRIER "1: lwarx %0,0,%1 # atomic_inc_return\n\
addic %0,%0,1\n"
" stwcx. %0,0,%1 \n\
bne- 1b \n" PPC_ATOMIC_EXIT_BARRIER
: "=&r"(t)
: "r"(v)
: "cc", "xer", "memory");
return t;
}
static __inline__ int atomic_inc(atomic_t *v)
{
return atomic_inc_return(v) - 1;
}
static __inline__ void atomic_dec(atomic_t *v)
{
int t;
__asm__ __volatile__("1: lwarx %0,0,%2 # atomic_dec\n\
addic %0,%0,-1\n"
" stwcx. %0,0,%2\n\
bne- 1b"
: "=&r"(t), "+m"(*v)
: "r"(v)
: "cc", "xer");
}
#endif /* __CR_ATOMIC_H__ */
| 2,421 | 27.494118 | 115 |
h
|
criu
|
criu-master/test/zdtm/lib/arch/s390/include/asm/atomic.h
|
#ifndef __ARCH_S390_ATOMIC__
#define __ARCH_S390_ATOMIC__
#include <stdint.h>
typedef uint32_t atomic_t;
#define __ATOMIC_OP(op_name, op_type, op_string) \
static inline op_type op_name(op_type val, op_type *ptr) \
{ \
op_type old, new; \
\
asm volatile("0: lr %[new],%[old]\n" op_string " %[new],%[val]\n" \
" cs %[old],%[new],%[ptr]\n" \
" jl 0b" \
: [old] "=d"(old), [new] "=&d"(new), [ptr] "+Q"(*ptr) \
: [val] "d"(val), "0"(*ptr) \
: "cc", "memory"); \
return old; \
}
#define __ATOMIC_OPS(op_name, op_type, op_string) \
__ATOMIC_OP(op_name, op_type, op_string) \
__ATOMIC_OP(op_name##_barrier, op_type, op_string)
__ATOMIC_OPS(__atomic_add, uint32_t, "ar")
#undef __ATOMIC_OPS
#undef __ATOMIC_OP
static inline int atomic_get(const atomic_t *v)
{
int c;
asm volatile(" l %0,%1\n" : "=d"(c) : "Q"(*v));
return c;
}
static inline void atomic_set(atomic_t *v, int i)
{
asm volatile(" st %1,%0\n" : "=Q"(*v) : "d"(i));
}
static inline int atomic_add_return(int i, atomic_t *v)
{
return __atomic_add_barrier(i, v) + i;
}
static inline void atomic_add(int i, atomic_t *v)
{
__atomic_add(i, v);
}
#define atomic_sub(_i, _v) atomic_add(-(int)(_i), _v)
static inline int atomic_inc(atomic_t *v)
{
return atomic_add_return(1, v) - 1;
}
#define atomic_dec(_v) atomic_sub(1, _v)
#endif /* __ARCH_S390_ATOMIC__ */
| 1,945 | 29.40625 | 95 |
h
|
criu
|
criu-master/test/zdtm/lib/arch/x86/include/asm/atomic.h
|
#ifndef ATOMIC_H__
#define ATOMIC_H__
#define atomic_set(mem, v) ({ asm volatile("lock xchg %0, %1\n" : "+r"(v), "+m"(*mem) : : "cc", "memory"); })
#define atomic_get(mem) \
({ \
uint32_t ret__ = 0; \
asm volatile("lock xadd %0, %1\n" : "+r"(ret__), "+m"(*mem) : : "cc", "memory"); \
ret__; \
})
#define atomic_inc(mem) \
({ \
uint32_t ret__ = 1; \
asm volatile("lock xadd %0, %1\n" : "+r"(ret__), "+m"(*mem) : : "cc", "memory"); \
ret__; \
})
#define atomic_dec(mem) \
({ \
uint32_t ret__ = -1; \
asm volatile("lock xadd %0, %1\n" : "+r"(ret__), "+m"(*mem) : : "cc", "memory"); \
ret__; \
})
#define atomic_add(i, mem) ({ asm volatile("lock addl %1,%0" : "+m"(*mem) : "ir"(i)); })
#endif /* ATOMIC_H__ */
| 1,617 | 52.933333 | 109 |
h
|
criu
|
criu-master/test/zdtm/static/aio01.c
|
#include <linux/aio_abi.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <aio.h>
#include "zdtmtst.h"
const char *test_doc = "Check head and tail restore correct";
const char *test_author = "Kirill Tkhai <[email protected]>";
struct aio_ring {
unsigned id; /* kernel internal index number */
unsigned nr; /* number of io_events */
unsigned head; /* Written to by userland or under ring_lock
* mutex by aio_read_events_ring(). */
unsigned tail;
unsigned magic;
unsigned compat_features;
unsigned incompat_features;
unsigned header_length; /* size of aio_ring */
struct io_event io_events[0];
}; /* 128 bytes + ring size */
int main(int argc, char **argv)
{
struct iocb iocb, *iocbp = &iocb;
volatile struct aio_ring *ring;
aio_context_t ctx = 0;
struct io_event event;
unsigned tail[2], head[2];
unsigned nr[2];
int i, fd, ret;
char buf[1];
test_init(argc, argv);
memset(&iocb, 0, sizeof(iocb));
if (syscall(__NR_io_setup, 64, &ctx) < 0) {
pr_perror("Can't setup io ctx");
return 1;
}
fd = open("/dev/null", O_WRONLY);
if (fd < 0) {
pr_perror("Can't open /dev/null");
return 1;
}
iocb.aio_fildes = fd;
iocb.aio_buf = (unsigned long)buf;
iocb.aio_nbytes = 1;
iocb.aio_lio_opcode = IOCB_CMD_PWRITE;
ring = (struct aio_ring *)ctx;
nr[0] = ring->nr;
for (i = 0; i < nr[0] + 2; i++) {
if (syscall(__NR_io_submit, ctx, 1, &iocbp) != 1) {
fail("Can't submit aio");
return 1;
}
if (!(i % 2))
continue;
ret = syscall(__NR_io_getevents, ctx, 0, 1, &event, NULL);
if (ret != 1) {
fail("Can't get event");
return 1;
}
}
tail[0] = *((volatile unsigned *)&ring->tail);
head[0] = *((volatile unsigned *)&ring->head);
test_msg("tail=%u, head=%u, nr=%u\n", tail[0], head[0], nr[0]);
test_daemon();
test_waitsig();
tail[1] = *((volatile unsigned *)&ring->tail);
head[1] = *((volatile unsigned *)&ring->head);
nr[1] = *((volatile unsigned *)&ring->nr);
test_msg("tail=%u, head=%u, nr=%u\n", tail[1], head[1], nr[1]);
if (tail[0] != tail[1] || head[0] != head[1] || nr[0] != nr[1]) {
fail("mismatch");
return 1;
}
if (syscall(__NR_io_submit, ctx, 1, &iocbp) != 1) {
fail("Can't submit aio");
return 1;
}
tail[1] = *((volatile unsigned *)&ring->tail);
head[1] = *((volatile unsigned *)&ring->head);
nr[1] = *((volatile unsigned *)&ring->nr);
test_msg("tail=%u, head=%u, nr=%u\n", tail[1], head[1], nr[1]);
if (tail[1] == tail[0] + 1 && head[1] == head[0] && nr[1] == nr[0])
pass();
else
fail("mismatch");
return 0;
}
| 2,640 | 21.965217 | 68 |
c
|
criu
|
criu-master/test/zdtm/static/auto_dev-ioctl.h
|
/*
* Copyright 2008 Red Hat, Inc. All rights reserved.
* Copyright 2008 Ian Kent <[email protected]>
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*/
#ifndef _LINUX_AUTO_DEV_IOCTL_H
#define _LINUX_AUTO_DEV_IOCTL_H
#include <linux/auto_fs.h>
#ifdef __KERNEL__
#include <linux/string.h>
#else
#include <string.h>
#endif /* __KERNEL__ */
#define AUTOFS_DEVICE_NAME "autofs"
#define AUTOFS_DEV_IOCTL_VERSION_MAJOR 1
#define AUTOFS_DEV_IOCTL_VERSION_MINOR 0
#define AUTOFS_DEVID_LEN 16
#define AUTOFS_DEV_IOCTL_SIZE sizeof(struct autofs_dev_ioctl)
/*
* An ioctl interface for autofs mount point control.
*/
struct args_protover {
__u32 version;
};
struct args_protosubver {
__u32 sub_version;
};
struct args_openmount {
__u32 devid;
};
struct args_ready {
__u32 token;
};
struct args_fail {
__u32 token;
__s32 status;
};
struct args_setpipefd {
__s32 pipefd;
};
struct args_timeout {
__u64 timeout;
};
struct args_requester {
__u32 uid;
__u32 gid;
};
struct args_expire {
__u32 how;
};
struct args_askumount {
__u32 may_umount;
};
struct args_ismountpoint {
union {
struct args_in {
__u32 type;
} in;
struct args_out {
__u32 devid;
__u32 magic;
} out;
};
};
/*
* All the ioctls use this structure.
* When sending a path size must account for the total length
* of the chunk of memory otherwise is is the size of the
* structure.
*/
struct autofs_dev_ioctl {
__u32 ver_major;
__u32 ver_minor;
__u32 size; /* total size of data passed in
* including this struct */
__s32 ioctlfd; /* automount command fd */
/* Command parameters */
union {
struct args_protover protover;
struct args_protosubver protosubver;
struct args_openmount openmount;
struct args_ready ready;
struct args_fail fail;
struct args_setpipefd setpipefd;
struct args_timeout timeout;
struct args_requester requester;
struct args_expire expire;
struct args_askumount askumount;
struct args_ismountpoint ismountpoint;
};
char path[0];
};
static inline void init_autofs_dev_ioctl(struct autofs_dev_ioctl *in)
{
memset(in, 0, sizeof(struct autofs_dev_ioctl));
in->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR;
in->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR;
in->size = sizeof(struct autofs_dev_ioctl);
in->ioctlfd = -1;
return;
}
/*
* If you change this make sure you make the corresponding change
* to autofs-dev-ioctl.c:lookup_ioctl()
*/
enum {
/* Get various version info */
AUTOFS_DEV_IOCTL_VERSION_CMD = 0x71,
AUTOFS_DEV_IOCTL_PROTOVER_CMD,
AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD,
/* Open mount ioctl fd */
AUTOFS_DEV_IOCTL_OPENMOUNT_CMD,
/* Close mount ioctl fd */
AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD,
/* Mount/expire status returns */
AUTOFS_DEV_IOCTL_READY_CMD,
AUTOFS_DEV_IOCTL_FAIL_CMD,
/* Activate/deactivate autofs mount */
AUTOFS_DEV_IOCTL_SETPIPEFD_CMD,
AUTOFS_DEV_IOCTL_CATATONIC_CMD,
/* Expiry timeout */
AUTOFS_DEV_IOCTL_TIMEOUT_CMD,
/* Get mount last requesting uid and gid */
AUTOFS_DEV_IOCTL_REQUESTER_CMD,
/* Check for eligible expire candidates */
AUTOFS_DEV_IOCTL_EXPIRE_CMD,
/* Request busy status */
AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD,
/* Check if path is a mountpoint */
AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD,
};
#define AUTOFS_IOCTL 0x93
#define AUTOFS_DEV_IOCTL_VERSION _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_VERSION_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_PROTOVER _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_PROTOVER_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_PROTOSUBVER _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_OPENMOUNT _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_CLOSEMOUNT _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_READY _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_READY_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_FAIL _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_FAIL_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_SETPIPEFD _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_CATATONIC _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_CATATONIC_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_TIMEOUT _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_TIMEOUT_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_REQUESTER _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_REQUESTER_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_EXPIRE _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_EXPIRE_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_ASKUMOUNT _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, struct autofs_dev_ioctl)
#define AUTOFS_DEV_IOCTL_ISMOUNTPOINT _IOWR(AUTOFS_IOCTL, AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, struct autofs_dev_ioctl)
#endif /* _LINUX_AUTO_DEV_IOCTL_H */
| 5,006 | 23.787129 | 117 |
h
|
criu
|
criu-master/test/zdtm/static/autofs.c
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/vfs.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <linux/auto_fs4.h>
#include <linux/magic.h>
#include "zdtmtst.h"
#include "auto_dev-ioctl.h"
const char *test_doc = "Autofs (v5) migration test";
const char *test_author = "Stanislav Kinsburskii <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
#define AUTOFS_DEV "/dev/autofs"
#define INDIRECT_MNT_DIR "mnt"
int autofs_dev;
task_waiter_t t;
static char *xvstrcat(char *str, const char *fmt, va_list args)
{
size_t offset = 0, delta;
int ret;
char *new;
va_list tmp;
if (str)
offset = strlen(str);
delta = strlen(fmt) * 2;
do {
ret = -ENOMEM;
new = realloc(str, offset + delta);
if (new) {
str = new;
va_copy(tmp, args);
ret = vsnprintf(new + offset, delta, fmt, tmp);
va_end(tmp);
if (ret >= delta) {
/* NOTE: vsnprintf returns the amount of bytes
* * to allocate. */
delta = ret + 1;
ret = 0;
}
}
} while (ret == 0);
if (ret == -ENOMEM) {
/* realloc failed. We must release former string */
pr_err("Failed to allocate string\n");
free(str);
} else if (ret < 0) {
/* vsnprintf failed */
pr_err("Failed to print string\n");
free(new);
new = NULL;
}
return new;
}
char *xstrcat(char *str, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
str = xvstrcat(str, fmt, args);
va_end(args);
return str;
}
char *xsprintf(const char *fmt, ...)
{
va_list args;
char *str;
va_start(args, fmt);
str = xvstrcat(NULL, fmt, args);
va_end(args);
return str;
}
struct autofs_params {
const char *mountpoint;
int (*create)(struct autofs_params *p);
int (*setup)(struct autofs_params *p);
int (*check)(struct autofs_params *p);
int (*reap)(struct autofs_params *p);
const unsigned type;
int fd;
struct stat fd_stat;
void (*onexit)(void);
const int close_pipe;
pid_t pid;
};
struct autofs_params *my_type;
static int stop;
static int setup_direct(struct autofs_params *p)
{
char *path;
path = xsprintf("%s/%s/direct_file", dirname, p->mountpoint);
if (!path) {
pr_err("failed to allocate path\n");
return -ENOMEM;
}
p->fd = open(path, O_CREAT | O_EXCL, 0600);
if (p->fd < 0) {
pr_perror("%d: failed to open file %s", getpid(), path);
return -errno;
}
if (fstat(p->fd, &p->fd_stat)) {
pr_perror("%d: failed to stat %s", getpid(), path);
return -errno;
}
free(path);
return 0;
}
static int setup_indirect(struct autofs_params *p)
{
char *path;
path = xsprintf("%s/%s/%s/indirect_file", dirname, p->mountpoint, INDIRECT_MNT_DIR);
if (!path) {
pr_err("failed to allocate path\n");
return -ENOMEM;
}
p->fd = open(path, O_CREAT | O_EXCL, 0600);
if (p->fd < 0) {
pr_perror("%d: failed to open file %s", getpid(), path);
return -errno;
}
if (fstat(p->fd, &p->fd_stat)) {
pr_perror("%d: failed to stat %s", getpid(), path);
return -errno;
}
free(path);
return 0;
}
static int umount_fs(const char *mountpoint, int magic)
{
struct statfs buf;
if (statfs(mountpoint, &buf)) {
pr_perror("%s: failed to statfs", mountpoint);
return -errno;
}
if (buf.f_type == magic) {
if (umount(mountpoint) < 0) {
pr_perror("failed to umount %s tmpfs", mountpoint);
return -errno;
}
}
return 0;
}
static int check_fd(struct autofs_params *p)
{
struct stat st;
int ret = 0;
if (fstat(p->fd, &st)) {
pr_perror("failed to stat fd %d", p->fd);
return -errno;
}
if (st.st_dev != p->fd_stat.st_dev) {
skip("%s: st_dev differs: %llu != %llu "
"(waiting for \"device namespaces\")",
p->mountpoint, (long long unsigned)st.st_dev, (long long unsigned)p->fd_stat.st_dev);
// ret++;
}
if (st.st_mode != p->fd_stat.st_mode) {
pr_err("%s: st_mode differs: 0%o != 0%o\n", p->mountpoint, st.st_mode, p->fd_stat.st_mode);
ret++;
}
if (st.st_nlink != p->fd_stat.st_nlink) {
pr_err("%s: st_nlink differs: %ld != %ld\n", p->mountpoint, (long)st.st_nlink,
(long)p->fd_stat.st_nlink);
ret++;
}
if (st.st_uid != p->fd_stat.st_uid) {
pr_err("%s: st_uid differs: %u != %u\n", p->mountpoint, st.st_uid, p->fd_stat.st_uid);
ret++;
}
if (st.st_gid != p->fd_stat.st_gid) {
pr_err("%s: st_gid differs: %u != %u\n", p->mountpoint, st.st_gid, p->fd_stat.st_gid);
ret++;
}
if (st.st_rdev != p->fd_stat.st_rdev) {
pr_err("%s: st_rdev differs: %lld != %lld\n", p->mountpoint, (long long)st.st_rdev,
(long long)p->fd_stat.st_rdev);
ret++;
}
if (st.st_size != p->fd_stat.st_size) {
pr_err("%s: st_size differs: %lld != %lld\n", p->mountpoint, (long long)st.st_size,
(long long)p->fd_stat.st_size);
ret++;
}
if (st.st_blksize != p->fd_stat.st_blksize) {
pr_err("%s: st_blksize differs %lld != %lld:\n", p->mountpoint, (long long)st.st_blksize,
(long long)p->fd_stat.st_blksize);
ret++;
}
if (st.st_blocks != p->fd_stat.st_blocks) {
pr_err("%s: st_blocks differs: %lld != %lld\n", p->mountpoint, (long long)st.st_blocks,
(long long)p->fd_stat.st_blocks);
ret++;
}
return ret;
}
static int check_automount(struct autofs_params *p)
{
int err;
char *mountpoint;
err = check_fd(p);
if (err) {
pr_err("%s: opened file descriptor wasn't migrated properly\n", p->mountpoint);
return err;
}
if (p->type == AUTOFS_TYPE_DIRECT)
mountpoint = xsprintf("%s/%s", dirname, p->mountpoint);
else if (p->type == AUTOFS_TYPE_INDIRECT)
mountpoint = xsprintf("%s/%s/%s", dirname, p->mountpoint, INDIRECT_MNT_DIR);
else {
pr_err("Unknown autofs type: %d\n", p->type);
return -EINVAL;
}
if (!mountpoint) {
pr_err("failed to allocate string\n");
return -ENOMEM;
}
if (close(p->fd)) {
pr_err("%s: failed to close fd %d\n", p->mountpoint, p->fd);
return -errno;
}
err = umount_fs(mountpoint, TMPFS_MAGIC);
if (err)
return err;
free(mountpoint);
mountpoint = NULL;
err = p->setup(p);
if (err) {
pr_err("autofs doesn't workafter restore\n");
return err;
}
if (close(p->fd)) {
pr_perror("mountpoint failed to close fd %d", p->fd);
return -errno;
}
return 0;
}
static int autofs_dev_open(void)
{
int fd;
if (access(AUTOFS_DEV, R_OK | W_OK)) {
pr_perror("Device /dev/autofs is not accessible");
return -1;
}
fd = open(AUTOFS_DEV, O_RDONLY);
if (fd == -1) {
pr_perror("failed to open /dev/autofs");
return -errno;
}
return fd;
}
static int autofs_open_mount(int devid, const char *mountpoint)
{
struct autofs_dev_ioctl *param;
size_t size;
int ret;
size = sizeof(struct autofs_dev_ioctl) + strlen(mountpoint) + 1;
param = malloc(size);
init_autofs_dev_ioctl(param);
param->size = size;
param->ioctlfd = -1;
param->openmount.devid = devid;
strcpy(param->path, mountpoint);
if (ioctl(autofs_dev, AUTOFS_DEV_IOCTL_OPENMOUNT, param) < 0) {
pr_perror("failed to open autofs mount %s", mountpoint);
ret = -errno;
goto out;
}
ret = param->ioctlfd;
out:
free(param);
return ret;
}
static int autofs_report_result(int token, int devid, const char *mountpoint, int result)
{
int ioctl_fd;
struct autofs_dev_ioctl param;
int err;
ioctl_fd = autofs_open_mount(devid, mountpoint);
if (ioctl_fd < 0) {
pr_err("failed to open autofs mountpoint %s\n", mountpoint);
return ioctl_fd;
}
init_autofs_dev_ioctl(¶m);
param.ioctlfd = ioctl_fd;
if (result) {
param.fail.token = token;
param.fail.status = result;
} else
param.ready.token = token;
err = ioctl(autofs_dev, result ? AUTOFS_DEV_IOCTL_FAIL : AUTOFS_DEV_IOCTL_READY, ¶m);
if (err) {
pr_perror("failed to report result to autofs mountpoint %s", mountpoint);
err = -errno;
}
close(ioctl_fd);
return err;
}
static int mount_tmpfs(const char *mountpoint)
{
struct statfs buf;
if (statfs(mountpoint, &buf)) {
pr_perror("failed to statfs %s", mountpoint);
return -errno;
}
if (buf.f_type == TMPFS_MAGIC)
return 0;
if (mount("autofs_test", mountpoint, "tmpfs", 0, "size=1M") < 0) {
pr_perror("failed to mount tmpfs to %s", mountpoint);
return -errno;
}
return 0;
}
static int autofs_mount_direct(const char *mountpoint, const struct autofs_v5_packet *packet)
{
int err;
const char *direct_mnt = mountpoint;
err = mount_tmpfs(direct_mnt);
if (err)
pr_err("%d: failed to mount direct autofs mountpoint\n", getpid());
return err;
}
static int autofs_mount_indirect(const char *mountpoint, const struct autofs_v5_packet *packet)
{
char *indirect_mnt;
int err;
indirect_mnt = xsprintf("%s/%s", mountpoint, packet->name);
if (!indirect_mnt) {
pr_err("failed to allocate indirect mount path\n");
return -ENOMEM;
}
if ((mkdir(indirect_mnt, 0755) < 0) && (errno != EEXIST)) {
pr_perror("failed to create %s directory", indirect_mnt);
return -errno;
}
err = mount_tmpfs(indirect_mnt);
if (err)
pr_err("%d: failed to mount indirect autofs mountpoint\n", getpid());
return err;
}
static int automountd_serve(const char *mountpoint, struct autofs_params *p, const union autofs_v5_packet_union *packet)
{
const struct autofs_v5_packet *v5_packet = &packet->v5_packet;
int err, res;
switch (packet->hdr.type) {
case autofs_ptype_missing_indirect:
res = autofs_mount_indirect(mountpoint, v5_packet);
break;
case autofs_ptype_missing_direct:
res = autofs_mount_direct(mountpoint, v5_packet);
break;
case autofs_ptype_expire_indirect:
pr_err("%d: expire request for indirect mount %s?\n", getpid(), v5_packet->name);
return -EINVAL;
case autofs_ptype_expire_direct:
pr_err("%d: expire request for direct mount?\n", getpid());
return -EINVAL;
default:
pr_err("unknown request type: %d\n", packet->hdr.type);
return -EINVAL;
}
err = autofs_report_result(v5_packet->wait_queue_token, v5_packet->dev, mountpoint, res);
if (err)
return err;
return res;
}
static int automountd_loop(int pipe, const char *mountpoint, struct autofs_params *param)
{
union autofs_v5_packet_union *packet;
ssize_t bytes;
size_t psize = sizeof(*packet);
int err = 0;
packet = malloc(psize);
if (!packet) {
pr_err("failed to allocate autofs packet\n");
return -ENOMEM;
}
while (!stop && !err) {
memset(packet, 0, psize);
bytes = read(pipe, packet, psize);
if (bytes < 0) {
if (errno != EINTR) {
pr_perror("failed to read packet");
return -errno;
}
continue;
}
if (bytes != psize) {
pr_err("read less than expected: %zd < %zd\n", bytes, psize);
return -EINVAL;
}
err = automountd_serve(mountpoint, param, packet);
if (err)
pr_err("request to autofs failed: %d\n", err);
}
return err;
}
static int automountd(struct autofs_params *p, int control_fd)
{
int pipes[2];
char *autofs_path;
char *options;
int ret = -1;
char *type;
my_type = p;
if (p->onexit)
atexit(p->onexit);
autofs_path = xsprintf("%s/%s", dirname, p->mountpoint);
if (!autofs_path) {
pr_err("failed to allocate autofs path\n");
goto err;
}
if (pipe(pipes) < 0) {
pr_perror("%d: failed to create pipe", getpid());
goto err;
}
if (setpgrp() < 0) {
pr_perror("failed to become a process group leader");
goto err;
}
switch (p->type) {
case AUTOFS_TYPE_DIRECT:
type = "direct";
break;
case AUTOFS_TYPE_INDIRECT:
type = "indirect";
break;
case AUTOFS_TYPE_OFFSET:
type = "offset";
break;
default:
pr_err("unknown autofs type: %d\n", p->type);
return -EINVAL;
}
options = xsprintf("fd=%d,pgrp=%d,minproto=5,maxproto=5,%s", pipes[1], getpgrp(), type);
if (!options) {
pr_err("failed to allocate autofs options\n");
goto err;
}
if (mkdir(autofs_path, 0600) < 0) {
pr_perror("failed to create %s", autofs_path);
test_msg("cwd: %s\n", get_current_dir_name());
goto err;
}
if (mount("autofs_test", autofs_path, "autofs", 0, options) < 0) {
pr_perror("failed to mount autofs with options \"%s\"", options);
goto err;
}
if (p->close_pipe)
close(pipes[1]);
ret = 0;
if (write(control_fd, &ret, sizeof(ret)) != sizeof(ret)) {
pr_perror("failed to send result");
goto err;
}
close(control_fd);
task_waiter_complete(&t, getpid());
return automountd_loop(pipes[0], autofs_path, p);
err:
if (write(control_fd, &ret, sizeof(ret) != sizeof(ret))) {
pr_perror("failed to send result");
return -errno;
}
return ret;
}
static int start_automounter(struct autofs_params *p)
{
int pid;
int control_fd[2];
ssize_t bytes;
int ret;
if (pipe(control_fd) < 0) {
pr_perror("failed to create control_fd pipe");
return -errno;
}
pid = test_fork();
switch (pid) {
case -1:
pr_perror("failed to fork");
return -1;
case 0:
close(control_fd[0]);
exit(automountd(p, control_fd[1]));
}
task_waiter_wait4(&t, pid);
p->pid = pid;
close(control_fd[1]);
bytes = read(control_fd[0], &ret, sizeof(ret));
close(control_fd[0]);
if (bytes < 0) {
pr_perror("failed to get start result");
return -errno;
}
if (bytes != sizeof(ret)) {
pr_err("received less than expected: %zu. Child %d died?\n", bytes, p->pid);
return -EINVAL;
}
return ret;
}
static void do_stop(int sig)
{
stop = 1;
}
static int reap_child(struct autofs_params *p)
{
int status;
int pid = p->pid;
if (kill(pid, SIGUSR2)) {
pr_perror("failed to kill child %d", pid);
return -errno;
}
if (waitpid(pid, &status, 0) == -1) {
pr_perror("failed to collect child %d", pid);
return -errno;
}
if (WIFSIGNALED(status)) {
pr_err("Child was killed by %d\n", WTERMSIG(status));
return -1;
}
return WEXITSTATUS(status);
}
static int reap_catatonic(struct autofs_params *p)
{
char *mountpoint;
int err;
mountpoint = xsprintf("%s/%s", dirname, p->mountpoint);
if (!mountpoint) {
pr_err("failed to allocate string\n");
return -ENOMEM;
}
err = umount_fs(mountpoint, AUTOFS_SUPER_MAGIC);
if (!err) {
if (rmdir(mountpoint) < 0) {
skip("failed to remove %s directory: %s\n", mountpoint, strerror(errno));
err = -errno;
}
}
return err;
}
static int setup_catatonic(struct autofs_params *p)
{
char *path;
path = xsprintf("%s/%s/file", dirname, p->mountpoint);
if (!path) {
pr_err("failed to allocate path\n");
return -ENOMEM;
}
p->fd = open(path, O_CREAT | O_EXCL, 0600);
if (p->fd >= 0) {
pr_perror("%d: was able to open file %s on catatonic mount", getpid(), path);
return -EINVAL;
}
free(path);
return 0;
}
static int check_catatonic(struct autofs_params *p)
{
char *mountpoint;
struct statfs buf;
mountpoint = xsprintf("%s/%s", dirname, p->mountpoint);
if (!mountpoint) {
pr_err("failed to allocate path\n");
return -ENOMEM;
}
if (statfs(mountpoint, &buf)) {
pr_perror("%s: failed to statfs", mountpoint);
return -errno;
}
if (buf.f_type != AUTOFS_SUPER_MAGIC) {
pr_err("Non-autofs mount on path %s\n", mountpoint);
return -EINVAL;
}
return setup_catatonic(p);
}
static int create_catatonic(struct autofs_params *p)
{
int err;
int status;
err = start_automounter(p);
if (err)
return err;
if (kill(p->pid, SIGKILL)) {
pr_perror("failed to kill child %d", p->pid);
return -errno;
}
if (waitpid(p->pid, &status, 0) == -1) {
pr_perror("failed to collect child %d", p->pid);
return -errno;
}
return 0;
}
static void test_exit(void)
{
if (rmdir(dirname) < 0)
skip("failed to remove %s directory: %s\n", dirname, strerror(errno));
}
typedef enum { AUTOFS_START, AUTOFS_SETUP, AUTOFS_CHECK, AUTOFS_STOP } autfs_test_action;
static int test_action(autfs_test_action act, struct autofs_params *p)
{
int ret = 0;
while (p->mountpoint) {
int (*action)(struct autofs_params * p);
switch (act) {
case AUTOFS_START:
action = p->create;
break;
case AUTOFS_SETUP:
action = p->setup;
break;
case AUTOFS_CHECK:
action = p->check;
break;
case AUTOFS_STOP:
action = p->reap;
break;
default:
pr_err("unknown action: %d\n", act);
return -1;
}
if (action && action(p))
ret++;
p++;
}
return ret;
}
static void direct_exit(void)
{
struct autofs_params *p = my_type;
char *mountpoint;
mountpoint = xsprintf("%s/%s", dirname, p->mountpoint);
if (!mountpoint) {
pr_err("failed to allocate string\n");
return;
}
if (umount_fs(mountpoint, TMPFS_MAGIC))
return;
if (umount_fs(mountpoint, AUTOFS_SUPER_MAGIC))
return;
if (rmdir(mountpoint) < 0)
skip("failed to remove %s directory: %s\n", mountpoint, strerror(errno));
}
static void indirect_exit(void)
{
struct autofs_params *p = my_type;
char *mountpoint, *tmpfs;
mountpoint = xsprintf("%s/%s", dirname, p->mountpoint);
if (!mountpoint) {
pr_err("failed to allocate string\n");
return;
}
tmpfs = xsprintf("%s/%s/%s", dirname, p->mountpoint, INDIRECT_MNT_DIR);
if (!tmpfs) {
pr_err("failed to allocate string\n");
return;
}
if (!access(tmpfs, F_OK)) {
if (umount_fs(tmpfs, TMPFS_MAGIC))
return;
}
if (umount_fs(mountpoint, AUTOFS_SUPER_MAGIC))
return;
if (rmdir(mountpoint) < 0)
skip("failed to remove %s directory: %s\n", mountpoint, strerror(errno));
}
enum autofs_tests {
AUTOFS_DIRECT,
AUTOFS_INDIRECT,
AUTOFS_CATATONIC,
};
struct autofs_params autofs_types[] = {
[AUTOFS_DIRECT] = {
.mountpoint = "direct",
.create = start_automounter,
.setup = setup_direct,
.check = check_automount,
.reap = reap_child,
.type = AUTOFS_TYPE_DIRECT,
.fd = -1,
.onexit = direct_exit,
.close_pipe = 1,
},
[AUTOFS_INDIRECT] = {
.mountpoint = "indirect",
.create = start_automounter,
.setup = setup_indirect,
.check = check_automount,
.reap = reap_child,
.type = AUTOFS_TYPE_INDIRECT,
.fd = -1,
.onexit = indirect_exit,
.close_pipe = 0,
},
[AUTOFS_CATATONIC] = {
.mountpoint = "catatonic",
.create = create_catatonic,
.setup = setup_catatonic,
.check = check_catatonic,
.reap = reap_catatonic,
.type = AUTOFS_TYPE_DIRECT,
.onexit = NULL,
.fd = -1,
.close_pipe = 1,
},
{ NULL, NULL, NULL, NULL }
};
int main(int argc, char **argv)
{
struct sigaction act = {
.sa_handler = do_stop,
/*
* SIGUSR2 is used to interrupt system calls, so SA_RESTART
* isn't set.
*/
};
int ret = 0;
test_init(argc, argv);
task_waiter_init(&t);
if (mkdir(dirname, 0777) < 0) {
pr_perror("failed to create %s directory", dirname);
return -1;
}
autofs_dev = autofs_dev_open();
if (autofs_dev < 0)
return -1;
if (sigaction(SIGUSR2, &act, NULL) < 0) {
pr_perror("Failed to set SIGUSR2 handler");
return -1;
}
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
pr_perror("Failed to set SIGPIPE handler");
return -1;
}
if (test_action(AUTOFS_START, autofs_types)) {
pr_err("AUTOFS_START action failed\n");
ret++;
goto err;
}
close(autofs_dev);
atexit(test_exit);
if (test_action(AUTOFS_SETUP, autofs_types)) {
pr_err("AUTOFS_SETUP action failed\n");
ret++;
goto err;
}
test_daemon();
test_waitsig();
if (test_action(AUTOFS_CHECK, autofs_types)) {
pr_err("AUTOFS_CHECK action failed\n");
ret++;
}
err:
if (test_action(AUTOFS_STOP, autofs_types)) {
pr_err("AUTOFS_STOP action failed\n");
ret++;
}
if (ret) {
fail();
return ret;
}
pass();
return 0;
}
| 19,181 | 20.079121 | 120 |
c
|
criu
|
criu-master/test/zdtm/static/bind-mount.c
|
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include "zdtmtst.h"
const char *test_doc = "Check bind-mounts";
const char *test_author = "Pavel Emelianov <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
int main(int argc, char **argv)
{
char test_dir[PATH_MAX], test_bind[PATH_MAX];
char test_file[PATH_MAX], test_bind_file[PATH_MAX];
int fd;
test_init(argc, argv);
mkdir(dirname, 0700);
snprintf(test_dir, sizeof(test_dir), "%s/test", dirname);
snprintf(test_bind, sizeof(test_bind), "%s/bind", dirname);
snprintf(test_file, sizeof(test_file), "%s/test/test.file", dirname);
snprintf(test_bind_file, sizeof(test_bind_file), "%s/bind/test.file", dirname);
mkdir(test_dir, 0700);
mkdir(test_bind, 0700);
if (mount(test_dir, test_bind, NULL, MS_BIND, NULL)) {
pr_perror("Unable to mount %s to %s", test_dir, test_bind);
return 1;
}
test_daemon();
test_waitsig();
fd = open(test_file, O_CREAT | O_WRONLY | O_EXCL, 0600);
if (fd < 0) {
pr_perror("Unable to open %s", test_file);
return 1;
}
close(fd);
if (access(test_bind_file, F_OK)) {
pr_perror("%s doesn't exist", test_bind_file);
return 1;
}
if (umount(test_bind)) {
pr_perror("Unable to umount %s", test_bind);
return 1;
}
pass();
return 0;
}
| 1,397 | 21.190476 | 80 |
c
|
criu
|
criu-master/test/zdtm/static/bpf_array.c
|
#include <bpf/bpf.h>
#include <sys/mman.h>
#include "zdtmtst.h"
#include "bpfmap_zdtm.h"
#ifndef LIBBPF_OPTS
#define LIBBPF_OPTS DECLARE_LIBBPF_OPTS
#define LEGACY_LIBBPF /* Using libbpf < 0.7 */
#endif
const char *test_doc = "Check that data and meta-data for BPF_MAP_TYPE_ARRAY"
"is correctly restored";
const char *test_author = "Abhishek Vijeev <[email protected]>";
static int map_batch_update(int map_fd, uint32_t max_entries, int *keys, int *values)
{
int i, ret;
LIBBPF_OPTS(bpf_map_batch_opts, opts);
for (i = 0; i < max_entries; i++) {
keys[i] = i;
values[i] = i + 1;
}
ret = bpf_map_update_batch(map_fd, keys, values, &max_entries, &opts);
if (ret && errno != ENOENT) {
pr_perror("Can't load key-value pairs to BPF map fd");
return -1;
}
return 0;
}
static int map_batch_verify(int *visited, uint32_t max_entries, int *keys, int *values)
{
int i;
memset(visited, 0, max_entries * sizeof(*visited));
for (i = 0; i < max_entries; i++) {
if (keys[i] + 1 != values[i]) {
pr_err("Key/value checking error: i=%d, key=%d, value=%d\n", i, keys[i], values[i]);
return -1;
}
visited[i] = 1;
}
for (i = 0; i < max_entries; i++) {
if (visited[i] != 1) {
pr_err("Visited checking error: keys array at index %d missing\n", i);
return -1;
}
}
return 0;
}
int main(int argc, char **argv)
{
uint32_t batch, count;
int map_fd;
int *keys = NULL, *values = NULL, *visited = NULL;
const uint32_t max_entries = 10;
int ret;
struct bpf_map_info old_map_info = {};
struct bpf_map_info new_map_info = {};
struct bpfmap_fdinfo_obj old_fdinfo = {};
struct bpfmap_fdinfo_obj new_fdinfo = {};
uint32_t info_len = sizeof(struct bpf_map_info);
#ifdef LEGACY_LIBBPF
struct bpf_create_map_attr xattr = {
.name = "array_test_map",
.map_type = BPF_MAP_TYPE_ARRAY,
.key_size = sizeof(int),
.value_size = sizeof(int),
.max_entries = max_entries,
.map_flags = BPF_F_NUMA_NODE,
};
#else
LIBBPF_OPTS(bpf_map_create_opts, bpf_mapfd_opts, .map_flags = BPF_F_NUMA_NODE);
#endif
LIBBPF_OPTS(bpf_map_batch_opts, opts);
keys = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
values = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
visited = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
if ((keys == MAP_FAILED) || (values == MAP_FAILED) || (visited == MAP_FAILED)) {
pr_perror("Can't mmap()");
goto err;
}
test_init(argc, argv);
#ifdef LEGACY_LIBBPF
map_fd = bpf_create_map_xattr(&xattr);
#else
map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "array_test_map", sizeof(int), sizeof(int), max_entries,
&bpf_mapfd_opts);
#endif
if (map_fd == -1) {
pr_perror("Can't create BPF map");
goto err;
}
if (map_batch_update(map_fd, max_entries, keys, values))
goto err;
ret = bpf_map_freeze(map_fd);
if (ret) {
pr_perror("Could not freeze map");
goto err;
}
ret = bpf_obj_get_info_by_fd(map_fd, &old_map_info, &info_len);
if (ret) {
pr_perror("Could not get old map info");
goto err;
}
ret = parse_bpfmap_fdinfo(map_fd, &old_fdinfo, 8);
if (ret) {
pr_perror("Could not parse old map fdinfo from procfs");
goto err;
}
test_daemon();
test_waitsig();
ret = bpf_obj_get_info_by_fd(map_fd, &new_map_info, &info_len);
if (ret) {
pr_perror("Could not get new map info");
goto err;
}
ret = parse_bpfmap_fdinfo(map_fd, &new_fdinfo, 8);
if (ret) {
pr_perror("Could not parse new map fdinfo from procfs");
goto err;
}
if (cmp_bpf_map_info(&old_map_info, &new_map_info)) {
pr_err("bpf_map_info mismatch\n");
goto err;
}
if (cmp_bpfmap_fdinfo(&old_fdinfo, &new_fdinfo)) {
pr_err("bpfmap fdinfo mismatch\n");
goto err;
}
memset(keys, 0, max_entries * sizeof(*keys));
memset(values, 0, max_entries * sizeof(*values));
ret = bpf_map_lookup_batch(map_fd, NULL, &batch, keys, values, &count, &opts);
if (ret && errno != ENOENT) {
pr_perror("Can't perform a batch lookup on BPF map");
goto err;
}
if (map_batch_verify(visited, max_entries, keys, values))
goto err;
munmap(keys, max_entries * sizeof(int));
munmap(values, max_entries * sizeof(int));
munmap(visited, max_entries * sizeof(int));
pass();
return 0;
err:
munmap(keys, max_entries * sizeof(int));
munmap(values, max_entries * sizeof(int));
munmap(visited, max_entries * sizeof(int));
fail();
return 1;
}
| 4,465 | 23.811111 | 107 |
c
|
criu
|
criu-master/test/zdtm/static/bpf_hash.c
|
#include <sys/mman.h>
#include <bpf/bpf.h>
#include "zdtmtst.h"
#include "bpfmap_zdtm.h"
#ifndef LIBBPF_OPTS
#define LIBBPF_OPTS DECLARE_LIBBPF_OPTS
#define LEGACY_LIBBPF /* Using libbpf < 0.7 */
#endif
const char *test_doc = "Check that data and meta-data for BPF_MAP_TYPE_HASH"
"is correctly restored";
const char *test_author = "Abhishek Vijeev <[email protected]>";
static int map_batch_update(int map_fd, uint32_t max_entries, int *keys, int *values)
{
int ret;
LIBBPF_OPTS(bpf_map_batch_opts, opts);
for (int i = 0; i < max_entries; i++) {
keys[i] = i + 1;
values[i] = i + 2;
}
ret = bpf_map_update_batch(map_fd, keys, values, &max_entries, &opts);
if (ret && errno != ENOENT) {
pr_perror("Can't load key-value pairs to BPF map");
return -1;
}
return 0;
}
static int map_batch_verify(int *visited, uint32_t max_entries, int *keys, int *values)
{
memset(visited, 0, max_entries * sizeof(*visited));
for (int i = 0; i < max_entries; i++) {
if (keys[i] + 1 != values[i]) {
pr_err("Key/value checking error: i=%d, key=%d, value=%d\n", i, keys[i], values[i]);
return -1;
}
visited[i] = 1;
}
for (int i = 0; i < max_entries; i++) {
if (visited[i] != 1) {
pr_err("Visited checking error: keys array at index %d missing\n", i);
return -1;
}
}
return 0;
}
int main(int argc, char **argv)
{
uint32_t batch, count;
int map_fd;
int *keys = NULL, *values = NULL, *visited = NULL;
const uint32_t max_entries = 10;
int ret;
struct bpf_map_info old_map_info = {};
struct bpf_map_info new_map_info = {};
struct bpfmap_fdinfo_obj old_fdinfo = {};
struct bpfmap_fdinfo_obj new_fdinfo = {};
uint32_t info_len = sizeof(struct bpf_map_info);
#ifdef LEGACY_LIBBPF
struct bpf_create_map_attr xattr = {
.name = "hash_test_map",
.map_type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(int),
.value_size = sizeof(int),
.max_entries = max_entries,
.map_flags = BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE,
};
#else
LIBBPF_OPTS(bpf_map_create_opts, bpf_mapfd_opts, .map_flags = BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE);
#endif
LIBBPF_OPTS(bpf_map_batch_opts, opts);
keys = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
values = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
visited = mmap(NULL, max_entries * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
if ((keys == MAP_FAILED) || (values == MAP_FAILED) || (visited == MAP_FAILED)) {
pr_perror("Can't mmap()");
goto err;
}
test_init(argc, argv);
#ifdef LEGACY_LIBBPF
map_fd = bpf_create_map_xattr(&xattr);
#else
map_fd = bpf_map_create(BPF_MAP_TYPE_HASH, "hash_test_map", sizeof(int), sizeof(int), max_entries,
&bpf_mapfd_opts);
#endif
if (!map_fd) {
pr_perror("Can't create BPF map");
goto err;
}
if (map_batch_update(map_fd, max_entries, keys, values))
goto err;
ret = bpf_map_freeze(map_fd);
if (ret) {
pr_perror("Could not freeze map");
goto err;
}
ret = bpf_obj_get_info_by_fd(map_fd, &old_map_info, &info_len);
if (ret) {
pr_perror("Could not get old map info");
goto err;
}
ret = parse_bpfmap_fdinfo(map_fd, &old_fdinfo, 8);
if (ret) {
pr_perror("Could not parse old map fdinfo from procfs");
goto err;
}
test_daemon();
test_waitsig();
ret = bpf_obj_get_info_by_fd(map_fd, &new_map_info, &info_len);
if (ret) {
pr_perror("Could not get new map info");
goto err;
}
ret = parse_bpfmap_fdinfo(map_fd, &new_fdinfo, 8);
if (ret) {
pr_perror("Could not parse new map fdinfo from procfs");
goto err;
}
if (cmp_bpf_map_info(&old_map_info, &new_map_info)) {
pr_err("bpf_map_info mismatch\n");
goto err;
}
if (cmp_bpfmap_fdinfo(&old_fdinfo, &new_fdinfo)) {
pr_err("bpfmap fdinfo mismatch\n");
goto err;
}
memset(keys, 0, max_entries * sizeof(*keys));
memset(values, 0, max_entries * sizeof(*values));
ret = bpf_map_lookup_batch(map_fd, NULL, &batch, keys, values, &count, &opts);
if (ret && errno != ENOENT) {
pr_perror("Can't perform a batch lookup on BPF map");
goto err;
}
if (map_batch_verify(visited, max_entries, keys, values))
goto err;
munmap(keys, max_entries * sizeof(int));
munmap(values, max_entries * sizeof(int));
munmap(visited, max_entries * sizeof(int));
pass();
return 0;
err:
munmap(keys, max_entries * sizeof(int));
munmap(values, max_entries * sizeof(int));
munmap(visited, max_entries * sizeof(int));
fail();
return 1;
}
| 4,495 | 24.40113 | 107 |
c
|
criu
|
criu-master/test/zdtm/static/bridge.c
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/limits.h>
#include <signal.h>
#include <arpa/inet.h>
#include <net/if.h>
#include "zdtmtst.h"
const char *test_doc = "check that empty bridges are c/r'd correctly";
const char *test_author = "Tycho Andersen <[email protected]>";
#define BRIDGE_NAME "zdtmbr0"
int add_bridge(void)
{
if (system("ip link add " BRIDGE_NAME " type bridge"))
return -1;
if (system("ip addr add 10.0.55.55/32 dev " BRIDGE_NAME))
return -1;
/* use a link local address so we can test scope_id change */
if (system("ip addr add fe80:4567::1/64 nodad dev " BRIDGE_NAME))
return -1;
if (system("ip link set " BRIDGE_NAME " up"))
return -1;
return 0;
}
int del_bridge(void)
{
/* don't check for errors, let's try to make sure it's deleted */
system("ip link set " BRIDGE_NAME " down");
if (system("ip link del " BRIDGE_NAME))
return -1;
return 0;
}
int main(int argc, char **argv)
{
int ret = 1;
struct sockaddr_in6 addr;
int sk;
test_init(argc, argv);
if (add_bridge() < 0)
return 1;
sk = socket(AF_INET6, SOCK_DGRAM, 0);
if (sk < 0) {
fail("can't get socket");
goto out;
}
memset(&addr, 0, sizeof(addr));
addr.sin6_port = htons(0);
addr.sin6_family = AF_INET6;
if (inet_pton(AF_INET6, "fe80:4567::1", &addr.sin6_addr) < 0) {
fail("can't convert inet6 addr");
goto out;
}
addr.sin6_scope_id = if_nametoindex(BRIDGE_NAME);
if (bind(sk, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
fail("can't bind");
goto out;
}
/* Here, we grep for inet because some of the IPV6 DAD stuff can be
* racy, and all we really care about is that the bridge got restored
* with the right MAC, since we know DAD will succeed eventually.
*
* (I got this race with zdtm.py, but not with zdtm.sh; not quite sure
* what the environment difference is/was.)
*/
if (system("ip addr list dev " BRIDGE_NAME " | grep inet | sort > bridge.dump.test")) {
pr_perror("can't save net config");
fail("Can't save net config");
goto out;
}
test_daemon();
test_waitsig();
if (system("ip addr list dev " BRIDGE_NAME " | grep inet | sort > bridge.rst.test")) {
fail("Can't get net config");
goto out;
}
if (system("diff bridge.rst.test bridge.dump.test")) {
fail("Net config differs after restore");
goto out;
}
pass();
ret = 0;
out:
del_bridge();
return ret;
}
| 2,498 | 20.921053 | 88 |
c
|
criu
|
criu-master/test/zdtm/static/cgroup04.c
|
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <limits.h>
#include "zdtmtst.h"
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
const char *test_doc = "Check that some cgroups properties in kernel controllers are preserved";
const char *test_author = "Tycho Andersen <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "cgroup directory name", 1);
static const char *cgname = "zdtmtst";
int mount_and_add(const char *controller, const char *path, const char *prop, const char *value)
{
char aux[1024], paux[1024], subdir[1024];
if (mkdir(dirname, 0700) < 0 && errno != EEXIST) {
pr_perror("Can't make dir");
return -1;
}
sprintf(subdir, "%s/%s", dirname, controller);
if (mkdir(subdir, 0700) < 0) {
pr_perror("Can't make dir");
return -1;
}
if (mount("none", subdir, "cgroup", 0, controller)) {
pr_perror("Can't mount cgroups");
goto err_rd;
}
ssprintf(paux, "%s/%s", subdir, path);
mkdir(paux, 0600);
ssprintf(paux, "%s/%s/%s", subdir, path, prop);
if (write_value(paux, value) < 0)
goto err_rs;
sprintf(aux, "%d", getpid());
ssprintf(paux, "%s/%s/tasks", subdir, path);
if (write_value(paux, aux) < 0)
goto err_rs;
ssprintf(paux, "%s/%s/special_prop_check", subdir, path);
mkdir(paux, 0600);
return 0;
err_rs:
umount(dirname);
err_rd:
rmdir(dirname);
return -1;
}
bool checkval(char *path, char *val)
{
char buf[1024];
int fd, n;
fd = open(path, O_RDONLY);
if (fd < 0) {
pr_perror("open %s", path);
return false;
}
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n < 0) {
pr_perror("read");
return false;
}
buf[n] = 0;
if (strcmp(val, buf)) {
pr_err("got %s expected %s\n", buf, val);
return false;
}
return true;
}
int main(int argc, char **argv)
{
int ret = -1, i;
char buf[1024], path[PATH_MAX];
struct stat sb;
char *dev_allow[] = {
"c *:* m", "b *:* m", "c 1:3 rwm", "c 1:5 rwm", "c 1:7 rwm", "c 5:0 rwm",
"c 5:2 rwm", "c 1:8 rwm", "c 1:9 rwm", "c 136:* rwm", "c 10:229 rwm",
};
test_init(argc, argv);
if (mount_and_add("devices", cgname, "devices.deny", "a") < 0)
goto out;
/* need to allow /dev/null for restore */
sprintf(path, "%s/devices/%s/devices.allow", dirname, cgname);
for (i = 0; i < ARRAY_SIZE(dev_allow); i++) {
if (write_value(path, dev_allow[i]) < 0)
goto out;
}
if (mount_and_add("memory", cgname, "memory.limit_in_bytes", "268435456") < 0)
goto out;
test_daemon();
test_waitsig();
buf[0] = 0;
for (i = 0; i < ARRAY_SIZE(dev_allow); i++) {
strcat(buf, dev_allow[i]);
strcat(buf, "\n");
}
sprintf(path, "%s/devices/%s/devices.list", dirname, cgname);
if (!checkval(path, buf)) {
fail();
goto out;
}
sprintf(path, "%s/memory/%s/memory.limit_in_bytes", dirname, cgname);
if (!checkval(path, "268435456\n")) {
fail();
goto out;
}
sprintf(path, "%s/devices/%s/special_prop_check", dirname, cgname);
if (stat(path, &sb) < 0) {
fail("special_prop_check doesn't exist?");
goto out;
}
if (!S_ISDIR(sb.st_mode)) {
fail("special_prop_check not a directory?");
goto out;
}
pass();
ret = 0;
out:
sprintf(path, "%s/devices/%s/special_prop_check", dirname, cgname);
rmdir(path);
sprintf(path, "%s/devices/%s", dirname, cgname);
rmdir(path);
sprintf(path, "%s/devices", dirname);
umount(path);
sprintf(path, "%s/memory/%s", dirname, cgname);
rmdir(path);
sprintf(path, "%s/memory", dirname);
umount(path);
return ret;
}
| 3,563 | 20.214286 | 96 |
c
|
criu
|
criu-master/test/zdtm/static/cgroup_ignore.c
|
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include "zdtmtst.h"
const char *test_doc = "Check that cgroups are correctly ignored";
const char *test_author = "Adrian Reber <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "cgroup directory name", 1);
static const char *cgname = "zdtmtst";
static size_t read_all(int fd, char *buf, size_t size)
{
ssize_t r = 0, ret;
while (r < size) {
ret = read(fd, buf + r, size - r);
if (ret < 0) {
pr_perror("Read failed");
return -1;
} else if (ret == 0) {
return 0;
}
r += ret;
}
return 0;
}
int main(int argc, char **argv)
{
cleanup_free char *cgroup_procs = NULL;
cleanup_close int cgroup_procs_fd = -1;
cleanup_free char *destination = NULL;
cleanup_free char *buffer_old = NULL;
cleanup_free char *buffer_new = NULL;
cleanup_close int fd = -1;
int ret = 1;
test_init(argc, argv);
buffer_old = malloc(PAGE_SIZE);
if (!buffer_old) {
pr_err("Could not allocate memory\n");
return 1;
}
memset(buffer_old, 0, PAGE_SIZE);
buffer_new = malloc(PAGE_SIZE);
if (!buffer_new) {
pr_err("Could not allocate memory\n");
return 1;
}
memset(buffer_new, 0, PAGE_SIZE);
// Read /proc/self/cgroup to later compare against it
fd = open("/proc/self/cgroup", O_RDONLY);
if (fd < 0) {
pr_err("Could not open /proc/self/cgroup\n");
return 1;
}
if (read_all(fd, buffer_old, PAGE_SIZE)) {
pr_err("Could not read data from /proc/self/cgroup\n");
return 1;
}
// Create the cgroup root directory
if (mkdir(dirname, 0700) < 0 && errno != EEXIST) {
pr_err("Cannot make directory %s\n", dirname);
return 1;
}
// Mount cgroup2, skip if cgroup2 is not available
if (mount("none", dirname, "cgroup2", 0, 0)) {
if (errno == ENODEV) {
skip("Test relies on cgroup2 semantics which this system does not support. Skipping");
test_daemon();
test_waitsig();
pass();
return 0;
} else {
pr_err("Could not mount cgroup2 at %s\n", dirname);
}
return 1;
}
// Create the cgroup cgname (if it does not already exist)
if (asprintf(&destination, "%s/%s", dirname, cgname) == -1) {
pr_err("Could not allocate memory\n");
goto err;
}
if (mkdir(destination, 0700) < 0 && errno != EEXIST) {
pr_err("Failed to create temporary cgroup directory %s\n", destination);
goto err;
}
// Move this process to the newly created cgroup
if (asprintf(&cgroup_procs, "%s/cgroup.procs", destination) == -1) {
pr_err("Could not allocate memory\n");
goto err;
}
cgroup_procs_fd = open(cgroup_procs, O_RDWR);
if (cgroup_procs_fd < 0) {
pr_err("Could not open %s\n", cgroup_procs);
goto err;
}
if (write(cgroup_procs_fd, "0", 1) != 1) {
pr_err("Writing to %s failed\n", cgroup_procs);
goto err;
}
// Read /proc/self/cgroup (should have changed)
lseek(fd, 0, SEEK_SET);
if (read_all(fd, buffer_new, PAGE_SIZE)) {
pr_err("Could not read data from /proc/self/cgroup\n");
goto err;
}
// Test if /proc/self/cgroup has changed
if (!memcmp(buffer_new, buffer_old, PAGE_SIZE)) {
fail("/proc/self/cgroup should differ after move to another cgroup");
pr_err("original /proc/self/cgroup content %s\n", buffer_old);
pr_err("new /proc/self/cgroup content %s\n", buffer_new);
goto err;
}
test_daemon();
test_waitsig();
// Read /proc/self/cgroup. It should not be the same as after
// moving this process to another cgroup because of restore
// with '--manage-cgroups=ignore'. The process should be
// now in cgroup of the current session.
lseek(fd, 0, SEEK_SET);
memset(buffer_old, 0, PAGE_SIZE);
if (read_all(fd, buffer_old, PAGE_SIZE)) {
pr_err("Could not read data from /proc/self/cgroup\n");
goto err;
}
// Test if /proc/self/cgroup has changed again
if (!memcmp(buffer_new, buffer_old, PAGE_SIZE)) {
fail("/proc/self/cgroup should differ after restore");
pr_err("original /proc/self/cgroup content %s\n", buffer_new);
pr_err("new /proc/self/cgroup content %s\n", buffer_old);
goto err;
}
ret = 0;
pass();
err:
rmdir(destination);
umount(dirname);
return ret;
}
| 4,137 | 24.54321 | 89 |
c
|
criu
|
criu-master/test/zdtm/static/cgroupv2_00.c
|
#include <sys/mount.h>
#include <sys/stat.h>
#include "zdtmtst.h"
const char *test_doc = "Check that some cgroup-v2 properties in kernel controllers are preserved";
const char *test_author = "Bui Quang Minh <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "cgroup-v2 directory name", 1);
const char *cgname = "subcg00";
int main(int argc, char **argv)
{
char path[1024], aux[1024];
int ret = -1;
test_init(argc, argv);
if (mkdir(dirname, 0700) < 0 && errno != EEXIST) {
pr_perror("Can't make dir");
return -1;
}
if (mount("cgroup2", dirname, "cgroup2", 0, NULL)) {
pr_perror("Can't mount cgroup-v2");
return -1;
}
sprintf(path, "%s/%s", dirname, cgname);
if (mkdir(path, 0700) < 0 && errno != EEXIST) {
pr_perror("Can't make dir");
goto out;
}
/* Make cpuset controllers available in children directory */
sprintf(path, "%s/%s", dirname, "cgroup.subtree_control");
sprintf(aux, "%s", "+cpuset");
if (write_value(path, aux))
goto out;
sprintf(path, "%s/%s/%s", dirname, cgname, "cgroup.subtree_control");
sprintf(aux, "%s", "+cpuset");
if (write_value(path, aux))
goto out;
sprintf(path, "%s/%s/%s", dirname, cgname, "cgroup.type");
sprintf(aux, "%s", "threaded");
if (write_value(path, aux))
goto out;
sprintf(path, "%s/%s/%s", dirname, cgname, "cgroup.procs");
sprintf(aux, "%d", getpid());
if (write_value(path, aux))
goto out;
test_daemon();
test_waitsig();
sprintf(path, "%s/%s/%s", dirname, cgname, "cgroup.subtree_control");
if (read_value(path, aux, sizeof(aux)))
goto out;
if (strcmp(aux, "cpuset\n")) {
fail("cgroup.subtree_control mismatches");
goto out;
}
sprintf(path, "%s/%s/%s", dirname, cgname, "cgroup.type");
if (read_value(path, aux, sizeof(aux)))
goto out;
if (strcmp(aux, "threaded\n")) {
fail("cgroup.type mismatches");
goto out;
}
pass();
ret = 0;
out:
sprintf(path, "%s", dirname);
umount(path);
return ret;
}
| 1,947 | 21.390805 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/cmdlinenv00.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "zdtmtst.h"
const char *test_doc = "Test that env/cmdline/auxv restored well\n";
const char *test_author = "Cyrill Gorcunov <[email protected]";
static char *arg1, *arg2, *arg3;
TEST_OPTION(arg1, string, "arg1", 1);
TEST_OPTION(arg2, string, "arg2", 1);
TEST_OPTION(arg3, string, "arg3", 1);
static void read_from_proc(const char *path, char *buf, size_t size)
{
ssize_t r = 0, ret;
int fd;
fd = open(path, O_RDONLY);
if (fd < 0) {
fail("Can't open cmdline");
exit(1);
}
while (r < size) {
ret = read(fd, buf + r, size - r);
if (ret < 0) {
pr_perror("Read failed");
exit(1);
} else if (ret == 0) {
break;
}
r += ret;
}
close(fd);
}
static int cmp_auxv(const void *auxv_orig, const void *auxv, size_t size)
{
const unsigned long long *new = auxv;
const unsigned int *old = auxv_orig;
if (!memcmp(auxv_orig, auxv, size))
return 0;
/*
* File /proc/$pid/auxv does not has compat layer, this "array of long"
* has different byte-representation between 32-bit and 64-bit host.
* We can migrate tasks only in one direction, thus check is simple.
*/
while (size > 0) {
if (*new != *old)
return -1;
new ++;
old++;
size -= sizeof(*new);
}
return 0;
}
int main(int argc, char *argv[])
{
char cmdline_orig[4096];
char cmdline[4096];
char env_orig[4096];
char env[4096];
char auxv_orig[1024];
char auxv[1024];
memset(cmdline_orig, 0, sizeof(cmdline_orig));
memset(cmdline, 0, sizeof(cmdline));
memset(env_orig, 0, sizeof(env_orig));
memset(env, 0, sizeof(env));
memset(auxv_orig, 0, sizeof(auxv_orig));
memset(auxv, 0, sizeof(auxv));
test_init(argc, argv);
read_from_proc("/proc/self/cmdline", cmdline_orig, sizeof(cmdline_orig));
read_from_proc("/proc/self/environ", env_orig, sizeof(env_orig));
read_from_proc("/proc/self/auxv", auxv_orig, sizeof(auxv_orig));
test_msg("old cmdline: %s\n", cmdline_orig);
test_msg("old environ: %s\n", env_orig);
test_daemon();
test_waitsig();
read_from_proc("/proc/self/cmdline", cmdline, sizeof(cmdline));
read_from_proc("/proc/self/environ", env, sizeof(env));
read_from_proc("/proc/self/auxv", auxv, sizeof(auxv));
test_msg("new cmdline: %s\n", cmdline);
test_msg("new environ: %s\n", env);
if (strncmp(cmdline_orig, cmdline, sizeof(cmdline_orig))) {
fail("cmdline corrupted on restore");
exit(1);
}
if (strncmp(env_orig, env, sizeof(env_orig))) {
fail("envirion corrupted on restore");
exit(1);
}
if (cmp_auxv(auxv_orig, auxv, sizeof(auxv_orig))) {
fail("auxv corrupted on restore");
exit(1);
}
pass();
return 0;
}
| 2,745 | 21.145161 | 74 |
c
|
criu
|
criu-master/test/zdtm/static/cow01.c
|
#include <fcntl.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include <sys/user.h>
#include <stdlib.h>
#include <sys/socket.h>
#include "zdtmtst.h"
const char *test_doc = "Check that cow memory are restored";
const char *test_author = "Andrey Vagin <[email protected]";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
struct test_case {
union {
struct {
uint8_t b_f_write : 1; /* before fork */
uint8_t b_f_read : 1;
uint8_t a_f_write_child : 1; /* after fork */
uint8_t a_f_write_parent : 1;
uint8_t a_f_read_child : 1;
uint8_t a_f_read_parent : 1;
#define TEST_CASES (2 << 6)
};
uint8_t num;
};
uint32_t crc_parent;
uint32_t crc_child;
};
struct test_cases {
struct test_case tc[TEST_CASES];
void *addr;
int (*init)(struct test_cases *tcs);
char *tname;
};
static int init_cow(struct test_cases *);
static int init_cow_gd(struct test_cases *tcs);
static int init_sep(struct test_cases *);
static int init_file(struct test_cases *);
static pid_t child_pid;
/*
* A return code of -1 means an error running the test (e.g. error opening a
* file, etc.). A return code of 1 means failure, it means criu was not able
* to checkpoint and/or restore the process properly.
*/
#define EXECUTE_ACTION(func, fd) \
({ \
int __ret = 0; \
__ret |= func(&sep_tcs, fd); \
__ret |= func(&cow_tcs, fd); \
__ret |= func(&cow_gd_tcs, fd); \
__ret |= func(&file_tcs, fd); \
__ret; \
})
struct test_cases cow_tcs = { .init = init_cow, .tname = "cow_tcs" },
sep_tcs = { .init = init_sep, .tname = "sep_tcs" },
file_tcs = { .init = init_file, .tname = "file_tcs" },
cow_gd_tcs = { .init = init_cow_gd, .tname = "cow_gd_tcs" };
uint32_t zero_crc = ~1;
static int is_cow(void *addr, pid_t pid_child, pid_t pid_parent, uint64_t *map_child_ret, uint64_t *map_parent_ret,
int fd)
{
char buf[PATH_MAX];
unsigned long pfn = (unsigned long)addr / PAGE_SIZE;
uint64_t map_child, map_parent;
int fd_child, fd_parent, ret, i;
off_t lseek_ret;
snprintf(buf, sizeof(buf), "/proc/%d/pagemap", pid_child);
fd_child = open(buf, O_RDONLY);
if (fd_child < 0) {
pr_perror("Unable to open child pagemap file %s", buf);
return -1;
}
snprintf(buf, sizeof(buf), "/proc/%d/pagemap", pid_parent);
fd_parent = open(buf, O_RDONLY);
if (fd_parent < 0) {
pr_perror("Unable to open parent pagemap file %s", buf);
return -1;
}
/*
* A page can be swapped or unswapped,
* so we should do several iterations.
*/
for (i = 0; i < 10; i++) {
void **p = addr;
lseek_ret = lseek(fd_child, pfn * sizeof(map_child), SEEK_SET);
if (lseek_ret == (off_t)-1) {
pr_perror("Unable to seek child pagemap to virtual addr %#08lx", pfn * PAGE_SIZE);
return -1;
}
lseek_ret = lseek(fd_parent, pfn * sizeof(map_parent), SEEK_SET);
if (lseek_ret == (off_t)-1) {
pr_perror("Unable to seek parent pagemap to virtual addr %#08lx", pfn * PAGE_SIZE);
return -1;
}
ret = read(fd_child, &map_child, sizeof(map_child));
if (ret != sizeof(map_child)) {
pr_perror("Unable to read child pagemap at virtual addr %#08lx", pfn * PAGE_SIZE);
return -1;
}
ret = read(fd_parent, &map_parent, sizeof(map_parent));
if (ret != sizeof(map_parent)) {
pr_perror("Unable to read parent pagemap at virtual addr %#08lx", pfn * PAGE_SIZE);
return -1;
}
if (map_child == map_parent && i > 5)
break;
p = (void **)(addr + i * PAGE_SIZE);
test_msg("Read *%p = %p\n", p, p[0]);
if (write(fd, &p, sizeof(p)) != sizeof(p)) {
pr_perror("write");
return -1;
}
if (read(fd, &p, sizeof(p)) != sizeof(p)) {
pr_perror("read");
return -1;
}
test_msg("Child %p\n", p);
}
close(fd_child);
close(fd_parent);
if (map_child_ret)
*map_child_ret = map_child;
if (map_parent_ret)
*map_parent_ret = map_parent;
// Return 0 for success, 1 if the pages differ.
return map_child != map_parent;
}
static int child_prep(struct test_cases *test_cases, int fd)
{
int i;
uint8_t *addr = test_cases->addr;
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = test_cases->tc + i;
if (tc->a_f_write_child) {
tc->crc_child = ~1;
datagen2(addr + i * PAGE_SIZE, PAGE_SIZE, &tc->crc_child);
}
if (tc->a_f_read_child) {
uint32_t crc = ~1;
datasum(addr + i * PAGE_SIZE, PAGE_SIZE, &crc);
}
}
return 0;
}
static int child_check(struct test_cases *test_cases, int fd)
{
int i, ret = 0;
uint8_t *addr = test_cases->addr;
for (i = 0; i < TEST_CASES; i++) {
uint32_t crc = ~1;
struct test_case *tc = test_cases->tc + i;
datasum(addr + i * PAGE_SIZE, PAGE_SIZE, &crc);
if (crc != tc->crc_child) {
errno = 0;
fail("%s[%#x]: %p child data mismatch (expected [%04x] got [%04x])", test_cases->tname, i,
addr + i * PAGE_SIZE, tc->crc_child, crc);
ret |= 1;
}
}
return ret;
}
static int parent_before_fork(struct test_cases *test_cases, int fd)
{
uint8_t *addr;
int i;
if (test_cases->init(test_cases))
return -1;
addr = test_cases->addr;
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = test_cases->tc + i;
tc->num = i;
if (tc->b_f_write) {
tc->crc_parent = ~1;
datagen2(addr + i * PAGE_SIZE, PAGE_SIZE, &tc->crc_parent);
if (test_cases != &sep_tcs)
tc->crc_child = tc->crc_parent;
}
if (tc->b_f_read) {
uint32_t crc = ~1;
datasum(addr + i * PAGE_SIZE, PAGE_SIZE, &crc);
}
}
return 0;
}
static int parent_post_fork(struct test_cases *test_cases, int fd)
{
uint8_t *addr = test_cases->addr;
int i;
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = test_cases->tc + i;
if (tc->a_f_write_parent) {
tc->crc_parent = ~1;
datagen2(addr + i * PAGE_SIZE, PAGE_SIZE, &tc->crc_parent);
}
if (tc->a_f_read_parent) {
uint32_t crc = ~1;
datasum(addr + i * PAGE_SIZE, PAGE_SIZE, &crc);
}
}
return 0;
}
static int parent_check(struct test_cases *test_cases, int fd)
{
uint8_t *addr = test_cases->addr;
int i, ret = 0;
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = test_cases->tc + i;
uint32_t crc = ~1;
datasum(addr + i * PAGE_SIZE, PAGE_SIZE, &crc);
if (crc != tc->crc_parent) {
errno = 0;
fail("%s[%#x]: %p parent data mismatch (expected [%04x] got [%04x])", test_cases->tname, i,
addr + i * PAGE_SIZE, tc->crc_parent, crc);
ret |= 1;
}
if (test_cases == &sep_tcs)
continue;
if (!tc->a_f_write_child && !tc->a_f_write_parent && tc->b_f_write) {
uint64_t map_child, map_parent;
int is_cow_ret;
is_cow_ret = is_cow(addr + i * PAGE_SIZE, child_pid, getpid(), &map_child, &map_parent, fd);
ret |= is_cow_ret;
if (is_cow_ret == 1) {
errno = 0;
fail("%s[%#x]: %p is not COW-ed (pagemap of "
"child=[%" PRIx64 "], parent=[%" PRIx64 "])",
test_cases->tname, i, addr + i * PAGE_SIZE, map_child, map_parent);
}
}
}
return ret;
}
static int __init_cow(struct test_cases *tcs, int flags)
{
int i;
void *addr;
addr = mmap(NULL, PAGE_SIZE * (TEST_CASES + 2), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
pr_perror("Can't allocate memory");
return -1;
}
/*
* Guard pages are used for preventing merging with other vma-s.
* In parent cow-ed and coinciding regions can be merged, but
* in child they cannot be, so COW will not be restored. FIXME
*/
mmap(addr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
addr += PAGE_SIZE;
tcs->addr = addr;
mmap(addr + PAGE_SIZE * TEST_CASES, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | flags, -1,
0);
test_msg("addr[%s]=%p\n", tcs->tname, tcs->addr);
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = tcs->tc + i;
tc->crc_parent = zero_crc;
tc->crc_child = zero_crc;
}
return 0;
}
static int init_cow(struct test_cases *tcs)
{
return __init_cow(tcs, 0);
}
static int init_cow_gd(struct test_cases *tcs)
{
return __init_cow(tcs, MAP_GROWSDOWN);
}
static int init_sep(struct test_cases *tcs)
{
int i;
tcs->addr = mmap(NULL, PAGE_SIZE * TEST_CASES, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (tcs->addr == MAP_FAILED) {
pr_perror("Can't allocate memory");
return -1;
}
test_msg("addr[%s]=%p\n", tcs->tname, tcs->addr);
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = tcs->tc + i;
tc->crc_parent = zero_crc;
tc->crc_child = zero_crc;
}
return 0;
}
static int init_file(struct test_cases *tcs)
{
int i, ret, fd;
uint8_t buf[PAGE_SIZE];
uint32_t crc;
fd = open(filename, O_TRUNC | O_CREAT | O_RDWR, 0600);
if (fd < 0) {
pr_perror("Unable to create a test file");
return -1;
}
for (i = 0; i < TEST_CASES; i++) {
struct test_case *tc = tcs->tc + i;
crc = ~1;
datagen2(buf, sizeof(buf), &crc);
ret = write(fd, buf, sizeof(buf));
if (ret != sizeof(buf)) {
pr_perror("Unable to write data in test file %s", filename);
return -1;
}
tc->crc_parent = crc;
tc->crc_child = crc;
}
tcs->addr = mmap(NULL, PAGE_SIZE * TEST_CASES, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, fd, 0);
if (tcs->addr == MAP_FAILED) {
pr_perror("Can't allocate memory");
return -1;
}
test_msg("addr[%s]=%p\n", tcs->tname, tcs->addr);
close(fd);
return 0;
}
static int child(task_waiter_t *child_waiter, int fd)
{
int ret = 0;
sep_tcs.addr = mmap(sep_tcs.addr, PAGE_SIZE * TEST_CASES, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (sep_tcs.addr == MAP_FAILED) {
pr_perror("Can't allocate memory");
return -1;
}
EXECUTE_ACTION(child_prep, fd);
task_waiter_complete_current(child_waiter);
while (1) {
void **p;
ret = read(fd, &p, sizeof(p));
if (ret == 0)
break;
if (ret != sizeof(p)) {
pr_perror("read");
return -1;
}
test_msg("Read *%p = %p\n", p, p[0]);
p = ((void **)p)[0];
if (write(fd, &p, sizeof(p)) != sizeof(p)) {
pr_perror("write");
return -1;
}
ret = 0;
}
ret = EXECUTE_ACTION(child_check, fd);
// Exit code of child process, so return 2 for a test error, 1 for a
// test failure (child_check got mismatched checksums) and 0 for
// success.
return (ret < 0) ? 2 : (ret != 0);
}
int main(int argc, char **argv)
{
uint8_t zero_page[PAGE_SIZE];
int status = -1, ret = 0;
task_waiter_t child_waiter;
int pfd[2], fd;
test_init(argc, argv);
task_waiter_init(&child_waiter);
memset(zero_page, 0, sizeof(zero_page));
datasum(zero_page, sizeof(zero_page), &zero_crc);
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, pfd)) {
pr_perror("pipe");
return 1;
}
if (EXECUTE_ACTION(parent_before_fork, -1))
return 2;
child_pid = test_fork();
if (child_pid < 0) {
pr_perror("Can't fork");
return 2;
}
if (child_pid == 0) {
close(pfd[0]);
return child(&child_waiter, pfd[1]);
}
close(pfd[1]);
fd = pfd[0];
task_waiter_wait4(&child_waiter, child_pid);
EXECUTE_ACTION(parent_post_fork, -1);
test_daemon();
test_waitsig();
ret |= EXECUTE_ACTION(parent_check, fd);
close(fd);
wait(&status);
unlink(filename);
if (WIFEXITED(status) && WEXITSTATUS(status) != 2)
ret |= WEXITSTATUS(status);
else
ret |= -1;
if (ret == 0)
pass();
// Exit code, so return 2 for a test error, 1 for a test failure and 0
// for success.
return (ret < 0) ? 2 : (ret != 0);
}
| 11,493 | 22.220202 | 115 |
c
|
criu
|
criu-master/test/zdtm/static/dumpable02.c
|
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "zdtmtst.h"
const char *test_doc = "Check dumpable flag handling (non-dumpable case)";
const char *test_author = "Filipe Brandenburger <[email protected]>";
int dumpable_server(void)
{
char buf[256];
int ret;
for (;;) {
ret = read(0, buf, sizeof(buf));
if (ret == 0)
break;
ret = snprintf(buf, sizeof(buf), "DUMPABLE:%d\n", prctl(PR_GET_DUMPABLE));
write(1, buf, ret);
}
return 0;
}
int get_dumpable_from_pipes(int pipe_input, int pipe_output)
{
char buf[256];
int len;
long value;
char *endptr = NULL;
/* input and output are from the child's point of view. */
write(pipe_input, "GET\n", 4);
len = read(pipe_output, buf, sizeof(buf) - 1);
if (len < 0) {
pr_perror("error in parent reading from pipe");
return -1;
}
buf[len] = 0;
if (memcmp(buf, "DUMPABLE:", 9) != 0) {
pr_err("child returned [%s]\n", buf);
return -1;
}
value = strtol(&buf[9], &endptr, 10);
if (!endptr || *endptr != '\n' || endptr != buf + len - 1) {
pr_err("child returned [%s]\n", buf);
return -1;
}
return (int)value;
}
int main(int argc, char **argv)
{
int pipe_input[2];
int pipe_output[2];
int save_dumpable;
int dumpable;
int ret;
pid_t pid;
pid_t waited;
int status;
/*
* Check if we are being re-executed to spawn the dumpable server. This
* re-execution is what essentially causes the dumpable flag to be
* cleared since we have execute but not read permissions to the
* binary.
*/
if (getenv("DUMPABLE_SERVER"))
return dumpable_server();
/*
* Otherwise, do normal startup and spawn a dumpable server. While we
* are still running as root, chmod() the binary to give it execute but
* not read permissions, that way when we execv() it as a non-root user
* the kernel will drop our dumpable flag and reset it to the value in
* /proc/sys/fs/suid_dumpable.
*/
ret = chmod(argv[0], 0111);
if (ret < 0) {
pr_perror("chmod(%s) failed", argv[0]);
return 1;
}
test_init(argc, argv);
ret = pipe(pipe_input);
if (ret < 0) {
pr_perror("error creating input pipe");
return 1;
}
ret = pipe(pipe_output);
if (ret < 0) {
pr_perror("error creating output pipe");
return 1;
}
pid = fork();
if (pid < 0) {
pr_perror("error forking the dumpable server");
return 1;
}
if (pid == 0) {
/*
* Child process will execv() the dumpable server. Start by
* reopening stdin and stdout to use the pipes, then set the
* environment variable and execv() the same binary.
*/
close(0);
close(1);
ret = dup2(pipe_input[0], 0);
if (ret < 0) {
pr_perror("could not dup2 pipe into child's stdin");
return 1;
}
ret = dup2(pipe_output[1], 1);
if (ret < 0) {
pr_perror("could not dup2 pipe into child's stdout");
return 1;
}
close(pipe_output[0]);
close(pipe_output[1]);
close(pipe_input[0]);
close(pipe_input[1]);
ret = setenv("DUMPABLE_SERVER", "yes", 1);
if (ret < 0) {
pr_perror("could not set the DUMPABLE_SERVER env variable");
return 1;
}
execl(argv[0], "dumpable_server", NULL);
pr_perror("could not execv %s as a dumpable_server", argv[0]);
return 1;
}
/*
* Parent process, write to the pipe_input socket to ask the server
* child to tell us what its dumpable flag value is on its side.
*/
close(pipe_input[0]);
close(pipe_output[1]);
save_dumpable = get_dumpable_from_pipes(pipe_input[1], pipe_output[0]);
if (save_dumpable < 0)
return 1;
#ifdef DEBUG
test_msg("DEBUG: before dump: dumpable=%d\n", save_dumpable);
#endif
/* Wait for dump and restore. */
test_daemon();
test_waitsig();
dumpable = get_dumpable_from_pipes(pipe_input[1], pipe_output[0]);
if (dumpable < 0)
return 1;
#ifdef DEBUG
test_msg("DEBUG: after restore: dumpable=%d\n", dumpable);
#endif
if (dumpable != save_dumpable) {
errno = 0;
fail("dumpable flag was not preserved over migration");
return 1;
}
/* Closing the pipes will terminate the child server. */
close(pipe_input[1]);
close(pipe_output[0]);
waited = wait(&status);
if (waited < 0) {
pr_perror("error calling wait on the child");
return 1;
}
errno = 0;
if (waited != pid) {
pr_err("waited pid %d did not match child pid %d\n", waited, pid);
return 1;
}
if (!WIFEXITED(status)) {
pr_err("child dumpable server returned abnormally with status=%d\n", status);
return 1;
}
if (WEXITSTATUS(status) != 0) {
pr_err("child dumpable server returned rc=%d\n", WEXITSTATUS(status));
return 1;
}
pass();
return 0;
}
| 4,652 | 21.263158 | 79 |
c
|
criu
|
criu-master/test/zdtm/static/epoll01.c
|
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include "zdtmtst.h"
const char *test_doc = "Check another case of epoll: This adds three epoll "
"targets on tfd 702 and then adds two epoll targets "
"on tfd 701. This test is for off calculation in "
"dump_one_eventpoll, the reverse order makes qsort "
"to actually work.";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
int main(int argc, char *argv[])
{
int epollfd;
struct epoll_event ev;
int i, ret;
struct {
int pipefd[2];
int dupfd;
bool close;
} pipes[5] = {
{ {}, 702, true }, { {}, 702, true }, { {}, 702, false }, { {}, 701, true }, { {}, 701, false },
};
test_init(argc, argv);
epollfd = epoll_create(1);
if (epollfd < 0) {
pr_perror("epoll_create failed");
exit(1);
}
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN | EPOLLOUT;
for (i = 0; i < ARRAY_SIZE(pipes); i++) {
int fd;
if (pipe(pipes[i].pipefd)) {
pr_err("Can't create pipe %d\n", i);
exit(1);
}
ev.data.u64 = i;
fd = dup2(pipes[i].pipefd[0], pipes[i].dupfd);
if (fd < 0 || fd != pipes[i].dupfd) {
pr_perror("Can't dup %d to %d", pipes[i].pipefd[0], pipes[i].dupfd);
exit(1);
}
test_msg("epoll %d add %d dup'ed from %d\n", epollfd, fd, pipes[i].pipefd[0]);
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev)) {
pr_perror("Can't add pipe %d", fd);
close(fd);
exit(1);
}
if (pipes[i].close) {
close(fd);
test_msg("epoll source %d closed\n", fd);
}
}
test_daemon();
test_waitsig();
ret = 0;
for (i = 0; i < ARRAY_SIZE(pipes); i++) {
uint8_t cw = 1, cr;
if (write(pipes[i].pipefd[1], &cw, sizeof(cw)) != sizeof(cw)) {
pr_perror("Unable to write into a pipe");
return 1;
}
if (epoll_wait(epollfd, &ev, 1, -1) != 1) {
pr_perror("Unable to wait events");
return 1;
}
if (ev.data.u64 != i) {
pr_err("ev.fd=%d ev.data.u64=%#llx (%d expected)\n", ev.data.fd, (long long)ev.data.u64, i);
ret |= 1;
}
if (read(pipes[i].pipefd[0], &cr, sizeof(cr)) != sizeof(cr)) {
pr_perror("read");
return 1;
}
}
if (ret)
return 1;
pass();
return 0;
}
| 2,468 | 20.102564 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/fanotify00.c
|
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/fanotify.h>
#include "zdtmtst.h"
#ifdef __x86_64__
#define __NR_fanotify_init 300
#define __NR_fanotify_mark 301
#elif defined(__PPC64__)
#define __NR_fanotify_init 323
#define __NR_fanotify_mark 324
#elif __aarch64__
#define __NR_fanotify_init 262
#define __NR_fanotify_mark 263
#elif __s390x__
#define __NR_fanotify_init 332
#define __NR_fanotify_mark 333
#else
#define __NR_fanotify_init 338
#define __NR_fanotify_mark 339
#endif
const char *test_doc = "Check for fanotify delivery";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
const char fanotify_path[] = "fanotify-del-after-cr";
#define BUFF_SIZE (8192)
struct fanotify_mark_inode {
unsigned long i_ino;
unsigned int s_dev;
unsigned int mflags;
unsigned int mask;
unsigned int ignored_mask;
unsigned int fhandle_bytes;
unsigned int fhandle_type;
unsigned char fhandle[512];
};
struct fanotify_mark_mount {
unsigned int mnt_id;
unsigned int mflags;
unsigned int mask;
unsigned int ignored_mask;
};
struct fanotify_glob {
unsigned int faflags;
unsigned int evflags;
};
struct fanotify_obj {
struct fanotify_glob glob;
struct fanotify_mark_inode inode;
struct fanotify_mark_mount mount;
};
static int fanotify_init(unsigned int flags, unsigned int event_f_flags)
{
return syscall(__NR_fanotify_init, flags, event_f_flags);
}
static int fanotify_mark(int fanotify_fd, unsigned int flags, unsigned long mask, int dfd, const char *pathname)
{
#ifdef __i386__
return syscall(__NR_fanotify_mark, fanotify_fd, flags, mask, 0, dfd, pathname);
#else
return syscall(__NR_fanotify_mark, fanotify_fd, flags, mask, dfd, pathname);
#endif
}
#define fdinfo_field(str, field) !strncmp(str, field ":", sizeof(field))
static void show_fanotify_obj(struct fanotify_obj *obj)
{
test_msg("fanotify obj at %p\n", obj);
test_msg(" glob\n");
test_msg(" faflags: %x evflags: %x\n", obj->glob.faflags, obj->glob.evflags);
test_msg(" inode\n");
test_msg(" i_ino: %lx s_dev: %x mflags: %x "
"mask: %x ignored_mask: %x "
"fhandle_bytes: %x fhandle_type: %x "
"fhandle: %s",
obj->inode.i_ino, obj->inode.s_dev, obj->inode.mflags, obj->inode.mask, obj->inode.ignored_mask,
obj->inode.fhandle_bytes, obj->inode.fhandle_type, obj->inode.fhandle);
test_msg(" mount\n");
test_msg(" mnt_id: %x mflags: %x mask: %x ignored_mask: %x\n", obj->mount.mnt_id, obj->mount.mflags,
obj->mount.mask, obj->mount.ignored_mask);
}
static void copy_fhandle(char *tok, struct fanotify_mark_inode *inode)
{
int off = 0;
while (*tok && (*tok > '0' || *tok < 'f')) {
inode->fhandle[off++] = *tok++;
if (off >= sizeof(inode->fhandle) - 1)
break;
}
inode->fhandle[off] = '\0';
}
static int cmp_fanotify_obj(struct fanotify_obj *old, struct fanotify_obj *new)
{
/*
* mnt_id and s_dev may change during container migration,
* moreover the backend (say PLOOP) may be re-mounted during
* c/r, so exclude them.
*/
if ((old->glob.faflags != new->glob.faflags) || (old->glob.evflags != new->glob.evflags) ||
(old->inode.i_ino != new->inode.i_ino) || (old->inode.mflags != new->inode.mflags) ||
(old->inode.mask != new->inode.mask) || (old->inode.ignored_mask != new->inode.ignored_mask))
return -1;
if (memcmp(old->inode.fhandle, new->inode.fhandle, sizeof(new->inode.fhandle)))
return -2;
if ((old->mount.mflags != new->mount.mflags) || (old->mount.mask != new->mount.mask) ||
(old->mount.ignored_mask != new->mount.ignored_mask))
return -3;
return 0;
}
int parse_fanotify_fdinfo(int fd, struct fanotify_obj *obj, unsigned int expected_to_meet)
{
unsigned int met = 0;
char str[512];
FILE *f;
int ret;
sprintf(str, "/proc/self/fdinfo/%d", fd);
f = fopen(str, "r");
if (!f) {
pr_perror("Can't open fdinfo to parse");
return -1;
}
while (fgets(str, sizeof(str), f)) {
if (fdinfo_field(str, "fanotify flags")) {
ret = sscanf(str, "fanotify flags:%x event-flags:%x", &obj->glob.faflags, &obj->glob.evflags);
if (ret != 2)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "fanotify mnt_id")) {
ret = sscanf(str, "fanotify mnt_id:%x mflags:%x mask:%x ignored_mask:%x", &obj->mount.mnt_id,
&obj->mount.mflags, &obj->mount.mask, &obj->mount.ignored_mask);
if (ret != 4)
goto parse_err;
met++;
continue;
}
if (fdinfo_field(str, "fanotify ino")) {
int hoff;
ret = sscanf(str,
"fanotify ino:%lx sdev:%x mflags:%x mask:%x ignored_mask:%x "
"fhandle-bytes:%x fhandle-type:%x f_handle: %n",
&obj->inode.i_ino, &obj->inode.s_dev, &obj->inode.mflags, &obj->inode.mask,
&obj->inode.ignored_mask, &obj->inode.fhandle_bytes, &obj->inode.fhandle_type,
&hoff);
if (ret != 7)
goto parse_err;
copy_fhandle(&str[hoff], &obj->inode);
met++;
continue;
}
}
if (expected_to_meet != met) {
pr_perror("Expected to meet %d entries but got %d", expected_to_meet, met);
return -1;
}
return 0;
parse_err:
pr_perror("Can't parse '%s'", str);
return -1;
}
int main(int argc, char *argv[])
{
struct fanotify_obj old = {}, new = {};
int fa_fd, fd, del_after;
char buf[BUFF_SIZE];
ssize_t length;
int ns = getenv("ZDTM_NEWNS") != NULL;
test_init(argc, argv);
if (ns) {
if (mkdir("/tmp", 666) && errno != EEXIST) {
pr_perror("Unable to create the /tmp directory");
return -1;
}
if (mount("zdtm", "/tmp", "tmpfs", 0, NULL)) {
pr_perror("Unable to mount tmpfs into %s", "/tmp");
}
}
fa_fd = fanotify_init(FAN_NONBLOCK | FAN_CLASS_NOTIF | FAN_UNLIMITED_QUEUE, O_RDONLY | O_LARGEFILE);
if (fa_fd < 0) {
pr_perror("fanotify_init failed");
exit(1);
}
del_after = open(fanotify_path, O_CREAT | O_TRUNC);
if (del_after < 0) {
pr_perror("open failed");
exit(1);
}
if (fanotify_mark(fa_fd, FAN_MARK_ADD, FAN_MODIFY | FAN_ACCESS | FAN_OPEN | FAN_CLOSE, AT_FDCWD,
fanotify_path)) {
pr_perror("fanotify_mark failed");
exit(1);
}
if (fanotify_mark(fa_fd, FAN_MARK_ADD | FAN_MARK_MOUNT, FAN_ONDIR | FAN_OPEN | FAN_CLOSE, AT_FDCWD, "/tmp")) {
pr_perror("fanotify_mark failed");
exit(1);
}
if (fanotify_mark(fa_fd, FAN_MARK_ADD | FAN_MARK_MOUNT | FAN_MARK_IGNORED_MASK | FAN_MARK_IGNORED_SURV_MODIFY,
FAN_MODIFY | FAN_ACCESS, AT_FDCWD, "/tmp")) {
pr_perror("fanotify_mark failed");
exit(1);
}
if (parse_fanotify_fdinfo(fa_fd, &old, 3)) {
pr_perror("parsing fanotify fdinfo failed");
exit(1);
}
show_fanotify_obj(&old);
test_daemon();
test_waitsig();
fd = open("/", O_RDONLY);
close(fd);
fd = open(fanotify_path, O_RDWR);
close(fd);
if (unlink(fanotify_path)) {
fail("can't unlink %s", fanotify_path);
exit(1);
}
if (parse_fanotify_fdinfo(fa_fd, &new, 3)) {
fail("parsing fanotify fdinfo failed");
exit(1);
}
show_fanotify_obj(&new);
if (cmp_fanotify_obj(&old, &new)) {
fail("fanotify mismatch on fdinfo level");
exit(1);
}
length = read(fa_fd, buf, sizeof(buf));
if (length <= 0) {
fail("No events in fanotify queue");
exit(1);
}
if (fanotify_mark(fa_fd, FAN_MARK_REMOVE | FAN_MARK_MOUNT, FAN_ONDIR | FAN_OPEN | FAN_CLOSE, AT_FDCWD,
"/tmp")) {
pr_perror("fanotify_mark failed");
exit(1);
}
pass();
return 0;
}
| 7,470 | 24.07047 | 112 |
c
|
criu
|
criu-master/test/zdtm/static/file_lease02.c
|
#include <fcntl.h>
#include <stdio.h>
#include <signal.h>
#include <limits.h>
#include "zdtmtst.h"
#define FD_COUNT 3
#define BREAK_SIGNUM SIGIO
const char *test_doc = "Check c/r of breaking leases";
const char *test_author = "Pavel Begunkov <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
char filename1[PATH_MAX];
char filename2[PATH_MAX];
char filename3[PATH_MAX];
int expected_fd;
int sigaction_error;
static void break_sigaction(int signo, siginfo_t *info, void *ctx)
{
if (signo != BREAK_SIGNUM) {
pr_err("Unexpected signal(%i)\n", signo);
sigaction_error = -1;
} else if (info->si_fd != expected_fd) {
pr_err("Unexpected fd(%i)\n", info->si_fd);
sigaction_error = -1;
}
expected_fd = -1;
}
static int check_lease_type(int fd, int expected_type)
{
int lease_type = fcntl(fd, F_GETLEASE);
if (lease_type != expected_type) {
if (lease_type < 0)
pr_perror("Can't acquire lease type");
else
pr_err("Mismatched lease type: %i\n", lease_type);
return -1;
}
return 0;
}
static int prepare_file(char *file, int file_type, int break_type)
{
int fd, fd_break;
int lease_type = (file_type == O_RDONLY) ? F_RDLCK : F_WRLCK;
fd = open(file, file_type | O_CREAT, 0666);
if (fd < 0) {
pr_perror("Can't open file (type %i)", file_type);
return fd;
}
if (fcntl(fd, F_SETLEASE, lease_type) < 0) {
pr_perror("Can't set exclusive lease");
goto err;
}
if (fcntl(fd, F_SETSIG, BREAK_SIGNUM) < 0) {
pr_perror("Can't set signum for file i/o");
goto err;
}
expected_fd = fd;
fd_break = open(file, break_type | O_NONBLOCK);
if (fd_break >= 0) {
close(fd_break);
pr_err("Conflicting lease not found\n");
goto err;
} else if (errno != EWOULDBLOCK) {
pr_perror("Can't break lease");
goto err;
}
return fd;
err:
close(fd);
return -1;
}
static void close_files(int fds[FD_COUNT])
{
int i;
for (i = 0; i < FD_COUNT; ++i)
if (fds[i] >= 0)
close(fds[i]);
unlink(filename1);
unlink(filename2);
unlink(filename3);
}
int main(int argc, char **argv)
{
int fds[FD_COUNT] = {};
int ret = -1;
struct sigaction act = {};
test_init(argc, argv);
snprintf(filename1, sizeof(filename1), "%s.0", filename);
snprintf(filename2, sizeof(filename2), "%s.1", filename);
snprintf(filename3, sizeof(filename3), "%s.2", filename);
act.sa_sigaction = break_sigaction;
act.sa_flags = SA_SIGINFO;
if (sigemptyset(&act.sa_mask) || sigaddset(&act.sa_mask, BREAK_SIGNUM) || sigaction(BREAK_SIGNUM, &act, NULL)) {
pr_perror("Can't set signal action");
fail();
return -1;
}
sigaction_error = 0;
fds[0] = prepare_file(filename1, O_RDONLY, O_WRONLY);
fds[1] = prepare_file(filename2, O_WRONLY, O_RDONLY);
fds[2] = prepare_file(filename3, O_WRONLY, O_WRONLY);
if (fds[0] < 0 || fds[1] < 0 || fds[2] < 0 || sigaction_error)
goto done;
test_daemon();
test_waitsig();
ret = 0;
if (sigaction_error)
fail("Ghost signal");
else if (check_lease_type(fds[0], F_UNLCK) || check_lease_type(fds[1], F_RDLCK) ||
check_lease_type(fds[2], F_UNLCK))
fail("Lease type doesn't match");
else
pass();
done:
close_files(fds);
return ret;
}
| 3,148 | 21.176056 | 113 |
c
|
criu
|
criu-master/test/zdtm/static/file_locks01.c
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <string.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include "zdtmtst.h"
#include "fs.h"
#ifndef LOCK_MAND
#define LOCK_MAND 32
#endif
#ifndef LOCK_READ
#define LOCK_READ 64
#endif
const char *test_doc = "Check that flock locks are restored";
const char *test_author = "Qiang Huang <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
char file0[PATH_MAX];
char file1[PATH_MAX];
char file2[PATH_MAX];
unsigned long inodes[3];
static mnt_info_t *m;
dev_t dev;
static int open_all_files(int *fd_0, int *fd_1, int *fd_2)
{
struct stat buf;
snprintf(file0, sizeof(file0), "%s.0", filename);
snprintf(file1, sizeof(file0), "%s.1", filename);
snprintf(file2, sizeof(file0), "%s.2", filename);
*fd_0 = open(file0, O_RDWR | O_CREAT | O_EXCL, 0666);
if (*fd_0 < 0) {
pr_perror("Unable to open file %s", file0);
return -1;
}
fstat(*fd_0, &buf);
inodes[0] = buf.st_ino;
if (!strcmp(m->fsname, "btrfs"))
dev = m->s_dev;
else
dev = buf.st_dev;
*fd_1 = open(file1, O_RDWR | O_CREAT | O_EXCL, 0666);
if (*fd_1 < 0) {
close(*fd_0);
unlink(file0);
pr_perror("Unable to open file %s", file1);
return -1;
}
fstat(*fd_1, &buf);
inodes[1] = buf.st_ino;
*fd_2 = open(file2, O_RDWR | O_CREAT | O_EXCL, 0666);
if (*fd_2 < 0) {
close(*fd_0);
close(*fd_1);
unlink(file0);
unlink(file1);
pr_perror("Unable to open file %s", file1);
return -1;
}
fstat(*fd_2, &buf);
inodes[2] = buf.st_ino;
return 0;
}
static int check_file_lock(int fd, char *expected_type, char *expected_option, unsigned int expected_dev,
unsigned long expected_ino)
{
char buf[100], fl_flag[16], fl_type[16], fl_option[16];
int found = 0, num, fl_owner;
FILE *fp_locks = NULL;
char path[PATH_MAX];
unsigned long i_no;
int maj, min;
test_msg("check_file_lock: (fsname %s) expecting fd %d type %s option %s dev %u ino %lu\n", m->fsname, fd,
expected_type, expected_option, expected_dev, expected_ino);
snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
fp_locks = fopen(path, "r");
if (!fp_locks) {
pr_perror("Can't open %s", path);
return -1;
}
while (fgets(buf, sizeof(buf), fp_locks)) {
if (strncmp(buf, "lock:\t", 6) != 0)
continue;
test_msg("c: %s", buf);
memset(fl_flag, 0, sizeof(fl_flag));
memset(fl_type, 0, sizeof(fl_type));
memset(fl_option, 0, sizeof(fl_option));
num = sscanf(buf, "%*s %*d:%s %s %s %d %x:%x:%ld %*d %*s", fl_flag, fl_type, fl_option, &fl_owner, &maj,
&min, &i_no);
if (num < 7) {
pr_err("Invalid lock info\n");
break;
}
if (!strcmp(m->fsname, "btrfs")) {
if (MKKDEV(major(maj), minor(min)) != expected_dev)
continue;
} else {
if (makedev(maj, min) != expected_dev)
continue;
}
if (fl_owner != getpid())
continue;
if (i_no != expected_ino)
continue;
if (strcmp(fl_flag, "FLOCK"))
continue;
if (strcmp(fl_type, expected_type))
continue;
if (strcmp(fl_option, expected_option))
continue;
found++;
}
fclose(fp_locks);
return found == 1 ? 0 : -1;
}
int main(int argc, char **argv)
{
int fd_0, fd_1, fd_2, ret = 0;
test_init(argc, argv);
m = get_cwd_mnt_info();
if (!m) {
pr_perror("Can't fetch mountinfo");
return -1;
}
if (!strcmp(m->fsname, "btrfs"))
m->s_dev = kdev_to_odev(m->s_dev);
if (open_all_files(&fd_0, &fd_1, &fd_2))
return -1;
flock(fd_0, LOCK_SH);
flock(fd_1, LOCK_EX);
test_daemon();
test_waitsig();
if (check_file_lock(fd_0, "ADVISORY", "READ", dev, inodes[0])) {
fail("Failed on fd %d", fd_0);
ret |= 1;
}
if (check_file_lock(fd_1, "ADVISORY", "WRITE", dev, inodes[1])) {
fail("Failed on fd %d", fd_1);
ret |= 1;
}
if (!ret)
pass();
close(fd_0);
close(fd_1);
close(fd_2);
unlink(file0);
unlink(file1);
unlink(file2);
return ret;
}
| 3,906 | 20.005376 | 107 |
c
|
criu
|
criu-master/test/zdtm/static/grow_map.c
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include "zdtmtst.h"
const char *test_doc = "Check that VMA-s with MAP_GROWSDOWN are restored correctly";
const char *test_author = "Andrew Vagin <[email protected]>";
int main(int argc, char **argv)
{
char *start_addr, *fake_grow_down, *test_addr, *grow_down;
volatile char *p;
test_init(argc, argv);
start_addr = mmap(NULL, PAGE_SIZE * 10, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (start_addr == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
munmap(start_addr, PAGE_SIZE * 10);
fake_grow_down = mmap(start_addr + PAGE_SIZE * 5, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED | MAP_GROWSDOWN, -1, 0);
if (fake_grow_down == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
p = fake_grow_down;
*p-- = 'c';
*p = 'b';
/* overlap the guard page of fake_grow_down */
test_addr = mmap(start_addr + PAGE_SIZE * 3, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0);
if (test_addr == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
grow_down = mmap(start_addr + PAGE_SIZE * 2, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED | MAP_GROWSDOWN, -1, 0);
if (grow_down == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
test_daemon();
test_waitsig();
munmap(test_addr, PAGE_SIZE);
if (fake_grow_down[0] != 'c' || *(fake_grow_down - 1) != 'b') {
fail("%c %c", fake_grow_down[0], *(fake_grow_down - 1));
return 1;
}
p = grow_down;
*p-- = 'z';
*p = 'x';
pass();
return 0;
}
| 1,690 | 24.238806 | 101 |
c
|
criu
|
criu-master/test/zdtm/static/grow_map02.c
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <signal.h>
#include <sys/wait.h>
#include "zdtmtst.h"
const char *test_doc = "Check that a few grow-down VMA-s are restored correctly";
const char *test_author = "Andrew Vagin <[email protected]>";
int main(int argc, char **argv)
{
char *start_addr, *grow_down;
test_init(argc, argv);
start_addr = mmap(NULL, PAGE_SIZE * 10, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (start_addr == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
munmap(start_addr, PAGE_SIZE * 10);
grow_down = mmap(start_addr + PAGE_SIZE * 3, PAGE_SIZE * 3, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED | MAP_GROWSDOWN, -1, 0);
if (grow_down == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
grow_down[0 * PAGE_SIZE] = 'x';
grow_down[1 * PAGE_SIZE] = 'y';
grow_down[2 * PAGE_SIZE] = 'z';
/*
* Split the grow-down vma on three parts.
* Only the irst one will have a guard page
*/
if (mprotect(grow_down + PAGE_SIZE, PAGE_SIZE, PROT_READ)) {
pr_perror("Can't change set protection on a region of memory");
return 1;
}
test_daemon();
test_waitsig();
test_msg("%c %c %c\n", grow_down[0 * PAGE_SIZE], grow_down[1 * PAGE_SIZE], grow_down[2 * PAGE_SIZE]);
if (grow_down[0 * PAGE_SIZE] != 'x')
return 1;
if (grow_down[1 * PAGE_SIZE] != 'y')
return 1;
if (grow_down[2 * PAGE_SIZE] != 'z')
return 1;
pass();
return 0;
}
| 1,503 | 23.655738 | 102 |
c
|
criu
|
criu-master/test/zdtm/static/grow_map03.c
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include "zdtmtst.h"
const char *test_doc = "Check that VMA-s with MAP_GROWSDOWN are restored correctly";
const char *test_author = "Andrew Vagin <[email protected]>";
/*
* This test case creates two consecutive grows down vmas with a hole
* between them.
*/
int main(int argc, char **argv)
{
char *start_addr, *addr1, *addr2;
test_init(argc, argv);
start_addr = mmap(NULL, PAGE_SIZE * 10, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (start_addr == MAP_FAILED) {
pr_perror("Can't mal a new region");
return 1;
}
munmap(start_addr, PAGE_SIZE * 10);
addr1 = mmap(start_addr + PAGE_SIZE * 5, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0);
addr2 = mmap(start_addr + PAGE_SIZE * 3, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0);
test_msg("%p %p\n", addr1, addr2);
test_daemon();
test_waitsig();
pass();
return 0;
}
| 1,035 | 23.093023 | 101 |
c
|
criu
|
criu-master/test/zdtm/static/inotify00.c
|
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sched.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include "zdtmtst.h"
const char *test_doc = "Check for inotify delivery";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
#define TEST_FILE "inotify-removed"
#define TEST_LINK "inotify-hardlink"
#define BUFF_SIZE ((sizeof(struct inotify_event) + PATH_MAX))
static void decode_event_mask(char *buf, size_t size, unsigned int mask)
{
static const char *names[32] = {
[0] = "IN_ACCESS", [1] = "IN_MODIFY", [2] = "IN_ATTRIB", [3] = "IN_CLOSE_WRITE",
[4] = "IN_CLOSE_NOWRITE", [5] = "IN_OPEN", [6] = "IN_MOVED_FROM", [7] = "IN_MOVED_TO",
[8] = "IN_CREATE", [9] = "IN_DELETE", [10] = "IN_DELETE_SELF", [11] = "IN_MOVE_SELF",
[13] = "IN_UNMOUNT", [14] = "IN_Q_OVERFLOW", [15] = "IN_IGNORED",
[24] = "IN_ONLYDIR", [25] = "IN_DONT_FOLLOW", [26] = "IN_EXCL_UNLINK",
[29] = "IN_MASK_ADD", [30] = "IN_ISDIR", [31] = "IN_ONESHOT",
};
size_t i, j;
memset(buf, 0, size);
for (i = 0, j = 0; i < 32 && j < size; i++) {
if (!(mask & (1u << i)))
continue;
if (j)
j += snprintf(&buf[j], size - j, " | %s", names[i]);
else
j += snprintf(&buf[j], size - j, "%s", names[i]);
}
}
static int inotify_read_events(char *prefix, int inotify_fd, unsigned int *expected)
{
struct inotify_event *event;
char buf[BUFF_SIZE * 8];
int ret, off, n = 0;
while (1) {
ret = read(inotify_fd, buf, sizeof(buf));
if (ret < 0) {
if (errno != EAGAIN) {
pr_perror("Can't read inotify queue");
return -1;
} else {
ret = 0;
goto out;
}
} else if (ret == 0)
break;
for (off = 0; off < ret; n++, off += sizeof(*event) + event->len) {
char emask[128];
event = (void *)(buf + off);
decode_event_mask(emask, sizeof(emask), event->mask);
test_msg("\t%-16s: event %#10x -> %s\n", prefix, event->mask, emask);
if (expected)
*expected &= ~event->mask;
}
}
out:
test_msg("\t%-16s: read %2d events\n", prefix, n);
return ret;
}
int main(int argc, char *argv[])
{
unsigned int mask = IN_DELETE | IN_CLOSE_WRITE | IN_DELETE_SELF | IN_CREATE;
char test_file_path[PATH_MAX];
int fd, real_fd;
unsigned int emask;
test_init(argc, argv);
if (mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) {
pr_perror("Can't create directory %s", dirname);
exit(1);
}
#ifdef INOTIFY01
{
pid_t pid;
task_waiter_t t;
static char buf[PATH_MAX];
task_waiter_init(&t);
if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL)) {
pr_perror("Unable to remount /");
return 1;
}
pid = fork();
if (pid < 0) {
pr_perror("Can't fork a test process");
exit(1);
}
if (pid == 0) {
int fd;
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
if (unshare(CLONE_NEWNS)) {
pr_perror("Unable to unshare mount namespace");
exit(1);
}
if (mount("zdtm", dirname, "tmpfs", 0, NULL)) {
pr_perror("Unable to mount tmpfs");
exit(1);
}
fd = open(dirname, O_RDONLY);
if (fd < 0) {
pr_perror("Unable to open %s", dirname);
exit(1);
}
dup2(fd, 100);
task_waiter_complete_current(&t);
while (1)
sleep(1000);
exit(1);
}
task_waiter_wait4(&t, pid);
snprintf(buf, sizeof(buf), "/proc/%d/fd/100", pid);
dirname = buf;
}
#endif
fd = inotify_init1(IN_NONBLOCK);
if (fd < 0) {
pr_perror("inotify_init failed");
exit(1);
}
snprintf(test_file_path, sizeof(test_file_path), "%s/%s", dirname, TEST_FILE);
real_fd = open(test_file_path, O_CREAT | O_TRUNC | O_RDWR, 0644);
if (real_fd < 0) {
pr_perror("Can't create %s", test_file_path);
exit(1);
}
if (inotify_add_watch(fd, dirname, mask) < 0) {
pr_perror("inotify_add_watch failed");
exit(1);
}
if (inotify_add_watch(fd, test_file_path, mask) < 0) {
pr_perror("inotify_add_watch failed");
exit(1);
}
/*
* At this moment we have a file inside testing
* directory and a hardlink to it. The file and
* hardlink are opened.
*/
#ifndef INOTIFY01
if (unlink(test_file_path)) {
pr_perror("can't unlink %s", test_file_path);
exit(1);
}
emask = IN_DELETE;
inotify_read_events("unlink 02", fd, &emask);
if (emask) {
char emask_bits[128];
decode_event_mask(emask_bits, sizeof(emask_bits), emask);
pr_perror("Unhandled events in emask %#x -> %s", emask, emask_bits);
exit(1);
}
#endif
test_daemon();
test_waitsig();
close(real_fd);
emask = IN_CLOSE_WRITE;
inotify_read_events("after", fd, &emask);
if (emask) {
char emask_bits[128];
decode_event_mask(emask_bits, sizeof(emask_bits), emask);
fail("Unhandled events in emask %#x -> %s", emask, emask_bits);
return 1;
}
#ifndef INOTIFY01
real_fd = open(test_file_path, O_CREAT | O_TRUNC | O_RDWR, 0644);
if (real_fd < 0) {
pr_perror("Can't create %s", test_file_path);
exit(1);
}
close(real_fd);
emask = IN_CREATE | IN_CLOSE_WRITE;
inotify_read_events("after2", fd, &emask);
if (emask) {
char emask_bits[128];
decode_event_mask(emask_bits, sizeof(emask_bits), emask);
fail("Unhandled events in emask %#x -> %s", emask, emask_bits);
return 1;
}
#endif
pass();
return 0;
}
| 5,426 | 21.802521 | 93 |
c
|
criu
|
criu-master/test/zdtm/static/inotify_system.c
|
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <signal.h>
#include <string.h>
#include "zdtmtst.h"
const char *test_doc = "Inotify on symlink should be checked";
#ifndef NO_DEL
char filename[] = "file";
char linkname[] = "file.lnk";
const char *inot_dir = "./inotify";
#else
char filename[] = "file.no_del";
char linkname[] = "file.no_del.lnk";
const char *inot_dir = "./inotify.no_del";
#endif
#ifdef __NR_inotify_init
#include <sys/inotify.h>
#ifndef IN_DONT_FOLLOW
/* Missed in SLES 10 header */
#define IN_DONT_FOLLOW 0x02000000
#endif
#define EVENT_MAX 1024
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof(struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define EVENT_BUF_LEN (EVENT_MAX * (EVENT_SIZE + 16))
#define BUF_SIZE 256
#define min_value(a, b) (a < b) ? a : b
#define handle_event(MASK) \
(MASK == IN_ACCESS) ? "IN_ACCESS" : \
(MASK == IN_MODIFY) ? "IN_MODIFY" : \
(MASK == IN_ATTRIB) ? "IN_ATTRIB" : \
(MASK == IN_CLOSE) ? "IN_CLOSE" : \
(MASK == IN_CLOSE_WRITE) ? "IN_CLOSE_WRITE" : \
(MASK == IN_CLOSE_NOWRITE) ? "IN_CLOSE_NOWRITE" : \
(MASK == IN_OPEN) ? "IN_OPEN" : \
(MASK == IN_MOVED_FROM) ? "IN_MOVED_FROM" : \
(MASK == IN_MOVED_TO) ? "IN_MOVED_TO" : \
(MASK == IN_DELETE) ? "IN_DELETE" : \
(MASK == IN_CREATE) ? "IN_CREATE" : \
(MASK == IN_DELETE_SELF) ? "IN_DELETE_SELF" : \
(MASK == IN_MOVE_SELF) ? "IN_MOVE_SELF" : \
(MASK == IN_UNMOUNT) ? "IN_UNMOUNT" : \
(MASK == IN_Q_OVERFLOW) ? "IN_Q_OVERFLOW" : \
(MASK == IN_IGNORED) ? "IN_IGNORED" : \
"UNKNOWN"
#include <unistd.h>
#include <fcntl.h>
typedef struct {
int infd;
int file;
int link;
int dir;
} desc;
void do_wait(void)
{
test_daemon();
test_waitsig();
}
int createFiles(char *path, char *target, char *link)
{
int fd;
fd = open(path, O_CREAT, 0644);
if (fd < 0) {
pr_perror("can't open %s", path);
return -1;
}
close(fd);
if (symlink(target, link) < 0) {
pr_perror("can't symlink %s to %s", path, link);
return -1;
}
return 0;
}
int addWatcher(int fd, const char *path)
{
int wd;
wd = inotify_add_watch(fd, path, IN_ALL_EVENTS | IN_DONT_FOLLOW);
if (wd < 0) {
pr_perror("inotify_add_watch(%d, %s, IN_ALL_EVENTS) failed", fd, path);
return -1;
}
return wd;
}
int fChmod(char *path)
{
if (chmod(path, 0755) < 0) {
pr_perror("chmod(%s, 0755) failed", path);
return -1;
}
return 0;
}
int fWriteClose(char *path)
{
int fd = open(path, O_RDWR | O_CREAT, 0700);
if (fd == -1) {
pr_perror("open(%s, O_RDWR|O_CREAT, 0700) failed", path);
return -1;
}
if (write(fd, "string", 7) == -1) {
pr_perror("write(%d, %s, 1) failed", fd, path);
return -1;
}
if (close(fd) == -1) {
pr_perror("close(%s) failed", path);
return -1;
}
return 0;
}
int fNoWriteClose(char *path)
{
char buf[BUF_SIZE];
int fd = open(path, O_RDONLY);
if (fd < 0) {
pr_perror("open(%s, O_RDONLY) failed", path);
return -1;
}
if (read(fd, buf, BUF_SIZE) == -1) {
pr_perror("read");
close(fd);
return -1;
}
if (close(fd) == -1) {
pr_perror("close(%s) failed", path);
return -1;
}
return 0;
}
int fMove(char *from, char *to)
{
if (rename(from, to) == -1) {
pr_perror("rename error (from: %s to: %s)", from, to);
return -1;
}
return 0;
}
desc init_env(const char *dir, char *file_path, char *link_path)
{
desc in_desc = { -1, -1, -1, -1 };
if (mkdir(dir, 0777) < 0) {
pr_perror("mkdir(%s)", dir);
return in_desc;
}
in_desc.infd = inotify_init();
if (in_desc.infd < 0) {
pr_perror("inotify_init() failed");
rmdir(dir);
return in_desc;
}
if (snprintf(file_path, BUF_SIZE, "%s/%s", dir, filename) >= BUF_SIZE) {
pr_err("filename %s is too long\n", filename);
rmdir(dir);
return in_desc;
}
if (snprintf(link_path, BUF_SIZE, "%s/%s", dir, linkname) >= BUF_SIZE) {
pr_err("filename %s is too long\n", linkname);
rmdir(dir);
return in_desc;
}
in_desc.dir = addWatcher(in_desc.infd, dir);
if (createFiles(file_path, filename, link_path)) {
return in_desc;
}
in_desc.link = addWatcher(in_desc.infd, link_path);
in_desc.file = addWatcher(in_desc.infd, file_path);
return in_desc;
}
int fDelete(char *path)
{
if (unlink(path) != 0) {
pr_perror("unlink(%s)", path);
return -1;
}
return 0;
}
int fRemDir(const char *target)
{
if (rmdir(target)) {
pr_perror("rmdir(%s)", target);
return -1;
}
return 0;
}
int test_actions(const char *dir, char *file_path, char *link_path)
{
if (fChmod(link_path) == 0 && fWriteClose(link_path) == 0 && fNoWriteClose(link_path) == 0 &&
fMove(file_path, filename) == 0 && fMove(filename, file_path) == 0
#ifndef NO_DEL
&& fDelete(file_path) == 0 && fDelete(link_path) == 0 && fRemDir(dir) == 0
#endif
) {
return 0;
}
return -1;
}
void dump_events(char *buf, int len)
{
int marker = 0;
struct inotify_event *event;
while (marker < len) {
event = (struct inotify_event *)&buf[marker];
test_msg("\t%s (%x mask, %d len", handle_event(event->mask), event->mask, event->len);
if (event->len)
test_msg(", '%s' name", event->name);
test_msg(")\n");
marker += EVENT_SIZE + event->len;
}
}
int harmless(int mask)
{
switch (mask) {
case IN_CLOSE_NOWRITE:
case IN_ATTRIB:
return 1;
}
return 0;
}
int errors(int exp_len, int len, char *etalon_buf, char *buf)
{
int marker = 0;
int error = 0;
while (marker < len) {
struct inotify_event *event;
struct inotify_event *exp_event;
event = (struct inotify_event *)&buf[marker];
/* It's OK if some additional events are recevived */
if (marker < exp_len)
exp_event = (struct inotify_event *)&etalon_buf[marker];
else {
if (!harmless(event->mask)) {
fail("got unexpected event %s (%x mask)", handle_event(event->mask), event->mask);
error++;
}
goto next_event;
}
if (event->mask != exp_event->mask) {
fail("Handled %s (%x mask), expected %s (%x mask)", handle_event(event->mask), event->mask,
handle_event(exp_event->mask), exp_event->mask);
error++;
}
if (event->len != exp_event->len) {
fail("Incorrect length of field name.");
error++;
break;
} else if (event->len && strncmp(event->name, exp_event->name, event->len)) {
fail("Handled file name %s, expected %s", event->name, exp_event->name);
error++;
}
next_event:
marker += EVENT_SIZE + event->len;
}
return error;
}
int read_set(int inot_fd, char *event_set)
{
int len;
if ((len = read(inot_fd, event_set, EVENT_BUF_LEN)) < 0) {
pr_perror("read(%d, buf, %lu) failed", inot_fd, (unsigned long)EVENT_BUF_LEN);
return -1;
}
return len;
}
void common_close(desc *descr)
{
if (descr->infd > 0) {
close(descr->infd);
descr->infd = -1;
descr->file = -1;
descr->dir = -1;
descr->link = -1;
}
}
int get_event_set(char *event_set, int wait)
{
int len;
char link_path[BUF_SIZE];
char file_path[BUF_SIZE];
desc common_desc;
common_desc = init_env(inot_dir, file_path, link_path);
if ((common_desc.infd < 0) || (common_desc.file < 0) || (common_desc.dir < 0) || (common_desc.link < 0)) {
common_close(&common_desc);
return -1;
}
if (test_actions(inot_dir, file_path, link_path) < 0) {
common_close(&common_desc);
return -1;
}
if (wait) {
do_wait();
}
len = read_set(common_desc.infd, event_set);
common_close(&common_desc);
#ifdef NO_DEL
if (!(fDelete(file_path) == 0 && fDelete(link_path) == 0 && fRemDir(inot_dir) == 0))
return -1;
#endif
return len;
}
int check(int len, char *event_set, int exp_len, char *etalon_event_set)
{
if ((exp_len < 0) || (len < 0)) {
fail("Error in preparing event sets.");
return -1;
}
if (len < exp_len) {
fail("Events are lost. Read: %d, Expected: %d", len, exp_len);
test_msg("expected events\n");
dump_events(etalon_event_set, exp_len);
test_msg("real events\n");
dump_events(event_set, len);
return -1;
}
if (errors(exp_len, len, etalon_event_set, event_set) == 0) {
pass();
return 0;
}
return -1;
}
int main(int argc, char **argv)
{
int exp_len = -1, len = -1;
char etalon_event_set[EVENT_BUF_LEN];
char event_set[EVENT_BUF_LEN];
test_init(argc, argv);
exp_len = get_event_set(etalon_event_set, 0);
len = get_event_set(event_set, 1);
if (check(len, event_set, exp_len, etalon_event_set)) {
return 1;
}
return 0;
}
#else
int main(int argc, char **argv)
{
test_init(argc, argv);
skip("Inotify not supported.");
return 0;
}
#endif //__NR_inotify_init
| 8,715 | 21.638961 | 107 |
c
|
criu
|
criu-master/test/zdtm/static/ipc_namespace.c
|
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <linux/msg.h>
#include <linux/sem.h>
#include <linux/shm.h>
#include <fcntl.h>
#include <limits.h>
#include "zdtmtst.h"
#define CLONE_NEWIPC 0x08000000
extern int msgctl(int __msqid, int __cmd, struct msqid_ds *__buf);
extern int semctl(int __semid, int __semnum, int __cmd, ...);
extern int shmctl(int __shmid, int __cmd, struct shmid_ds *__buf);
struct ipc_ids {
int in_use; /* TODO: Check for 0 */
// unsigned short seq;
// unsigned short seq_max;
// struct rw_semaphore rw_mutex;
// struct idr ipcs_idr; /* TODO */
};
struct ipc_ns {
struct ipc_ids ids[3];
int sem_ctls[4];
int used_sems;
int msg_ctlmax;
int msg_ctlmnb;
int msg_ctlmni;
int msg_bytes;
int msg_hdrs;
int auto_msgmni;
int msg_next_id;
int sem_next_id;
int shm_next_id;
size_t shm_ctlmax;
size_t shm_ctlall;
int shm_ctlmni;
int shm_tot;
int shm_rmid_forced;
// struct vfsmount *mq_mnt;
// unsigned int mq_queues_count;
unsigned int mq_queues_max; /* initialized to DFLT_QUEUESMAX */
unsigned int mq_msg_max; /* initialized to DFLT_MSGMAX */
unsigned int mq_msgsize_max; /* initialized to DFLT_MSGSIZEMAX */
unsigned int mq_msg_default; /* initialized to DFLT_MSG */
unsigned int mq_msgsize_default; /* initialized to DFLT_MSGSIZE */
struct user_ns *user_ns;
};
#define IPC_SEM_IDS 0
#define IPC_MSG_IDS 1
#define IPC_SHM_IDS 2
const char *test_doc = "Check that ipc ns context migrated successfully";
const char *test_author = "Stanislav Kinsbursky <[email protected]>";
struct ipc_ns ipc_before, ipc_after;
static int read_ipc_sysctl(char *name, int *data, size_t size)
{
int fd;
int ret;
char buf[32];
fd = open(name, O_RDONLY);
if (fd < 0) {
pr_perror("Can't open %s", name);
return fd;
}
ret = read(fd, buf, 32);
if (ret < 0) {
pr_perror("Can't read %s", name);
ret = -errno;
goto err;
}
*data = (int)strtoul(buf, NULL, 10);
ret = 0;
err:
close(fd);
return ret;
}
static int get_messages_info(struct ipc_ns *ipc)
{
struct msginfo info;
int ret;
ret = msgctl(0, MSG_INFO, (struct msqid_ds *)&info);
if (ret < 0) {
pr_perror("msgctl failed");
return ret;
}
ipc->msg_ctlmax = info.msgmax;
ipc->msg_ctlmnb = info.msgmnb;
ipc->msg_ctlmni = info.msgmni;
ipc->msg_bytes = info.msgtql;
ipc->msg_hdrs = info.msgmap;
ipc->ids[IPC_MSG_IDS].in_use = info.msgpool;
if (read_ipc_sysctl("/proc/sys/kernel/auto_msgmni", &ipc->auto_msgmni, sizeof(ipc->auto_msgmni)))
return -1;
if (read_ipc_sysctl("/proc/sys/kernel/msg_next_id", &ipc->msg_next_id, sizeof(ipc->msg_next_id)))
return -1;
if (read_ipc_sysctl("/proc/sys/kernel/sem_next_id", &ipc->sem_next_id, sizeof(ipc->sem_next_id)))
return -1;
if (read_ipc_sysctl("/proc/sys/kernel/shm_next_id", &ipc->shm_next_id, sizeof(ipc->shm_next_id)))
return -1;
if (read_ipc_sysctl("/proc/sys/fs/mqueue/queues_max", (int *)&ipc->mq_queues_max, sizeof(ipc->mq_queues_max)))
return -1;
if (read_ipc_sysctl("/proc/sys/fs/mqueue/msg_max", (int *)&ipc->mq_msg_max, sizeof(ipc->mq_msg_max)))
return -1;
if (read_ipc_sysctl("/proc/sys/fs/mqueue/msgsize_max", (int *)&ipc->mq_msgsize_max,
sizeof(ipc->mq_msgsize_max)))
return -1;
if (read_ipc_sysctl("/proc/sys/fs/mqueue/msg_default", (int *)&ipc->mq_msg_default,
sizeof(ipc->mq_msg_default)))
return -1;
if (read_ipc_sysctl("/proc/sys/fs/mqueue/msgsize_default", (int *)&ipc->mq_msgsize_default,
sizeof(ipc->mq_msgsize_default)))
return -1;
return 0;
}
static int get_semaphores_info(struct ipc_ns *ipc)
{
int err;
struct seminfo info;
err = semctl(0, 0, SEM_INFO, &info);
if (err < 0)
pr_perror("semctl failed");
ipc->sem_ctls[0] = info.semmsl;
ipc->sem_ctls[1] = info.semmns;
ipc->sem_ctls[2] = info.semopm;
ipc->sem_ctls[3] = info.semmni;
ipc->used_sems = info.semaem;
ipc->ids[IPC_SEM_IDS].in_use = info.semusz;
return 0;
}
static int get_shared_memory_info(struct ipc_ns *ipc)
{
int ret;
union {
struct shminfo64 shminfo64;
struct shm_info shminfo;
struct shmid_ds shmid;
} u;
ret = shmctl(0, IPC_INFO, &u.shmid);
if (ret < 0)
pr_perror("semctl failed");
ipc->shm_ctlmax = u.shminfo64.shmmax;
ipc->shm_ctlall = u.shminfo64.shmall;
ipc->shm_ctlmni = u.shminfo64.shmmni;
ret = shmctl(0, SHM_INFO, &u.shmid);
if (ret < 0)
pr_perror("semctl failed");
ipc->shm_tot = u.shminfo.shm_tot;
ipc->ids[IPC_SHM_IDS].in_use = u.shminfo.used_ids;
if (read_ipc_sysctl("/proc/sys/kernel/shm_rmid_forced", &ipc->shm_rmid_forced, sizeof(ipc->shm_rmid_forced)))
return -1;
return 0;
}
int fill_ipc_ns(struct ipc_ns *ipc)
{
int ret;
ret = get_messages_info(ipc);
if (ret < 0) {
pr_err("Failed to collect messages\n");
return ret;
}
ret = get_semaphores_info(ipc);
if (ret < 0) {
pr_err("Failed to collect semaphores\n");
return ret;
}
ret = get_shared_memory_info(ipc);
if (ret < 0) {
pr_err("Failed to collect shared memory\n");
return ret;
}
return 0;
}
static int rand_ipc_sysctl(char *name, unsigned int val)
{
int fd;
int ret;
char buf[32];
fd = open(name, O_WRONLY);
if (fd < 0) {
pr_perror("Can't open %s", name);
return fd;
}
sprintf(buf, "%d\n", val);
ret = write(fd, buf, strlen(buf));
if (ret < 0) {
pr_perror("Can't write %u into %s", val, name);
return -errno;
}
close(fd);
return 0;
}
#define MAX_MNI (1 << 15)
static int rand_ipc_sem(void)
{
int fd;
int ret;
char buf[128];
char *name = "/proc/sys/kernel/sem";
fd = open(name, O_WRONLY);
if (fd < 0) {
pr_perror("Can't open %s", name);
return fd;
}
sprintf(buf, "%d %d %d %d\n", (unsigned)lrand48(), (unsigned)lrand48(), (unsigned)lrand48(),
(unsigned)lrand48() % MAX_MNI);
ret = write(fd, buf, 128);
if (ret < 0) {
pr_perror("Can't write %s", name);
return -errno;
}
close(fd);
return 0;
}
static int rand_ipc_ns(void)
{
int ret;
ret = rand_ipc_sem();
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/msgmax", (unsigned)lrand48());
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/msgmnb", (unsigned)lrand48());
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/msgmni", (unsigned)lrand48() % MAX_MNI);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/auto_msgmni", 0);
if (!ret && (unsigned)lrand48() % 2)
ret = rand_ipc_sysctl("/proc/sys/kernel/msg_next_id", (unsigned)lrand48() % ((unsigned)INT_MAX + 1));
if (!ret && (unsigned)lrand48() % 2)
ret = rand_ipc_sysctl("/proc/sys/kernel/sem_next_id", (unsigned)lrand48() % ((unsigned)INT_MAX + 1));
if (!ret && (unsigned)lrand48() % 2)
ret = rand_ipc_sysctl("/proc/sys/kernel/shm_next_id", (unsigned)lrand48() % ((unsigned)INT_MAX + 1));
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/shmmax", (unsigned)lrand48());
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/shmall", (unsigned)lrand48());
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/shmmni", (unsigned)lrand48() % MAX_MNI);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/kernel/shm_rmid_forced", (unsigned)lrand48() & 1);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/fs/mqueue/queues_max", (((unsigned)lrand48()) % 1023) + 1);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/fs/mqueue/msg_max", ((unsigned)lrand48() % 65536) + 1);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/fs/mqueue/msgsize_max",
((unsigned)lrand48() & (8192 * 128 - 1)) | 128);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/fs/mqueue/msg_default", ((unsigned)lrand48() % 65536) + 1);
if (!ret)
ret = rand_ipc_sysctl("/proc/sys/fs/mqueue/msgsize_default",
((unsigned)lrand48() & (8192 * 128 - 1)) | 128);
if (ret < 0)
pr_err("Failed to randomize ipc namespace tunables\n");
return ret;
}
static void show_ipc_entry(struct ipc_ns *old, struct ipc_ns *new)
{
int i;
for (i = 0; i < 3; i++) {
if (old->ids[i].in_use != new->ids[i].in_use)
pr_err("ids[%d].in_use differs: %d ---> %d\n", i, old->ids[i].in_use, new->ids[i].in_use);
}
for (i = 0; i < 4; i++) {
if (old->sem_ctls[i] != new->sem_ctls[i])
pr_err("sem_ctls[%d] differs: %d ---> %d\n", i, old->sem_ctls[i], new->sem_ctls[i]);
}
if (old->msg_ctlmax != new->msg_ctlmax)
pr_err("msg_ctlmax differs: %d ---> %d\n", old->msg_ctlmax, new->msg_ctlmax);
if (old->msg_ctlmnb != new->msg_ctlmnb)
pr_err("msg_ctlmnb differs: %d ---> %d\n", old->msg_ctlmnb, new->msg_ctlmnb);
if (old->msg_ctlmni != new->msg_ctlmni)
pr_err("msg_ctlmni differs: %d ---> %d\n", old->msg_ctlmni, new->msg_ctlmni);
if (old->auto_msgmni != new->auto_msgmni)
pr_err("auto_msgmni differs: %d ---> %d\n", old->auto_msgmni, new->auto_msgmni);
if (old->msg_next_id != new->msg_next_id)
pr_err("msg_next_id differs: %d ---> %d\n", old->msg_next_id, new->msg_next_id);
if (old->sem_next_id != new->sem_next_id)
pr_err("sem_next_id differs: %d ---> %d\n", old->sem_next_id, new->sem_next_id);
if (old->shm_next_id != new->shm_next_id)
pr_err("shm_next_id differs: %d ---> %d\n", old->shm_next_id, new->shm_next_id);
if (old->shm_ctlmax != new->shm_ctlmax)
pr_err("shm_ctlmax differs: %zu ---> %zu\n", old->shm_ctlmax, new->shm_ctlmax);
if (old->shm_ctlall != new->shm_ctlall)
pr_err("shm_ctlall differs: %zu ---> %zu\n", old->shm_ctlall, new->shm_ctlall);
if (old->shm_ctlmni != new->shm_ctlmni)
pr_err("shm_ctlmni differs: %d ---> %d\n", old->shm_ctlmni, new->shm_ctlmni);
if (old->shm_rmid_forced != new->shm_rmid_forced)
pr_err("shm_rmid_forced differs: %d ---> %d\n", old->shm_rmid_forced, new->shm_rmid_forced);
if (old->mq_queues_max != new->mq_queues_max)
pr_err("mq_queues_max differs: %d ---> %d\n", old->mq_queues_max, new->mq_queues_max);
if (old->mq_msg_max != new->mq_msg_max)
pr_err("mq_msg_max differs: %d ---> %d\n", old->mq_msg_max, new->mq_msg_max);
if (old->mq_msgsize_max != new->mq_msgsize_max)
pr_err("mq_msgsize_max differs: %d ---> %d\n", old->mq_msgsize_max, new->mq_msgsize_max);
if (old->mq_msg_default != new->mq_msg_default)
pr_err("mq_msg_default differs: %d ---> %d\n", old->mq_msg_default, new->mq_msg_default);
if (old->mq_msgsize_default != new->mq_msgsize_default)
pr_err("mq_msgsize_default differs: %d ---> %d\n", old->mq_msgsize_default, new->mq_msgsize_default);
}
int main(int argc, char **argv)
{
int ret;
test_init(argc, argv);
ret = rand_ipc_ns();
if (ret) {
pr_err("Failed to randomize ipc ns before migration\n");
return -1;
}
ret = fill_ipc_ns(&ipc_before);
if (ret) {
pr_err("Failed to collect ipc ns before migration\n");
return ret;
}
test_daemon();
test_waitsig();
ret = fill_ipc_ns(&ipc_after);
if (ret) {
pr_err("Failed to collect ipc ns after migration\n");
return ret;
}
if (memcmp(&ipc_before, &ipc_after, sizeof(ipc_after))) {
pr_err("IPCs differ\n");
show_ipc_entry(&ipc_before, &ipc_after);
return -EINVAL;
}
pass();
return 0;
}
| 10,847 | 26.886889 | 111 |
c
|
criu
|
criu-master/test/zdtm/static/maps00.c
|
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <setjmp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "zdtmtst.h"
const char *test_doc = "Create all sorts of maps and compare /proc/pid/maps\n"
"before and after migration\n";
const char *test_author = "Pavel Emelianov <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
const static int map_prots[] = {
PROT_NONE,
PROT_READ,
PROT_READ | PROT_WRITE,
PROT_READ | PROT_WRITE | PROT_EXEC,
};
#define NUM_MPROTS sizeof(map_prots) / sizeof(int)
#define RW_PROT(x) ((x) & (PROT_READ | PROT_WRITE))
#define X_PROT(x) ((x)&PROT_EXEC)
int check_prot(int src_prot, int dst_prot)
{
if (RW_PROT(src_prot) != RW_PROT(dst_prot))
return 0;
/* If exec bit will be enabled may depend on NX capability of CPUs of
* source and destination nodes. In any case, migrated mapping should
* not have less permissions than newly created one
**
* A is a subset of B iff (A & B) == A
*/
return (X_PROT(dst_prot) & X_PROT(src_prot)) == X_PROT(dst_prot);
}
const static int map_flags[] = { MAP_PRIVATE, MAP_SHARED, MAP_PRIVATE | MAP_ANONYMOUS, MAP_SHARED | MAP_ANONYMOUS };
#define NUM_MFLAGS sizeof(map_flags) / sizeof(int)
#define NUM_MAPS NUM_MPROTS *NUM_MFLAGS
#define ONE_MAP_SIZE 0x2000
struct map {
int prot;
int prot_real;
int flag;
char filename[256];
int fd;
void *ptr;
};
static void init_map(struct map *map, int prot_no, int flag_no)
{
map->fd = -1;
map->prot = map_prots[prot_no];
map->flag = map_flags[flag_no];
}
static int make_map(struct map *map)
{
uint32_t crc;
uint8_t buf[ONE_MAP_SIZE];
static int i = 0;
if (!(map->flag & MAP_ANONYMOUS)) {
/* need file */
if (snprintf(map->filename, sizeof(map->filename), "%s-%02d", filename, i++) >= sizeof(map->filename)) {
pr_perror("filename %s is too long", filename);
return -1;
}
map->fd = open(map->filename, O_RDWR | O_CREAT, 0600);
if (map->fd < 0) {
pr_perror("can't open %s", map->filename);
return -1;
}
crc = ~0;
datagen(buf, sizeof(buf), &crc);
if (write(map->fd, buf, sizeof(buf)) != sizeof(buf)) {
pr_perror("failed to write %s", map->filename);
return -1;
}
}
map->ptr = mmap(NULL, ONE_MAP_SIZE, map->prot, map->flag, map->fd, 0);
if (map->ptr == MAP_FAILED) {
pr_perror("can't create mapping");
return -1;
}
if ((map->flag & MAP_ANONYMOUS) && (map->prot & PROT_WRITE)) {
/* can't fill it with data otherwise */
crc = ~0;
datagen(map->ptr, ONE_MAP_SIZE, &crc);
}
test_msg("map: ptr %p flag %8x prot %8x\n", map->ptr, map->flag, map->prot);
return 0;
}
static sigjmp_buf segv_ret; /* we need sig*jmp stuff, otherwise SIGSEGV will reset our handler */
static void segfault(int signo)
{
siglongjmp(segv_ret, 1);
}
/*
* after test func should be placed check map, because size of test_func
* is calculated as (check_map-test_func)
*/
int test_func(void)
{
return 1;
}
static int check_map(struct map *map)
{
int prot = PROT_WRITE | PROT_READ | PROT_EXEC;
if (signal(SIGSEGV, segfault) == SIG_ERR) {
fail("setting SIGSEGV handler failed");
return -1;
}
if (!sigsetjmp(segv_ret, 1)) {
uint32_t crc = ~0;
if (datachk(map->ptr, ONE_MAP_SIZE, &crc)) /* perform read access */
if (!(map->flag & MAP_ANONYMOUS) ||
(map->prot & PROT_WRITE)) { /* anon maps could only be filled when r/w */
fail("CRC mismatch: ptr %p flag %8x prot %8x", map->ptr, map->flag, map->prot);
return -1;
}
/* prot |= PROT_READ// need barrier before this line,
because compiler change order commands.
I finded one method: look at next lines*/
} else
prot &= PROT_WRITE | !PROT_READ | PROT_EXEC;
if (signal(SIGSEGV, segfault) == SIG_ERR) {
fail("setting SIGSEGV handler failed");
return -1;
}
if (!sigsetjmp(segv_ret, 1)) {
*(int *)(map->ptr) = 1234; /* perform write access */
} else
prot &= !PROT_WRITE | PROT_READ | PROT_EXEC;
if (signal(SIGSEGV, segfault) == SIG_ERR) {
fail("restoring SIGSEGV handler failed");
return -1;
}
if (!sigsetjmp(segv_ret, 1)) {
if (map->prot & PROT_WRITE) {
memcpy(map->ptr, test_func, ONE_MAP_SIZE);
/* The ARM ARM architecture does not require the
* hardware to ensure coherency between instruction
* caches and memory, flushing dcache and icache is
* necessory to prevent SIGILL signal.
*/
__builtin___clear_cache(map->ptr, map->ptr + ONE_MAP_SIZE);
} else {
if (!(map->flag & MAP_ANONYMOUS)) {
uint8_t funlen = (uint8_t *)check_map - (uint8_t *)test_func;
lseek(map->fd, 0, SEEK_SET);
if (write(map->fd, test_func, funlen) < funlen) {
pr_perror("failed to write %s", map->filename);
return -1;
}
}
}
if (!(map->flag & MAP_ANONYMOUS) || map->prot & PROT_WRITE)
/* Function body has been copied into the mapping */
((int (*)(void))map->ptr)(); /* perform exec access */
else
/* No way to copy function body into mapping,
* clear exec bit from effective protection
*/
prot &= PROT_WRITE | PROT_READ | !PROT_EXEC;
} else
prot &= PROT_WRITE | PROT_READ | !PROT_EXEC;
if (signal(SIGSEGV, SIG_DFL) == SIG_ERR) {
fail("restoring SIGSEGV handler failed");
return -1;
}
return prot;
}
static void destroy_map(struct map *map)
{
munmap(map->ptr, ONE_MAP_SIZE);
if (map->fd >= 0) {
close(map->fd);
unlink(map->filename);
}
}
#define MAPS_LEN 0x10000
int main(int argc, char **argv)
{
struct map maps[NUM_MAPS] = {}, maps_compare[NUM_MAPS] = {};
int i, j, k;
test_init(argc, argv);
k = 0;
for (i = 0; i < NUM_MPROTS; i++)
for (j = 0; j < NUM_MFLAGS; j++)
init_map(maps + k++, i, j);
for (i = 0; i < NUM_MAPS; i++)
if (make_map(maps + i))
goto err;
test_daemon();
test_waitsig();
for (i = 0; i < NUM_MAPS; i++)
if ((maps[i].prot_real = check_map(maps + i)) < 0)
goto err;
k = 0;
for (i = 0; i < NUM_MPROTS; i++)
for (j = 0; j < NUM_MFLAGS; j++)
init_map(maps_compare + k++, i, j);
for (i = 0; i < NUM_MAPS; i++)
if (make_map(maps_compare + i))
goto err;
for (i = 0; i < NUM_MAPS; i++)
if ((maps_compare[i].prot_real = check_map(maps_compare + i)) < 0)
goto err;
for (i = 0; i < NUM_MAPS; i++)
if (!check_prot(maps[i].prot_real, maps_compare[i].prot_real)) {
fail("protection on %i (flag=%d prot=%d) maps has changed (prot=%d(expected %d))", i,
maps[i].flag, maps[i].prot, maps[i].prot_real, maps_compare[i].prot_real);
goto err;
}
pass();
for (i = 0; i < NUM_MAPS; i++) {
destroy_map(maps + i);
destroy_map(maps_compare + i);
}
return 0;
err:
return 1;
}
| 6,667 | 24.844961 | 116 |
c
|
criu
|
criu-master/test/zdtm/static/maps01.c
|
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include "zdtmtst.h"
#define MEM_SIZE (1LU << 30)
#define MEM_OFFSET (1LU << 29)
#define MEM_OFFSET2 (MEM_SIZE - PAGE_SIZE)
#define MEM_OFFSET3 (20LU * PAGE_SIZE)
const char *test_doc = "Test shared memory";
const char *test_author = "Andrew Vagin <[email protected]";
int main(int argc, char **argv)
{
void *m, *m2, *p, *p2;
char path[PATH_MAX];
uint32_t crc;
pid_t pid = -1;
int status, fd;
task_waiter_t t;
test_init(argc, argv);
task_waiter_init(&t);
m = mmap(NULL, MEM_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (m == MAP_FAILED) {
pr_perror("Failed to mmap %lu Mb shared anonymous R/W memory", MEM_SIZE >> 20);
goto err;
}
p = mmap(NULL, MEM_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) {
pr_perror("Failed to mmap %ld Mb shared anonymous R/W memory", MEM_SIZE >> 20);
goto err;
}
p2 = mmap(NULL, MEM_OFFSET, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p2 == MAP_FAILED) {
pr_perror("Failed to mmap %lu Mb anonymous memory", MEM_OFFSET >> 20);
goto err;
}
pid = test_fork();
if (pid < 0) {
pr_err("Fork failed with %d\n", pid);
goto err;
} else if (pid == 0) {
void *p3;
p3 = mmap(NULL, MEM_OFFSET3, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p3 == MAP_FAILED) {
pr_perror("Failed to mmap %lu Mb anonymous R/W memory", MEM_OFFSET3 >> 20);
goto err;
}
crc = ~0;
datagen(m + MEM_OFFSET, PAGE_SIZE, &crc);
crc = ~0;
datagen(m + MEM_OFFSET2, PAGE_SIZE, &crc);
crc = ~0;
datagen(p + MEM_OFFSET + MEM_OFFSET3, PAGE_SIZE, &crc);
crc = ~0;
datagen(p + MEM_OFFSET + 2 * MEM_OFFSET3, PAGE_SIZE, &crc);
crc = ~0;
datagen(p + MEM_OFFSET3, PAGE_SIZE, &crc);
crc = ~0;
datagen(p3, PAGE_SIZE, &crc);
task_waiter_complete(&t, 1);
test_waitsig();
crc = ~0;
status = datachk(m + MEM_OFFSET, PAGE_SIZE, &crc);
if (status)
return 1;
crc = ~0;
status = datachk(m + MEM_OFFSET2, PAGE_SIZE, &crc);
if (status)
return 1;
crc = ~0;
status = datachk(m + PAGE_SIZE, PAGE_SIZE, &crc);
if (status)
return 1;
crc = ~0;
status = datachk(p + MEM_OFFSET + 2 * MEM_OFFSET3, PAGE_SIZE, &crc);
if (status)
return 1;
crc = ~0;
status = datachk(p + MEM_OFFSET3, PAGE_SIZE, &crc);
if (status)
return 1;
crc = ~0;
status = datachk(p3, PAGE_SIZE, &crc);
if (status)
return 1;
return 0;
}
task_waiter_wait4(&t, 1);
munmap(p, MEM_OFFSET);
p2 = mremap(p + MEM_OFFSET, MEM_OFFSET, MEM_OFFSET, MREMAP_FIXED | MREMAP_MAYMOVE, p2);
if (p2 == MAP_FAILED)
goto err;
snprintf(path, PATH_MAX, "/proc/self/map_files/%lx-%lx", (unsigned long)m, (unsigned long)m + MEM_SIZE);
fd = open(path, O_RDWR);
if (fd == -1) {
pr_perror("Can't open file %s", path);
goto err;
}
m2 = mmap(NULL, PAGE_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, fd, MEM_OFFSET3);
if (m2 == MAP_FAILED) {
pr_perror("Can't map file %s", path);
goto err;
}
close(fd);
munmap(m, PAGE_SIZE);
munmap(m + PAGE_SIZE * 10, PAGE_SIZE);
munmap(m + MEM_OFFSET2, PAGE_SIZE);
crc = ~0;
datagen(m + PAGE_SIZE, PAGE_SIZE, &crc);
crc = ~0;
datagen(m2, PAGE_SIZE, &crc);
test_daemon();
test_waitsig();
kill(pid, SIGTERM);
wait(&status);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status))
goto err;
} else
goto err;
crc = ~0;
if (datachk(m + MEM_OFFSET, PAGE_SIZE, &crc))
goto err;
crc = ~0;
if (datachk(m2, PAGE_SIZE, &crc))
goto err;
crc = ~0;
if (datachk(p2 + MEM_OFFSET3, PAGE_SIZE, &crc))
goto err;
pass();
return 0;
err:
if (waitpid(-1, NULL, WNOHANG) == 0) {
kill(pid, SIGTERM);
wait(NULL);
}
return 1;
}
| 3,874 | 21.142857 | 105 |
c
|
criu
|
criu-master/test/zdtm/static/maps02.c
|
#include <sys/mman.h>
#include "zdtmtst.h"
#include "get_smaps_bits.h"
#ifndef MADV_DONTDUMP
#define MADV_DONTDUMP 16
#endif
const char *test_doc = "Test shared memory with advises";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
struct mmap_data {
void *start;
unsigned long orig_flags;
unsigned long orig_madv;
unsigned long new_flags;
unsigned long new_madv;
};
#define MEM_SIZE (8192)
static int alloc_anon_mmap(struct mmap_data *m, int flags, int adv)
{
m->start = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, flags, -1, 0);
if (m->start == MAP_FAILED) {
pr_perror("mmap failed");
return -1;
}
if (madvise(m->start, MEM_SIZE, adv)) {
if (errno == EINVAL) {
test_msg("madvise failed, no kernel support\n");
munmap(m->start, MEM_SIZE);
*m = (struct mmap_data){};
} else {
pr_perror("madvise failed");
return -1;
}
}
return 0;
}
int main(int argc, char **argv)
{
struct mmap_data m[5] = {};
size_t i;
test_init(argc, argv);
test_msg("Alloc growsdown\n");
if (alloc_anon_mmap(&m[0], MAP_PRIVATE | MAP_ANONYMOUS, MADV_DONTFORK))
return -1;
test_msg("Alloc locked/sequential\n");
if (alloc_anon_mmap(&m[1], MAP_PRIVATE | MAP_ANONYMOUS | MAP_LOCKED, MADV_SEQUENTIAL))
return -1;
test_msg("Alloc noreserve/dontdump\n");
if (alloc_anon_mmap(&m[2], MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, MADV_DONTDUMP))
return -1;
test_msg("Alloc hugetlb/hugepage\n");
if (alloc_anon_mmap(&m[3], MAP_PRIVATE | MAP_ANONYMOUS, MADV_HUGEPAGE))
return -1;
test_msg("Alloc dontfork/random|mergeable\n");
if (alloc_anon_mmap(&m[4], MAP_PRIVATE | MAP_ANONYMOUS, MADV_MERGEABLE))
return -1;
test_msg("Fetch existing flags/adv\n");
for (i = 0; i < sizeof(m) / sizeof(m[0]); i++) {
if (get_smaps_bits((unsigned long)m[i].start, &m[i].orig_flags, &m[i].orig_madv))
return -1;
}
test_daemon();
test_waitsig();
test_msg("Fetch restored flags/adv\n");
for (i = 0; i < sizeof(m) / sizeof(m[0]); i++) {
if (get_smaps_bits((unsigned long)m[i].start, &m[i].new_flags, &m[i].new_madv))
return -1;
if (m[i].orig_flags != m[i].new_flags) {
pr_perror("Flags are changed %lx %lx -> %lx (%zu)", (unsigned long)m[i].start, m[i].orig_flags,
m[i].new_flags, i);
fail();
return -1;
}
if (m[i].orig_madv != m[i].new_madv) {
pr_perror("Madvs are changed %lx %lx -> %lx (%zu)", (unsigned long)m[i].start, m[i].orig_madv,
m[i].new_madv, i);
fail();
return -1;
}
}
pass();
return 0;
}
| 2,495 | 23 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/maps05.c
|
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <setjmp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "zdtmtst.h"
const char *test_doc = "Create a bunch of small VMAs and test they survive transferring\n";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
#define NR_MAPS 4096
#define NR_MAPS_1 (NR_MAPS + 0)
#define NR_MAPS_2 (NR_MAPS + 1)
#define MAPS_SIZE_1 (140 << 10)
#define MAPS_SIZE_2 (8192)
int main(int argc, char *argv[])
{
void *map[NR_MAPS + 2] = {}, *addr;
size_t i, summary;
test_init(argc, argv);
summary = NR_MAPS * 2 * 4096 + MAPS_SIZE_1 + MAPS_SIZE_2 + (1 << 20);
addr = mmap(NULL, summary, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (addr == MAP_FAILED) {
pr_perror("Can't mmap");
return 1;
}
munmap(addr, summary);
for (i = 0; i < NR_MAPS; i++) {
map[i] = mmap(i > 0 ? map[i - 1] + 8192 : addr, 4096, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (map[i] == MAP_FAILED) {
pr_perror("Can't mmap");
return 1;
} else {
/* Dirtify it */
int *v = (void *)map[i];
*v = i;
}
}
map[NR_MAPS_1] = mmap(map[NR_MAPS_1 - 1] + 8192, MAPS_SIZE_1, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0);
if (map[NR_MAPS_1] == MAP_FAILED) {
pr_perror("Can't mmap");
return 1;
} else {
/* Dirtify it */
int *v = (void *)map[NR_MAPS_1];
*v = i;
test_msg("map-1: %p %p\n", map[NR_MAPS_1], map[NR_MAPS_1] + MAPS_SIZE_1);
}
map[NR_MAPS_2] = mmap(map[NR_MAPS_1] + MAPS_SIZE_1, MAPS_SIZE_2, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0);
if (map[NR_MAPS_2] == MAP_FAILED) {
pr_perror("Can't mmap");
return 1;
} else {
/* Dirtify it */
int *v = (void *)map[NR_MAPS_2];
*v = i;
test_msg("map-2: %p %p\n", map[NR_MAPS_2], map[NR_MAPS_2] + MAPS_SIZE_2);
}
test_daemon();
test_waitsig();
for (i = 0; i < NR_MAPS; i++) {
int *v = (void *)map[i];
if (*v != i) {
fail("Data corrupted at page %lu", (unsigned long)i);
return 1;
}
}
pass();
return 0;
}
| 2,187 | 22.782609 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/maps_file_prot.c
|
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/limits.h>
#include "zdtmtst.h"
const char *test_doc = "Test mappings of same file with different prot";
const char *test_author = "Jamie Liu <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
#define die(fmt, arg...) \
do { \
pr_perror(fmt, ##arg); \
return 1; \
} while (0)
int main(int argc, char **argv)
{
void *ro_map, *rw_map;
int fd;
test_init(argc, argv);
fd = open(filename, O_RDWR | O_CREAT, 0644);
if (fd < 0)
die("open failed");
if (ftruncate(fd, 2 * PAGE_SIZE))
die("ftruncate failed");
ro_map = mmap(NULL, 2 * PAGE_SIZE, PROT_READ, MAP_SHARED, fd, 0);
if (ro_map == MAP_FAILED)
die("mmap failed");
rw_map = ro_map + PAGE_SIZE;
if (mprotect(rw_map, PAGE_SIZE, PROT_READ | PROT_WRITE))
die("mprotect failed");
close(fd);
test_daemon();
test_waitsig();
/* Check that rw_map is still writeable */
*(volatile char *)rw_map = 1;
if (mprotect(ro_map, PAGE_SIZE, PROT_READ | PROT_WRITE)) {
fail("mprotect after restore failed");
return 1;
}
pass();
return 0;
}
| 1,245 | 20.482759 | 72 |
c
|
criu
|
criu-master/test/zdtm/static/memfd01.c
|
#include <fcntl.h>
#include <linux/memfd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/vfs.h>
#include <unistd.h>
#include "zdtmtst.h"
const char *test_doc = "memfd with different file pointer";
const char *test_author = "Nicolas Viennot <[email protected]>";
#define err(exitcode, msg, ...) \
({ \
pr_perror(msg, ##__VA_ARGS__); \
exit(exitcode); \
})
static int _memfd_create(const char *name, unsigned int flags)
{
return syscall(SYS_memfd_create, name, flags);
}
int main(int argc, char *argv[])
{
pid_t pid, pid_child;
int fd, ret, status;
task_waiter_t t;
test_init(argc, argv);
task_waiter_init(&t);
fd = _memfd_create("somename", MFD_CLOEXEC);
if (fd < 0)
err(1, "Can't call memfd_create");
pid = getpid();
pid_child = fork();
if (pid_child < 0)
err(1, "Can't fork");
if (!pid_child) {
char fdpath[100];
char buf[1];
int fl_flags1, fl_flags2, fd_flags1, fd_flags2;
snprintf(fdpath, sizeof(fdpath), "/proc/%d/fd/%d", pid, fd);
/*
* We pass O_LARGEFILE because in compat mode, our file
* descriptor does not get O_LARGEFILE automatically, but the
* restorer using non-compat open() is forced O_LARGEFILE.
* This creates a flag difference, which we don't want to deal
* with this at the moment.
*/
fd = open(fdpath, O_RDONLY | O_LARGEFILE);
if (fd < 0)
err(1, "Can't open memfd via proc");
if ((fl_flags1 = fcntl(fd, F_GETFL)) == -1)
err(1, "Can't get fl flags");
if ((fd_flags1 = fcntl(fd, F_GETFD)) == -1)
err(1, "Can't get fd flags");
task_waiter_complete(&t, 1);
// checkpoint-restore happens here
task_waiter_wait4(&t, 2);
if (read(fd, buf, 1) != 1)
err(1, "Can't read");
if ((fl_flags2 = fcntl(fd, F_GETFL)) == -1)
err(1, "Can't get fl flags");
if (fl_flags1 != fl_flags2)
err(1, "fl flags differs");
if ((fd_flags2 = fcntl(fd, F_GETFD)) == -1)
err(1, "Can't get fd flags");
if (fd_flags1 != fd_flags2)
err(1, "fd flags differs");
if (buf[0] != 'x')
err(1, "Read incorrect");
return 0;
}
task_waiter_wait4(&t, 1);
test_daemon();
test_waitsig();
if (write(fd, "x", 1) != 1)
err(1, "Can't write");
task_waiter_complete(&t, 2);
ret = wait(&status);
if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
kill(pid, SIGKILL);
fail("child had issue");
return 1;
}
pass();
return 0;
}
| 2,568 | 20.588235 | 75 |
c
|
criu
|
criu-master/test/zdtm/static/memfd03.c
|
#include <fcntl.h>
#include <linux/memfd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <sys/mman.h>
#include "zdtmtst.h"
const char *test_doc = "memfd seals";
const char *test_author = "Nicolas Viennot <[email protected]>";
#define err(exitcode, msg, ...) \
({ \
pr_perror(msg, ##__VA_ARGS__); \
exit(exitcode); \
})
static int _memfd_create(const char *name, unsigned int flags)
{
return syscall(SYS_memfd_create, name, flags);
}
#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
#endif
#ifndef F_GET_SEALS
#define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
#endif
#ifndef F_SEAL_SEAL
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
#define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
#define F_SEAL_GROW 0x0004 /* prevent file from growing */
#define F_SEAL_WRITE 0x0008 /* prevent writes */
#endif
int main(int argc, char *argv[])
{
#define LEN 5
int fd, fd2;
void *addr_write, *addr_read;
char fdpath[100];
test_init(argc, argv);
fd = _memfd_create("somename", MFD_ALLOW_SEALING | MFD_CLOEXEC);
if (fd < 0)
err(1, "Can't call memfd_create");
if (write(fd, "hello", LEN) != LEN)
err(1, "Can't write");
if (fcntl(fd, F_ADD_SEALS, F_SEAL_WRITE) < 0)
err(1, "Can't add seals");
test_daemon();
test_waitsig();
snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd);
fd2 = open(fdpath, O_RDWR);
if (fd2 < 0)
err(1, "Can't open memfd via proc");
if (fcntl(fd, F_GET_SEALS) != F_SEAL_WRITE) {
fail("Seals are different");
return 1;
}
addr_write = mmap(NULL, LEN, PROT_WRITE, MAP_SHARED, fd2, 0);
if (addr_write != MAP_FAILED) {
fail("Should not be able to get write access");
return 1;
}
addr_read = mmap(NULL, 1, PROT_READ, MAP_PRIVATE, fd2, 0);
if (addr_read == MAP_FAILED)
err(1, "Can't mmap");
if (memcmp(addr_read, "hello", LEN)) {
fail("Mapping has bad data");
return 1;
}
pass();
return 0;
}
| 2,230 | 21.31 | 75 |
c
|
criu
|
criu-master/test/zdtm/static/mmx00.c
|
#include <string.h>
#include <stdlib.h>
#include "zdtmtst.h"
const char *test_doc = "Start a calculation, leaving MMX in a certain state,\n"
"before migration, continue after";
const char *test_author = "Pavel Emelianov <[email protected]>";
#if defined(__i386__) || defined(__x86_64__)
void start(uint8_t *bytes, uint16_t *words)
{
__asm__ volatile("movq %0, %%mm0\n"
"movq %1, %%mm1\n"
"movq %2, %%mm2\n"
"movq %3, %%mm3\n"
"paddb %%mm0, %%mm1\n"
"psubw %%mm2, %%mm3\n"
:
: "m"(bytes[0]), "m"(bytes[8]), "m"(words[0]), "m"(words[4]));
}
void finish(uint8_t *bytes, uint16_t *words)
{
__asm__ volatile("movq %%mm1, %0\n"
"movq %%mm3, %1\n"
: "=m"(bytes[0]), "=m"(words[0]));
}
static inline void cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx)
{
__asm__("cpuid" : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx) : "0"(op), "c"(0));
}
int chk_proc_mmx(void)
{
unsigned int eax, ebx, ecx, edx;
cpuid(1, &eax, &ebx, &ecx, &edx);
return edx & (1 << 23);
}
#endif
int main(int argc, char **argv)
{
#if defined(__i386__) || defined(__x86_64__)
uint8_t bytes[16];
uint16_t words[8];
uint32_t rnd[8];
int i;
uint8_t resbytes1[8], resbytes2[8];
uint16_t reswords1[4], reswords2[4];
#endif
test_init(argc, argv);
#if defined(__i386__) || defined(__x86_64__)
if (!chk_proc_mmx()) {
skip("MMX not supported");
return 1;
}
for (i = 0; i < (sizeof(bytes) + sizeof(words)) / 4; i++)
rnd[i] = mrand48();
memcpy((uint8_t *)bytes, (uint8_t *)rnd, sizeof(bytes));
memcpy((uint8_t *)words, (uint8_t *)rnd + sizeof(bytes), sizeof(words));
start(bytes, words);
finish(resbytes1, reswords1);
start(bytes, words);
test_daemon();
test_waitsig();
finish(resbytes2, reswords2);
if (memcmp((uint8_t *)resbytes1, (uint8_t *)resbytes2, sizeof(resbytes1)))
fail("byte op mismatch");
else if (memcmp((uint8_t *)reswords1, (uint8_t *)reswords2, sizeof(reswords2)))
fail("word op mismatch");
else
pass();
#else
skip("Unsupported arch");
#endif
return 0;
}
| 2,079 | 22.111111 | 117 |
c
|
criu
|
criu-master/test/zdtm/static/mnt_ext_auto.c
|
#include <sched.h>
#include <sys/mount.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "zdtmtst.h"
const char *test_doc = "Check --mnt-ext-map";
const char *test_author = "Andrew Vagin <[email protected]>";
#ifdef ZDTM_EXTMAP_MANUAL
char *dirname = "mnt_ext_manual.test";
char *dirname_private_shared_bind = "mnt_ext_manual_private_shared_bind.test";
char *dirname_bind = "mnt_ext_manual_bind.test";
char *dirname_slave_shared_bind = "mnt_ext_manual_slave_shared_bind.test";
char *dirname_slave_bind = "mnt_ext_manual_slave_bind.test";
#define DDIR "mtest"
#else
char *dirname = "mnt_ext_auto.test";
char *dirname_private_shared_bind = "mnt_ext_auto_private_shared_bind.test";
char *dirname_bind = "mnt_ext_auto_bind.test";
char *dirname_slave_shared_bind = "mnt_ext_auto_slave_shared_bind.test";
char *dirname_slave_bind = "mnt_ext_auto_slave_bind.test";
#define DDIR "atest"
#endif
TEST_OPTION(dirname, string, "directory name", 1);
int main(int argc, char **argv)
{
char src[PATH_MAX], dst[PATH_MAX], *root;
char dst_bind[PATH_MAX], dst_private_shared_bind[PATH_MAX], dst_slave_shared_bind[PATH_MAX],
dst_slave_bind[PATH_MAX];
char *dname = "/tmp/zdtm_ext_auto.XXXXXX";
struct stat sta, stb, bsta, bstb, ssbsta, sbsta, ssbstb, sbstb, psbsta, psbstb;
char *zdtm_newns = getenv("ZDTM_NEWNS");
root = getenv("ZDTM_ROOT");
if (root == NULL) {
pr_perror("root");
return 1;
}
sprintf(dst, "%s/%s", get_current_dir_name(), dirname);
sprintf(dst_private_shared_bind, "%s/%s", get_current_dir_name(), dirname_private_shared_bind);
sprintf(dst_bind, "%s/%s", get_current_dir_name(), dirname_bind);
sprintf(dst_slave_shared_bind, "%s/%s", get_current_dir_name(), dirname_slave_shared_bind);
sprintf(dst_slave_bind, "%s/%s", get_current_dir_name(), dirname_slave_bind);
if (!zdtm_newns) {
pr_perror("ZDTM_NEWNS is not set");
return 1;
} else if (strcmp(zdtm_newns, "1")) {
goto test;
}
mkdir(dname, 755);
sprintf(src, "%s/%s", dname, DDIR);
if (mount("zdtm_auto_ext_mnt", dname, "tmpfs", 0, NULL)) {
pr_perror("mount");
return 1;
}
mkdir(src, 755);
if (unshare(CLONE_NEWNS)) {
pr_perror("unshare");
return 1;
}
mkdir(dst, 755);
if (mount(src, dst, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
mkdir(dst_private_shared_bind, 755);
if (mount(dst, dst_private_shared_bind, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
if (mount("none", dst_private_shared_bind, NULL, MS_PRIVATE, NULL)) {
pr_perror("bind");
return 1;
}
if (mount("none", dst_private_shared_bind, NULL, MS_SHARED, NULL)) {
pr_perror("bind");
return 1;
}
mkdir(dst_bind, 755);
if (mount(dst_private_shared_bind, dst_bind, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
mkdir(dst_slave_shared_bind, 755);
if (mount(dst_bind, dst_slave_shared_bind, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
if (mount("none", dst_slave_shared_bind, NULL, MS_SLAVE, NULL)) {
pr_perror("bind");
return 1;
}
if (mount("none", dst_slave_shared_bind, NULL, MS_SHARED, NULL)) {
pr_perror("bind");
return 1;
}
mkdir(dst_slave_bind, 755);
if (mount(dst_slave_shared_bind, dst_slave_bind, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
if (mount("none", dst_slave_bind, NULL, MS_SLAVE, NULL)) {
pr_perror("bind");
return 1;
}
test:
test_init(argc, argv);
if (stat(dirname, &stb)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_private_shared_bind, &psbstb)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_bind, &bstb)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_slave_shared_bind, &ssbstb)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_slave_bind, &sbstb)) {
pr_perror("stat");
sleep(100);
return 1;
}
test_daemon();
test_waitsig();
if (stat(dirname, &sta)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_private_shared_bind, &psbsta)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_bind, &bsta)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_slave_shared_bind, &ssbsta)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (stat(dirname_slave_bind, &sbsta)) {
pr_perror("stat");
sleep(100);
return 1;
}
if (sta.st_dev != stb.st_dev) {
fail();
return 1;
}
if (psbsta.st_dev != psbstb.st_dev) {
fail();
return 1;
}
if (bsta.st_dev != bstb.st_dev) {
fail();
return 1;
}
if (ssbsta.st_dev != ssbstb.st_dev) {
fail();
return 1;
}
if (sbsta.st_dev != sbstb.st_dev) {
fail();
return 1;
}
pass();
return 0;
}
| 4,736 | 22.567164 | 96 |
c
|
criu
|
criu-master/test/zdtm/static/mnt_ext_multiple.c
|
#include <sched.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include "zdtmtst.h"
const char *test_doc = "Check multiple non-common root external mounts with same external master";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
char *dirname = "mnt_ext_multiple.test";
char *source = "zdtm_ext_multiple";
char *ext_source = "zdtm_ext_multiple.ext";
TEST_OPTION(dirname, string, "directory name", 1);
int main(int argc, char **argv)
{
char *root, testdir[PATH_MAX];
char dst_a[PATH_MAX], dst_b[PATH_MAX];
char src[PATH_MAX], src_a[PATH_MAX], src_b[PATH_MAX];
char nsdst_a[PATH_MAX], nsdst_b[PATH_MAX];
char *tmp = "/tmp/zdtm_ext_multiple.tmp";
char *zdtm_newns = getenv("ZDTM_NEWNS");
root = getenv("ZDTM_ROOT");
if (root == NULL) {
pr_perror("root");
return 1;
}
if (!zdtm_newns) {
pr_perror("ZDTM_NEWNS is not set");
return 1;
} else if (strcmp(zdtm_newns, "1")) {
goto test;
}
/* Prepare directories in test root */
sprintf(testdir, "%s/%s", root, dirname);
mkdir(testdir, 0755);
sprintf(dst_a, "%s/%s/dst_a", root, dirname);
mkdir(dst_a, 0755);
sprintf(dst_b, "%s/%s/dst_b", root, dirname);
mkdir(dst_b, 0755);
/* Prepare directories in criu root */
mkdir(tmp, 0755);
if (mount(source, tmp, "tmpfs", 0, NULL)) {
pr_perror("mount tmpfs");
return 1;
}
if (mount(NULL, tmp, NULL, MS_PRIVATE, NULL)) {
pr_perror("make private");
return 1;
}
sprintf(src, "%s/src", tmp);
mkdir(src, 0755);
/* Create a shared mount in criu mntns */
if (mount(ext_source, src, "tmpfs", 0, NULL)) {
pr_perror("mount tmpfs");
return 1;
}
if (mount(NULL, src, NULL, MS_PRIVATE, NULL)) {
pr_perror("make private");
return 1;
}
if (mount(NULL, src, NULL, MS_SHARED, NULL)) {
pr_perror("make shared");
return 1;
}
/*
* Create temporary mntns, next mounts will not show up in criu mntns
*/
if (unshare(CLONE_NEWNS)) {
pr_perror("unshare");
return 1;
}
/*
* Populate to the tests root subdirectories of the src mount
*/
sprintf(src_a, "%s/src/a", tmp);
mkdir(src_a, 0755);
if (mount(src_a, dst_a, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
sprintf(src_b, "%s/src/b", tmp);
mkdir(src_b, 0755);
if (mount(src_b, dst_b, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
test:
test_init(argc, argv);
/* Make "external" mounts to have external master */
sprintf(nsdst_a, "/%s/dst_a", dirname);
if (mount(NULL, nsdst_a, NULL, MS_SLAVE, NULL)) {
pr_perror("make slave");
return 1;
}
sprintf(nsdst_b, "/%s/dst_b", dirname);
if (mount(NULL, nsdst_b, NULL, MS_SLAVE, NULL)) {
pr_perror("make slave");
return 1;
}
test_daemon();
test_waitsig();
pass();
return 0;
}
| 2,730 | 21.94958 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/mnt_ext_sharing.c
|
#include <sched.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "zdtmtst.h"
#include "lock.h"
const char *test_doc = "Check sharing vs external mounts vs mntns";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
char *dirname = "mnt_ext_sharing.test";
char *source = "zdtm_ext_sharing";
char *internal_source = "zdtm_ext_sharing.internal";
#define SUBDIR "subdir"
TEST_OPTION(dirname, string, "directory name", 1);
enum {
TEST_START,
TEST_STARTED,
TEST_EXIT,
TEST_EXITED,
};
struct shared {
futex_t fstate;
int ret;
};
struct shared *sh;
#define BUF_SIZE 4096
int pid_mntinfo_get_shid(char *pid, char *source)
{
char path[PATH_MAX], line[BUF_SIZE];
FILE *mountinfo;
char *hyphen, *shared;
int ret = -1;
sprintf(path, "/proc/%s/mountinfo", pid);
mountinfo = fopen(path, "r");
if (!mountinfo) {
pr_perror("fopen");
return ret;
}
while (fgets(line, sizeof(line), mountinfo)) {
hyphen = strchr(line, '-');
if (!hyphen) {
pr_perror("no hyphen in mountinfo");
break;
}
if (!strstr(hyphen + 1, source))
continue;
shared = strstr(line, "shared:");
if (!shared) {
pr_err("no shared id\n");
break;
}
ret = atoi(shared + 7);
break;
}
fclose(mountinfo);
return ret;
}
int secondary_mntns_child(void)
{
if (unshare(CLONE_NEWNS)) {
pr_perror("unshare");
sh->ret = 1;
futex_abort_and_wake(&sh->fstate);
return 1;
}
futex_set_and_wake(&sh->fstate, TEST_STARTED);
futex_wait_until(&sh->fstate, TEST_EXIT);
/* These task is just holding the reference to secondary mntns */
futex_set_and_wake(&sh->fstate, TEST_EXITED);
return 0;
}
int main(int argc, char **argv)
{
char *root, testdir[PATH_MAX], spid[BUF_SIZE];
char internal_dst[PATH_MAX], internal_src[PATH_MAX], internal_nsdst[PATH_MAX];
int internal_shid_self = -1, internal_shid_pid = -1;
char *tmp = "/tmp/zdtm_ext_sharing.tmp";
char *zdtm_newns = getenv("ZDTM_NEWNS");
int pid, status;
root = getenv("ZDTM_ROOT");
if (root == NULL) {
pr_perror("root");
return 1;
}
if (!zdtm_newns) {
pr_perror("ZDTM_NEWNS is not set");
return 1;
} else if (strcmp(zdtm_newns, "1")) {
goto test;
}
/* Prepare directories in test root */
sprintf(testdir, "%s/%s", root, dirname);
mkdir(testdir, 0755);
sprintf(internal_dst, "%s/%s/internal", root, dirname);
mkdir(internal_dst, 0755);
/* Prepare directories in criu root */
mkdir(tmp, 0755);
if (mount(source, tmp, "tmpfs", 0, NULL)) {
pr_perror("mount tmpfs");
return 1;
}
if (mount(NULL, tmp, NULL, MS_PRIVATE, NULL)) {
pr_perror("make private");
return 1;
}
sprintf(internal_src, "%s/internal", tmp);
mkdir(internal_src, 0755);
/* Create a shared mount in criu mntns */
if (mount(internal_source, internal_src, "tmpfs", 0, NULL)) {
pr_perror("mount tmpfs");
return 1;
}
if (mount(NULL, internal_src, NULL, MS_PRIVATE, NULL)) {
pr_perror("make private");
return 1;
}
if (mount(NULL, internal_src, NULL, MS_SHARED, NULL)) {
pr_perror("make shared");
return 1;
}
/*
* Create temporary mntns, next mounts will not show up in criu mntns
*/
if (unshare(CLONE_NEWNS)) {
pr_perror("unshare");
return 1;
}
/*
* Populate to the tests root only a subdirectory of the internal_src
* mount to ensure that it will be restored as an external mount.
*/
sprintf(internal_src, "%s/internal/%s", tmp, SUBDIR);
mkdir(internal_src, 0755);
if (mount(internal_src, internal_dst, NULL, MS_BIND, NULL)) {
pr_perror("bind");
return 1;
}
test:
test_init(argc, argv);
sh = mmap(NULL, sizeof(struct shared), PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (sh == MAP_FAILED) {
pr_perror("Failed to alloc shared region");
exit(1);
}
futex_set(&sh->fstate, TEST_START);
sh->ret = 0;
sprintf(internal_nsdst, "/%s/internal", dirname);
/* Make "external" mount to have internal sharing */
if (mount(NULL, internal_nsdst, NULL, MS_PRIVATE, NULL)) {
pr_perror("make shared");
return 1;
}
if (mount(NULL, internal_nsdst, NULL, MS_SHARED, NULL)) {
pr_perror("make shared");
return 1;
}
/* Create secondary mntns copying all mounts */
pid = fork();
if (pid < 0) {
pr_perror("fork");
return 1;
} else if (pid == 0) {
exit(secondary_mntns_child());
}
futex_wait_until(&sh->fstate, TEST_STARTED);
if (sh->ret != 0) {
pr_err("error in child\n");
return 1;
}
test_daemon();
test_waitsig();
/*
* Check mounts in primary and secondary
* mntnses are shared to each other.
*/
sprintf(spid, "%d", pid);
internal_shid_pid = pid_mntinfo_get_shid(spid, internal_source);
internal_shid_self = pid_mntinfo_get_shid("self", internal_source);
/* Cleanup */
futex_set_and_wake(&sh->fstate, TEST_EXIT);
futex_wait_until(&sh->fstate, TEST_EXITED);
while (wait(&status) > 0) {
if (!WIFEXITED(status) || WEXITSTATUS(status)) {
fail("Wrong exit status: %d", status);
return 1;
}
}
if (internal_shid_pid == -1 || internal_shid_self == -1 || internal_shid_pid != internal_shid_self) {
fail("Shared ids does not match (internal)");
return 1;
}
/* Print shared id so that it can be checked in cleanup hook */
test_msg("internal_shared_id = %d\n", internal_shid_pid);
pass();
return 0;
}
| 5,264 | 21.21519 | 102 |
c
|
criu
|
criu-master/test/zdtm/static/mntns_rw_ro_rw.c
|
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include "zdtmtst.h"
const char *test_doc = "Test read-only bind mounts";
const char *test_author = "Andrey Vagin <[email protected]>";
int main(int argc, char **argv)
{
test_init(argc, argv);
if (mount("/proc/sys/", "/proc/sys", NULL, MS_BIND, NULL)) {
pr_perror("Unable to bind-mount /proc/sys");
return 1;
}
if (mount("/proc/sys/net", "/proc/sys/net", NULL, MS_BIND, NULL)) {
pr_perror("Unable to bind-mount /proc/sys/net");
return 1;
}
if (mount("/proc/sys/", "/proc/sys", NULL, MS_RDONLY | MS_BIND | MS_REMOUNT, NULL)) {
pr_perror("Unable to remount /proc/sys");
return 1;
}
test_daemon();
test_waitsig();
if (access("/proc/sys/net/ipv4/ip_forward", W_OK)) {
fail("Unable to access /proc/sys/net/ipv4/ip_forward");
return 1;
}
if (access("/proc/sys/kernel/ns_last_pid", W_OK) != -1 || errno != EROFS) {
fail("Unable to access /proc/sys/kernel/ns_last_pid");
return 1;
}
pass();
return 0;
}
| 1,069 | 21.765957 | 86 |
c
|
criu
|
criu-master/test/zdtm/static/mount_complex_sharing.c
|
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/limits.h>
#include "mountinfo.h"
#include "zdtmtst.h"
const char *test_doc = "Check complex sharing options for mounts";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
char *dirname = "mount_complex_sharing";
TEST_OPTION(dirname, string, "directory name", 1);
/*
* Description for creating a single file:
* path - path to create file in (relative to mount)
* dir - true if file is a directory
* content - if file is not a directory, this string is written into the file
*/
struct file {
char *path;
bool dir;
char *content;
};
/*
* Description for creating a single mount:
* mountpoint - path to create mount on (relative to dirname)
* bind - id of bind source if any or -1
* bind_root - root offset from bind source
* fstype - needed for non-binds, always tmpfs
* source - source for mounting
* flags - array of sharing options or mount flags applied after
* mounting (ending with -1)
* mounted - identifies implicitly propagated mounts
* files - array of files we need to create on mount (ending with zeroed file)
*/
struct mountinfo {
char *mountpoint;
int bind;
char *bind_root;
char *fstype;
char *source;
int flags[3];
bool mounted;
struct file files[10];
};
/* clang-format off */
struct mountinfo mounts[] = {
{"", -1, "", "tmpfs", "tmpfs-dirname", {MS_PRIVATE, -1}, false,
{
{"shared-bind-1", true},
{"shared-bind-2", true},
{"shared-bind-3", true},
{"shared-bind-4", true},
{"private-mnt", true},
{"shared-mnt", true},
{"slave-mnt", true},
{"slave-shared-mnt", true},
{"testfile", false, "TESTFILE"},
{NULL}
}
},
{"shared-bind-1", -1, "", "tmpfs", "tmpfs-shared-bind", {MS_SHARED, -1}, false,
{
{"prop-private", true},
{"prop-shared", true},
{"prop-slave", true},
{"prop-slave-shared", true},
{"prop-mount-flags", true},
{NULL}
}
},
{"shared-bind-2", 1, "", NULL, NULL, {-1}, false},
{"shared-bind-3", 1, "", NULL, NULL, {-1}, false},
{"shared-bind-4", 1, "", NULL, NULL, {-1}, false},
{"private-mnt", -1, "", "tmpfs", "tmpfs-mnt", {MS_PRIVATE, -1}, false,
{
{"subdir", true},
{NULL}
}
},
{"shared-mnt", 5, "", NULL, NULL, {MS_SHARED, -1}, false},
{"slave-mnt", 6, "", NULL, NULL, {MS_SLAVE, -1}, false},
{"slave-shared-mnt", 7, "", NULL, NULL, {MS_SHARED, -1}, false},
{"shared-bind-1/prop-private", 5, "subdir", NULL, NULL, {-1}, false},
{"shared-bind-1/prop-shared", 6, "subdir", NULL, NULL, {-1}, false},
{"shared-bind-1/prop-slave", 7, "subdir", NULL, NULL, {-1}, false},
{"shared-bind-1/prop-slave-shared", 8, "subdir", NULL, NULL, {-1}, false},
{"shared-bind-2/prop-private", -1, NULL, NULL, NULL, {MS_PRIVATE, -1}, true},
{"shared-bind-2/prop-shared", -1, NULL, NULL, NULL, {MS_PRIVATE, -1}, true},
{"shared-bind-2/prop-slave", -1, NULL, NULL, NULL, {MS_PRIVATE, -1}, true},
{"shared-bind-2/prop-slave-shared", -1, NULL, NULL, NULL, {MS_PRIVATE, -1}, true},
{"shared-bind-3/prop-private", -1, NULL, NULL, NULL, {MS_SLAVE, -1}, true},
{"shared-bind-3/prop-shared", -1, NULL, NULL, NULL, {MS_SLAVE, -1}, true},
{"shared-bind-3/prop-slave", -1, NULL, NULL, NULL, {MS_SLAVE, -1}, true},
{"shared-bind-3/prop-slave-shared", -1, NULL, NULL, NULL, {MS_SLAVE, -1}, true},
{"shared-bind-4/prop-private", -1, NULL, NULL, NULL, {MS_PRIVATE, MS_SHARED, -1}, true},
{"shared-bind-4/prop-shared", -1, NULL, NULL, NULL, {MS_PRIVATE, MS_SHARED, -1}, true},
{"shared-bind-4/prop-slave", -1, NULL, NULL, NULL, {MS_PRIVATE, MS_SHARED, -1}, true},
{"shared-bind-4/prop-slave-shared", -1, NULL, NULL, NULL, {MS_PRIVATE, MS_SHARED, -1}, true},
{"shared-bind-1/prop-mount-flags", 5, "subdir", NULL, NULL, {MS_RDONLY|MS_REMOUNT|MS_BIND, -1}, false},
{"shared-bind-2/prop-mount-flags", -1, NULL, NULL, NULL, {MS_RDONLY|MS_REMOUNT|MS_BIND, -1}, true},
{"shared-bind-3/prop-mount-flags", -1, NULL, NULL, NULL, {-1}, true},
{"shared-bind-4/prop-mount-flags", -1, NULL, NULL, NULL, {-1}, true},
};
/* clang-format on */
static int fill_content(struct mountinfo *mi)
{
struct file *file = &mi->files[0];
char path[PATH_MAX];
while (file->path != NULL) {
snprintf(path, sizeof(path), "%s/%s/%s", dirname, mi->mountpoint, file->path);
if (file->dir) {
test_msg("Mkdir %s\n", path);
if (mkdir(path, 0700)) {
pr_perror("Failed to create dir %s", path);
return -1;
}
} else {
int fd, len = strlen(file->content);
test_msg("Create file %s with content %s\n", path, file->content);
fd = open(path, O_WRONLY | O_CREAT, 0777);
if (fd < 0) {
pr_perror("Failed to create file %s", path);
return -1;
}
if (write(fd, file->content, len) != len) {
pr_perror("Failed to write %s to file %s", file->content, path);
close(fd);
return -1;
}
close(fd);
}
file++;
}
return 0;
}
static int mount_one(struct mountinfo *mi)
{
char source[PATH_MAX], target[PATH_MAX];
int *flags = mi->flags, mflags = 0;
char *fstype = NULL;
test_msg("Mounting %s %d %s %s %d\n", mi->mountpoint, mi->bind, mi->fstype, mi->source, mi->mounted);
snprintf(target, sizeof(target), "%s/%s", dirname, mi->mountpoint);
if (mi->mounted)
goto apply_flags;
if (mi->bind != -1) {
snprintf(source, sizeof(source), "%s/%s/%s", dirname, mounts[mi->bind].mountpoint, mi->bind_root);
fstype = NULL;
mflags = MS_BIND;
} else {
snprintf(source, sizeof(source), "%s", mi->source);
fstype = mi->fstype;
}
if (mount(source, target, fstype, mflags, NULL)) {
pr_perror("Failed to mount %s %s %s", source, target, fstype);
return -1;
}
if (fill_content(mi))
return -1;
apply_flags:
while (flags[0] != -1) {
test_msg("Making mount %s 0x%x\n", target, flags[0]);
if (mount(NULL, target, NULL, flags[0], NULL)) {
pr_perror("Failed to make mount %s 0x%x", target, flags[0]);
return -1;
}
flags++;
}
return 0;
}
static int mount_loop(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(mounts); i++) {
if (mount_one(&mounts[i]))
return 1;
}
return 0;
}
int main(int argc, char **argv)
{
MNTNS_ZDTM(mntns_before);
MNTNS_ZDTM(mntns_after);
int ret = 1;
test_init(argc, argv);
if (mkdir(dirname, 0700) && errno != EEXIST) {
pr_perror("Failed to create %s", dirname);
goto err;
}
if (mount_loop())
goto err;
if (mntns_parse_mountinfo(&mntns_before))
goto err;
test_daemon();
test_waitsig();
if (mntns_parse_mountinfo(&mntns_after))
goto err;
if (mntns_compare(&mntns_before, &mntns_after))
goto err;
pass();
ret = 0;
err:
mntns_free_all(&mntns_before);
mntns_free_all(&mntns_after);
if (ret)
fail();
return ret;
}
| 6,706 | 25.828 | 104 |
c
|
criu
|
criu-master/test/zdtm/static/mountpoints.c
|
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sched.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "zdtmtst.h"
const char *test_doc = "Check that mountpoints (in mount namespace) are supported";
const char *test_author = "Pavel Emelianov <[email protected]>";
#define MPTS_ROOT "/zdtm_mpts/"
#define NS_STACK_SIZE 4096
/* All arguments should be above stack, because it grows down */
struct ns_exec_args {
char stack[NS_STACK_SIZE] __stack_aligned__;
char stack_ptr[0];
int status_pipe[2];
};
task_waiter_t t;
int ns_child(void *_arg)
{
struct stat st;
pid_t pid;
int fd, ufd;
mkdir(MPTS_ROOT "/dev/mntns2", 0600);
if (mount("none", MPTS_ROOT "/dev/mntns2", "tmpfs", 0, "") < 0) {
fail("Can't mount tmpfs");
return 1;
}
mkdir(MPTS_ROOT "/dev/mntns2/test", 0600);
fd = open(MPTS_ROOT "/dev/mntns2/test/test.file", O_WRONLY | O_CREAT, 0666);
if (fd < 0)
return 1;
ufd = open(MPTS_ROOT "/dev/mntns2/test/test.file.unlinked", O_WRONLY | O_CREAT, 0666);
if (ufd < 0)
return 1;
unlink(MPTS_ROOT "/dev/mntns2/test/test.file.unlinked");
pid = fork();
task_waiter_complete(&t, 1);
test_waitsig();
if (pid) {
int status = 1;
kill(pid, SIGTERM);
wait(&status);
if (status)
return 1;
}
if (stat(MPTS_ROOT "/dev/mntns2/test", &st)) {
pr_perror("Can't stat /dev/share-1/test.share/test.share");
return 1;
}
return 0;
}
int main(int argc, char **argv)
{
int fd, tmpfs_fd, have_bfmtm = 0;
struct ns_exec_args args;
pid_t pid = -1;
test_init(argc, argv);
task_waiter_init(&t);
rmdir(MPTS_ROOT);
if (mkdir(MPTS_ROOT, 0600) < 0) {
fail("Can't make zdtm_sys");
return 1;
}
if (mount("none", MPTS_ROOT, "sysfs", 0, "") < 0) {
fail("Can't mount sysfs");
return 1;
}
if (mount("none", MPTS_ROOT "/dev", "tmpfs", 0, "") < 0) {
fail("Can't mount tmpfs");
return 1;
}
tmpfs_fd = open(MPTS_ROOT "/dev/test", O_WRONLY | O_CREAT);
if (write(tmpfs_fd, "hello", 5) <= 0) {
pr_perror("write() failed");
return 1;
}
/* Check that over-mounted files are restored on tmpfs */
mkdir(MPTS_ROOT "/dev/overmount", 0600);
fd = open(MPTS_ROOT "/dev/overmount/test.over", O_WRONLY | O_CREAT);
if (fd == -1) {
pr_perror("Unable to open " MPTS_ROOT "/dev/overmount");
return -1;
}
close(fd);
if (mount("none", MPTS_ROOT "/dev/overmount", "tmpfs", 0, "") < 0) {
pr_perror("Can't mount " MPTS_ROOT "/dev/overmount");
return 1;
}
mkdir(MPTS_ROOT "/dev/non-root", 0600);
if (mount(MPTS_ROOT "/dev/non-root", MPTS_ROOT "/module", NULL, MS_BIND, NULL) < 0) {
pr_perror("Can't bind-mount %s -> %s", MPTS_ROOT "/dev/tdir", MPTS_ROOT "/module");
}
mkdir(MPTS_ROOT "/dev/non-root/test", 0600);
mkdir(MPTS_ROOT "/dev/share-1", 0600);
if (mount("none", MPTS_ROOT "/dev/share-1/", "tmpfs", 0, "") < 0) {
fail("Can't mount tmpfs");
return 1;
}
if (mount("none", MPTS_ROOT "/dev/share-1/", NULL, MS_SHARED, NULL) < 0) {
fail("Can't mount tmpfs");
return 1;
}
//#define CR_NEXT
#ifdef CR_NEXT
mkdir(MPTS_ROOT "/dev/share-1/alone", 0600);
if (mount("none", MPTS_ROOT "/dev/share-1/alone", "tmpfs", 0, "") < 0) {
fail("Can't mount tmpfs");
return 1;
}
#endif
mkdir(MPTS_ROOT "/dev/share-2", 0600);
if (mount(MPTS_ROOT "/dev/share-1", MPTS_ROOT "/dev/share-2", NULL, MS_BIND, NULL) < 0) {
fail("Can't bind mount a tmpfs directory");
return 1;
}
mkdir(MPTS_ROOT "/dev/share-3", 0600);
if (mount(MPTS_ROOT "/dev/share-1", MPTS_ROOT "/dev/share-3", NULL, MS_BIND, NULL) < 0) {
fail("Can't bind mount a tmpfs directory");
return 1;
}
mkdir(MPTS_ROOT "/dev/slave", 0600);
if (mount(MPTS_ROOT "/dev/share-1", MPTS_ROOT "/dev/slave", NULL, MS_BIND, NULL) < 0) {
fail("Can't bind mount a tmpfs directory");
return 1;
}
if (mount("none", MPTS_ROOT "/dev/slave", NULL, MS_SLAVE, NULL) < 0) {
fail("Can't mount tmpfs");
return 1;
}
mkdir(MPTS_ROOT "/dev/slave2", 0600);
if (mount(MPTS_ROOT "/dev/share-3", MPTS_ROOT "/dev/slave2", NULL, MS_BIND, NULL) < 0) {
fail("Can't bind mount a tmpfs directory");
return 1;
}
if (mount("none", MPTS_ROOT "/dev/slave2", NULL, MS_SLAVE, NULL) < 0) {
fail("Can't mount tmpfs");
return 1;
}
mkdir(MPTS_ROOT "/dev/share-1/test.mnt.share", 0600);
if (mount("none", MPTS_ROOT "/dev/share-1/test.mnt.share", "tmpfs", 0, "size=1G") < 0) {
fail("Can't mount tmpfs");
return 1;
}
mkdir(MPTS_ROOT "/dev/share-1/test.mnt.share/test.share", 0600);
if (umount(MPTS_ROOT "/dev/slave2/test.mnt.share")) {
pr_perror("Can't umount " MPTS_ROOT "/dev/slave2/test.mnt.share");
return 1;
}
mkdir(MPTS_ROOT "/dev/slave/test.mnt.slave", 0600);
if (mount("none", MPTS_ROOT "/dev/slave/test.mnt.slave", "tmpfs", 0, "") < 0) {
fail("Can't mount tmpfs");
return 1;
}
mkdir(MPTS_ROOT "/dev/slave/test.mnt.slave/test.slave", 0600);
fd = open(MPTS_ROOT "/dev/bmfile", O_CREAT | O_WRONLY);
if (fd < 0) {
pr_perror("Can't create " MPTS_ROOT "/dev/share-1/bmfile");
return 1;
}
close(fd);
fd = open(MPTS_ROOT "/dev/bmfile-mount", O_CREAT | O_WRONLY);
if (fd < 0) {
pr_perror("Can't create " MPTS_ROOT "/dev/share-1/bmfile");
return 1;
}
close(fd);
if (mount(MPTS_ROOT "/dev/bmfile", MPTS_ROOT "/dev/bmfile-mount", NULL, MS_BIND, NULL) < 0) {
fail("Can't mount tmpfs");
return 1;
}
if (mount("none", MPTS_ROOT "/kernel", "proc", 0, "") < 0) {
fail("Can't mount proc");
return 1;
}
if (mount("none", MPTS_ROOT "/kernel/sys/fs/binfmt_misc", "binfmt_misc", 0, "") == 0)
have_bfmtm = 1;
fd = open(MPTS_ROOT "/kernel/meminfo", O_RDONLY);
if (fd == -1)
return 1;
if (getenv("ZDTM_NOSUBNS") == NULL) {
pid = clone(ns_child, args.stack_ptr, CLONE_NEWNS | SIGCHLD, &args);
if (pid < 0) {
pr_perror("Unable to fork child");
return 1;
}
}
task_waiter_wait4(&t, 1);
test_daemon();
test_waitsig();
/* this checks both -- sys and proc presence */
if (access(MPTS_ROOT "/kernel/meminfo", F_OK)) {
fail("No proc after restore");
return 1;
}
if (have_bfmtm && access(MPTS_ROOT "/kernel/sys/fs/binfmt_misc/register", F_OK)) {
fail("No binfmt_misc after restore");
return 1;
}
if (umount(MPTS_ROOT "/dev/overmount") == -1) {
pr_perror("Can't umount " MPTS_ROOT "/dev/overmount");
return -1;
}
if (access(MPTS_ROOT "/dev/overmount/test.over", F_OK)) {
fail(MPTS_ROOT "/dev/overmount/test.over");
return -1;
}
{
struct stat st1, st2;
if (stat(MPTS_ROOT "/dev/share-1/test.mnt.share/test.share", &st1)) {
pr_perror("Can't stat /dev/share-1/test.share/test.share");
return 1;
}
if (stat(MPTS_ROOT "/dev/share-2/test.mnt.share/test.share", &st2)) {
pr_perror("Can't stat /dev/share-2/test.mnt.share/test.share");
return 1;
}
if (st1.st_ino != st2.st_ino) {
fail("/dev/share-1 and /dev/share-1 is not shared");
return 1;
}
if (stat(MPTS_ROOT "/dev/slave/test.mnt.share/test.share", &st2)) {
pr_perror("Can't stat /dev/slave/test.mnt.share/test.share");
return 1;
}
if (st1.st_ino != st2.st_ino) {
fail("/dev/slave is not slave of /dev/share-1");
return 1;
}
if (stat(MPTS_ROOT "/dev/share-1/test.mnt.slave/test.slave", &st1) != -1 || errno != ENOENT) {
pr_perror("/dev/share-1/test.mnt.slave/test.slave exists");
return 1;
}
if (stat(MPTS_ROOT "/dev/slave/test.mnt.slave/test.slave", &st2)) {
pr_perror("Can't stat /dev/slave/test.mnt.slave/test.slave");
return 1;
}
if (stat(MPTS_ROOT "/dev/non-root/test", &st1)) {
pr_perror("Can't stat /dev/non-root/test");
return 1;
}
}
if (pid > 0) {
int status = 1;
kill(pid, SIGTERM);
wait(&status);
if (status)
return 1;
}
pass();
return 0;
}
| 7,711 | 24.368421 | 96 |
c
|
criu
|
criu-master/test/zdtm/static/msgque.c
|
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <signal.h>
#include <errno.h>
#include "zdtmtst.h"
const char *test_doc = "Tests sysv5 msg queues supporting by checkpointing";
const char *test_author = "Stanislav Kinsbursky <[email protected]>";
struct msg1 {
long mtype;
char mtext[30];
};
#define TEST_STRING "Test sysv5 msg"
#define MSG_TYPE 1
#define ANOTHER_TEST_STRING "Yet another test sysv5 msg"
#define ANOTHER_MSG_TYPE 26538
int main(int argc, char **argv)
{
key_t key;
int msg, pid;
struct msg1 msgbuf;
int chret;
test_init(argc, argv);
key = ftok(argv[0], 822155650);
if (key == -1) {
pr_perror("Can't make key");
exit(1);
}
pid = test_fork();
if (pid < 0) {
pr_perror("Can't fork");
exit(1);
}
msg = msgget(key, IPC_CREAT | IPC_EXCL | 0666);
if (msg == -1) {
msg = msgget(key, 0666);
if (msg == -1) {
pr_perror("Can't get queue");
goto err_kill;
}
}
if (pid == 0) {
test_waitsig();
if (msgrcv(msg, &msgbuf, sizeof(TEST_STRING), MSG_TYPE, IPC_NOWAIT) == -1) {
fail("Child: msgrcv failed");
return -errno;
}
if (strncmp(TEST_STRING, msgbuf.mtext, sizeof(TEST_STRING))) {
fail("Child: the source and received strings aren't equal");
return -errno;
}
test_msg("Child: received %s\n", msgbuf.mtext);
msgbuf.mtype = ANOTHER_MSG_TYPE;
memcpy(msgbuf.mtext, ANOTHER_TEST_STRING, sizeof(ANOTHER_TEST_STRING));
if (msgsnd(msg, &msgbuf, sizeof(ANOTHER_TEST_STRING), IPC_NOWAIT) != 0) {
fail("Child: msgsnd failed");
return -errno;
};
pass();
return 0;
} else {
msgbuf.mtype = MSG_TYPE;
memcpy(msgbuf.mtext, TEST_STRING, sizeof(TEST_STRING));
if (msgsnd(msg, &msgbuf, sizeof(TEST_STRING), IPC_NOWAIT) != 0) {
fail("Parent: msgsnd failed");
goto err_kill;
};
msgbuf.mtype = ANOTHER_MSG_TYPE;
memcpy(msgbuf.mtext, ANOTHER_TEST_STRING, sizeof(ANOTHER_TEST_STRING));
if (msgsnd(msg, &msgbuf, sizeof(ANOTHER_TEST_STRING), IPC_NOWAIT) != 0) {
fail("child: msgsnd (2) failed");
return -errno;
};
test_daemon();
test_waitsig();
kill(pid, SIGTERM);
wait(&chret);
chret = WEXITSTATUS(chret);
if (chret) {
fail("Parent: child exited with non-zero code %d (%s)", chret, strerror(chret));
goto out;
}
if (msgrcv(msg, &msgbuf, sizeof(ANOTHER_TEST_STRING), ANOTHER_MSG_TYPE, IPC_NOWAIT) == -1) {
fail("Parent: msgrcv failed");
goto err;
}
if (strncmp(ANOTHER_TEST_STRING, msgbuf.mtext, sizeof(ANOTHER_TEST_STRING))) {
fail("Parent: the source and received strings aren't equal");
goto err;
}
test_msg("Parent: received %s\n", msgbuf.mtext);
pass();
}
out:
if (msgctl(msg, IPC_RMID, 0)) {
fail("Failed to destroy message queue");
return -errno;
}
return chret;
err_kill:
kill(pid, SIGKILL);
wait(NULL);
err:
chret = -errno;
goto out;
}
| 2,985 | 20.79562 | 94 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.