Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_granularity/mocks_dax_windows.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* mocks_dax_windows.c -- mocked function required to control
* FILE_DAX_VOLUME value reported by the OS APIs
*/
#include "unittest.h"
FUNC_MOCK_DLLIMPORT(GetVolumeInformationByHandleW, BOOL,
HANDLE hFile,
LPWSTR lpVolumeNameBuffer,
DWORD nVolumeNameSize,
LPDWORD lpVolumeSerialNumber,
LPDWORD lpMaximumComponentLength,
LPDWORD lpFileSystemFlags,
LPWSTR lpFileSystemNameBuffer,
DWORD nFileSystemNameSize)
FUNC_MOCK_RUN_DEFAULT {
size_t is_pmem = atoi(os_getenv("IS_PMEM"));
if (is_pmem)
*lpFileSystemFlags = FILE_DAX_VOLUME;
else
*lpFileSystemFlags = 0;
return TRUE;
}
FUNC_MOCK_END
| 688 | 22.758621 | 61 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_granularity/pmem2_granularity.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* pmem2_granularity.h -- header file for windows mocks
* for pmem2_granularity
*/
#ifndef PMEM2_GRANULARITY_H
#define PMEM2_GRANULARITY_H 1
extern size_t Is_nfit;
extern size_t Pc_type;
extern size_t Pc_capabilities;
#endif
| 314 | 18.6875 | 55 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_granularity/mocks_dax_windows.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* mocks_dax_windows.h -- redefinitions of GetVolumeInformationByHandleW
*
* This file is Windows-specific.
*
* This file should be included (i.e. using Forced Include) by libpmem2
* files, when compiled for the purpose of pmem2_granularity test.
* It would replace default implementation with mocked functions defined
* in mocks_windows.c
*
* This WRAP_REAL define could also be passed as a preprocessor definition.
*/
#ifndef MOCKS_WINDOWS_H
#define MOCKS_WINDOWS_H 1
#include <windows.h>
#ifndef WRAP_REAL
#define GetVolumeInformationByHandleW __wrap_GetVolumeInformationByHandleW
BOOL
__wrap_GetVolumeInformationByHandleW(HANDLE hFile, LPWSTR lpVolumeNameBuffer,
DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber,
LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags,
LPWSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize);
#endif
#endif
| 956 | 28.90625 | 77 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmempool_sync_remote/config.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2018, Intel Corporation
#
#
# pmempool_sync_remote/config.sh -- test configuration
#
CONF_GLOBAL_BUILD_TYPE="debug nondebug"
CONF_GLOBAL_RPMEM_PROVIDER=all
CONF_GLOBAL_RPMEM_PMETHOD=all
| 265 | 19.461538 | 54 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmempool_sync_remote/common.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2020, Intel Corporation
#
#
# pmempool_sync_remote/common.sh -- pmempool sync with remote replication
#
set -e
require_nodes 2
require_node_libfabric 0 $RPMEM_PROVIDER
require_node_libfabric 1 $RPMEM_PROVIDER
setup
init_rpmem_on_node 1 0
require_node_log_files 1 pmemobj$UNITTEST_NUM.log
require_node_log_files 1 pmempool$UNITTEST_NUM.log
PMEMOBJCLI_SCRIPT="pmemobjcli.script"
copy_files_to_node 1 ${NODE_TEST_DIR[1]} $PMEMOBJCLI_SCRIPT
POOLSET_LOCAL="local_pool.set"
#
# configure_poolsets -- configure pool set files for test
# usage: configure_poolsets <local replicas> <remote replicas>
#
function configure_poolsets() {
local n_local=$1
local n_remote=$2
local poolset_args="8M:${NODE_DIR[1]}/pool.part.1:x
8M:${NODE_DIR[1]}/pool.part.2:x"
for i in $(seq 0 $((n_local - 1))); do
poolset_args="$poolset_args R 8M:${NODE_DIR[1]}/pool.$i.part.1:x
8M:${NODE_DIR[1]}/pool.$i.part.2:x"
done
for i in $(seq 0 $((n_remote - 1))); do
POOLSET_REMOTE[$i]="remote_pool.$i.set"
create_poolset $DIR/${POOLSET_REMOTE[$i]}\
8M:${NODE_DIR[0]}remote.$i.part.1:x\
8M:${NODE_DIR[0]}remote.$i.part.2:x
copy_files_to_node 0 ${NODE_DIR[0]} $DIR/${POOLSET_REMOTE[$i]}
poolset_args="$poolset_args m ${NODE_ADDR[0]}:${POOLSET_REMOTE[$i]}"
done
create_poolset $DIR/$POOLSET_LOCAL $poolset_args
copy_files_to_node 1 ${NODE_DIR[1]} $DIR/$POOLSET_LOCAL
expect_normal_exit run_on_node 1 ../pmempool rm -sf ${NODE_DIR[1]}$POOLSET_LOCAL
expect_normal_exit run_on_node 1 ../pmempool create obj ${NODE_DIR[1]}$POOLSET_LOCAL
expect_normal_exit run_on_node 1 ../pmemobjcli -s $PMEMOBJCLI_SCRIPT ${NODE_DIR[1]}$POOLSET_LOCAL > /dev/null
}
DUMP_INFO_LOG="../pmempool info -lHZCOoAa"
DUMP_INFO_LOG_REMOTE="$DUMP_INFO_LOG -f obj"
DUMP_INFO_SED="sed -e '/^Checksum/d' -e '/^Creation/d'"
DUMP_INFO_SED_REMOTE="$DUMP_INFO_SED -e '/^Previous part UUID/d' -e '/^Next part UUID/d'"
function dump_info_log() {
local node=$1
local rep=$2
local poolset=$3
local name=$4
local ignore=$5
local sed_cmd="$DUMP_INFO_SED"
if [ -n "$ignore" ]; then
sed_cmd="$sed_cmd -e '/^$ignore/d'"
fi
expect_normal_exit run_on_node $node "\"$DUMP_INFO_LOG -p $rep $poolset | $sed_cmd > $name\""
}
function dump_info_log_remote() {
local node=$1
local poolset=$2
local name=$3
local ignore=$4
local sed_cmd="$DUMP_INFO_SED_REMOTE"
if [ -n "$ignore" ]; then
sed_cmd="$sed_cmd -e '/^$ignore/d'"
fi
expect_normal_exit run_on_node $node "\"$DUMP_INFO_LOG_REMOTE $poolset | $sed_cmd > $name\""
}
function diff_log() {
local node=$1
local f1=$2
local f2=$3
expect_normal_exit run_on_node $node "\"[ -s $f1 ] && [ -s $f2 ] && diff $f1 $f2\""
}
exec_pmemobjcli_script() {
local node=$1
local script=$2
local poolset=$3
local out=$4
expect_normal_exit run_on_node $node "\"../pmemobjcli -s $script $poolset > $out \""
}
| 2,911 | 25 | 110 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmempool_sync/setup.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2020, IBM Corporation
#
PARTSIZE=$(($(getconf PAGESIZE)/1024*2))
POOLSIZE_REP=$(($PARTSIZE*3))
| 168 | 20.125 | 40 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmem_fip/rpmem_fip_test.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmem_fip_test.c -- tests for rpmem_fip and rpmemd_fip modules
*/
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "unittest.h"
#include "pmemcommon.h"
#include "librpmem.h"
#include "rpmem.h"
#include "rpmem_proto.h"
#include "rpmem_common.h"
#include "rpmem_util.h"
#include "rpmem_fip_common.h"
#include "rpmem_fip_oob.h"
#include "rpmemd_fip.h"
#include "rpmemd_log.h"
#include "rpmemd_util.h"
#include "rpmem_fip.h"
#include "os.h"
#define SIZE_PER_LANE 64
#define COUNT_PER_LANE 32
#define NLANES 1024
#define SOCK_NLANES 32
#define NTHREADS 32
#define TOTAL_PER_LANE (SIZE_PER_LANE * COUNT_PER_LANE)
#define POOL_SIZE (NLANES * TOTAL_PER_LANE)
static uint8_t lpool[POOL_SIZE];
static uint8_t rpool[POOL_SIZE];
TEST_CASE_DECLARE(client_init);
TEST_CASE_DECLARE(server_init);
TEST_CASE_DECLARE(client_connect);
TEST_CASE_DECLARE(server_connect);
TEST_CASE_DECLARE(server_process);
TEST_CASE_DECLARE(client_flush);
TEST_CASE_DECLARE(client_flush_mt);
TEST_CASE_DECLARE(client_persist);
TEST_CASE_DECLARE(client_persist_mt);
TEST_CASE_DECLARE(client_read);
TEST_CASE_DECLARE(client_wq_size);
struct fip_client {
enum rpmem_provider provider;
unsigned max_wq_size;
unsigned nlanes;
};
#define FIP_CLIENT_DEFAULT {RPMEM_PROV_UNKNOWN, 0, NLANES}
/*
* get_persist_method -- parse persist method
*/
static enum rpmem_persist_method
get_persist_method(const char *pm)
{
if (strcmp(pm, "GPSPM") == 0)
return RPMEM_PM_GPSPM;
else if (strcmp(pm, "APM") == 0)
return RPMEM_PM_APM;
else
UT_FATAL("unknown method");
}
/*
* get_provider -- get provider for given target
*/
static void
get_provider(const char *target, const char *prov_name,
struct fip_client *client)
{
struct rpmem_fip_probe probe;
int ret;
int any = 0;
if (strcmp(prov_name, "any") == 0)
any = 1;
ret = rpmem_fip_probe_get(target, &probe);
UT_ASSERTeq(ret, 0);
UT_ASSERT(rpmem_fip_probe_any(probe));
if (any) {
/* return verbs in first place */
if (rpmem_fip_probe(probe,
RPMEM_PROV_LIBFABRIC_VERBS))
client->provider = RPMEM_PROV_LIBFABRIC_VERBS;
else if (rpmem_fip_probe(probe,
RPMEM_PROV_LIBFABRIC_SOCKETS))
client->provider = RPMEM_PROV_LIBFABRIC_SOCKETS;
else
UT_ASSERT(0);
} else {
client->provider = rpmem_provider_from_str(prov_name);
UT_ASSERTne(client->provider, RPMEM_PROV_UNKNOWN);
UT_ASSERT(rpmem_fip_probe(probe, client->provider));
}
/*
* Decrease number of lanes for socket provider because
* the test may be too long.
*/
if (client->provider == RPMEM_PROV_LIBFABRIC_SOCKETS)
client->nlanes = min(client->nlanes, SOCK_NLANES);
client->max_wq_size = probe.max_wq_size[client->provider];
}
/*
* set_pool_data -- set pools data to well known values
*/
static void
set_pool_data(uint8_t *pool, int inverse)
{
for (unsigned l = 0; l < NLANES; l++) {
for (unsigned i = 0; i < COUNT_PER_LANE; i++) {
size_t offset = l * TOTAL_PER_LANE + i * SIZE_PER_LANE;
unsigned val = i + l;
if (inverse)
val = ~val;
memset(&pool[offset], (int)val, SIZE_PER_LANE);
}
}
}
/*
* flush_arg -- arguments for client persist and flush / drain threads
*/
struct flush_arg {
struct rpmem_fip *fip;
unsigned lane;
};
typedef void *(*flush_fn)(void *arg);
/*
* client_flush_thread -- thread callback for flush / drain operation
*/
static void *
client_flush_thread(void *arg)
{
struct flush_arg *args = arg;
int ret;
/* persist with len == 0 should always succeed */
ret = rpmem_fip_flush(args->fip, args->lane * TOTAL_PER_LANE,
0, args->lane, RPMEM_FLUSH_WRITE);
UT_ASSERTeq(ret, 0);
for (unsigned i = 0; i < COUNT_PER_LANE; i++) {
size_t offset = args->lane * TOTAL_PER_LANE + i * SIZE_PER_LANE;
unsigned val = args->lane + i;
memset(&lpool[offset], (int)val, SIZE_PER_LANE);
ret = rpmem_fip_flush(args->fip, offset,
SIZE_PER_LANE, args->lane, RPMEM_FLUSH_WRITE);
UT_ASSERTeq(ret, 0);
}
ret = rpmem_fip_drain(args->fip, args->lane);
UT_ASSERTeq(ret, 0);
return NULL;
}
/*
* client_persist_thread -- thread callback for persist operation
*/
static void *
client_persist_thread(void *arg)
{
struct flush_arg *args = arg;
int ret;
/* persist with len == 0 should always succeed */
ret = rpmem_fip_persist(args->fip, args->lane * TOTAL_PER_LANE,
0, args->lane, RPMEM_FLUSH_WRITE);
UT_ASSERTeq(ret, 0);
for (unsigned i = 0; i < COUNT_PER_LANE; i++) {
size_t offset = args->lane * TOTAL_PER_LANE + i * SIZE_PER_LANE;
unsigned val = args->lane + i;
memset(&lpool[offset], (int)val, SIZE_PER_LANE);
ret = rpmem_fip_persist(args->fip, offset,
SIZE_PER_LANE, args->lane, RPMEM_FLUSH_WRITE);
UT_ASSERTeq(ret, 0);
}
return NULL;
}
/*
* client_init -- test case for client initialization
*/
int
client_init(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
set_rpmem_cmd("server_init %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
/*
* Tune the maximum number of lanes according to environment.
*/
rpmem_util_get_env_max_nlanes(&Rpmem_max_nlanes);
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
client_close_begin(client);
client_close_end(client);
rpmem_fip_fini(fip);
rpmem_target_free(info);
return 3;
}
/*
* server_init -- test case for server initialization
*/
int
server_init(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: %s <persist method>", tc->name);
enum rpmem_persist_method persist_method = get_persist_method(argv[0]);
unsigned nlanes;
enum rpmem_provider provider;
char *addr = NULL;
int ret;
server_exchange_begin(&nlanes, &provider, &addr);
UT_ASSERTne(addr, NULL);
struct rpmemd_fip_attr attr = {
.addr = rpool,
.size = POOL_SIZE,
.nlanes = nlanes,
.provider = provider,
.persist_method = persist_method,
.nthreads = NTHREADS,
};
ret = rpmemd_apply_pm_policy(&attr.persist_method, &attr.persist,
&attr.memcpy_persist,
1 /* is pmem */);
UT_ASSERTeq(ret, 0);
struct rpmem_resp_attr resp;
struct rpmemd_fip *fip;
enum rpmem_err err;
fip = rpmemd_fip_init(addr, NULL, &attr, &resp, &err);
UT_ASSERTne(fip, NULL);
server_exchange_end(resp);
server_close_begin();
server_close_end();
rpmemd_fip_fini(fip);
FREE(addr);
return 1;
}
/*
* client_connect -- test case for establishing connection - client side
*/
int
client_connect(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
set_rpmem_cmd("server_connect %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
int ret;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
ret = rpmem_fip_connect(fip);
UT_ASSERTeq(ret, 0);
client_close_begin(client);
ret = rpmem_fip_close(fip);
UT_ASSERTeq(ret, 0);
client_close_end(client);
rpmem_fip_fini(fip);
rpmem_target_free(info);
return 3;
}
/*
* server_connect -- test case for establishing connection - server side
*/
int
server_connect(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: %s <persist method>", tc->name);
enum rpmem_persist_method persist_method = get_persist_method(argv[0]);
unsigned nlanes;
enum rpmem_provider provider;
char *addr = NULL;
server_exchange_begin(&nlanes, &provider, &addr);
UT_ASSERTne(addr, NULL);
struct rpmemd_fip_attr attr = {
.addr = rpool,
.size = POOL_SIZE,
.nlanes = nlanes,
.provider = provider,
.persist_method = persist_method,
.nthreads = NTHREADS,
};
int ret;
struct rpmem_resp_attr resp;
struct rpmemd_fip *fip;
enum rpmem_err err;
ret = rpmemd_apply_pm_policy(&attr.persist_method, &attr.persist,
&attr.memcpy_persist,
1 /* is pmem */);
UT_ASSERTeq(ret, 0);
fip = rpmemd_fip_init(addr, NULL, &attr, &resp, &err);
UT_ASSERTne(fip, NULL);
server_exchange_end(resp);
ret = rpmemd_fip_accept(fip, -1);
UT_ASSERTeq(ret, 0);
server_close_begin();
server_close_end();
ret = rpmemd_fip_wait_close(fip, -1);
UT_ASSERTeq(ret, 0);
ret = rpmemd_fip_close(fip);
UT_ASSERTeq(ret, 0);
rpmemd_fip_fini(fip);
FREE(addr);
return 1;
}
/*
* server_process -- test case for processing data on server side
*/
int
server_process(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: %s <persist method>", tc->name);
enum rpmem_persist_method persist_method = get_persist_method(argv[0]);
set_pool_data(rpool, 1);
unsigned nlanes;
enum rpmem_provider provider;
char *addr = NULL;
server_exchange_begin(&nlanes, &provider, &addr);
UT_ASSERTne(addr, NULL);
struct rpmemd_fip_attr attr = {
.addr = rpool,
.size = POOL_SIZE,
.nlanes = nlanes,
.provider = provider,
.persist_method = persist_method,
.nthreads = NTHREADS,
};
int ret;
struct rpmem_resp_attr resp;
struct rpmemd_fip *fip;
enum rpmem_err err;
ret = rpmemd_apply_pm_policy(&attr.persist_method, &attr.persist,
&attr.memcpy_persist,
1 /* is pmem */);
UT_ASSERTeq(ret, 0);
fip = rpmemd_fip_init(addr, NULL, &attr, &resp, &err);
UT_ASSERTne(fip, NULL);
server_exchange_end(resp);
ret = rpmemd_fip_accept(fip, -1);
UT_ASSERTeq(ret, 0);
ret = rpmemd_fip_process_start(fip);
server_close_begin();
ret = rpmemd_fip_process_stop(fip);
UT_ASSERTeq(ret, 0);
server_close_end();
ret = rpmemd_fip_wait_close(fip, -1);
UT_ASSERTeq(ret, 0);
ret = rpmemd_fip_close(fip);
UT_ASSERTeq(ret, 0);
rpmemd_fip_fini(fip);
FREE(addr);
return 1;
}
/*
* flush_common -- common part for single-threaded persist and flush / drain
* test cases
*/
static void
flush_common(char *target, char *prov_name, char *persist_method,
flush_fn flush_func)
{
set_rpmem_cmd("server_process %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
int ret;
set_pool_data(lpool, 1);
set_pool_data(rpool, 1);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
ret = rpmem_fip_connect(fip);
UT_ASSERTeq(ret, 0);
struct flush_arg arg = {
.fip = fip,
.lane = 0,
};
flush_func(&arg);
ret = rpmem_fip_read(fip, rpool, POOL_SIZE, 0, 0);
UT_ASSERTeq(ret, 0);
client_close_begin(client);
ret = rpmem_fip_close(fip);
UT_ASSERTeq(ret, 0);
client_close_end(client);
rpmem_fip_fini(fip);
ret = memcmp(rpool, lpool, POOL_SIZE);
UT_ASSERTeq(ret, 0);
rpmem_target_free(info);
}
/*
* flush_common_mt -- common part for multi-threaded persist and flush / drain
* test cases
*/
static int
flush_common_mt(char *target, char *prov_name, char *persist_method,
flush_fn flush_thread_func)
{
set_rpmem_cmd("server_process %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
int ret;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
set_pool_data(lpool, 1);
set_pool_data(rpool, 1);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
ret = rpmem_fip_connect(fip);
UT_ASSERTeq(ret, 0);
os_thread_t *flush_thread = MALLOC(resp.nlanes * sizeof(os_thread_t));
struct flush_arg *args = MALLOC(resp.nlanes * sizeof(struct flush_arg));
for (unsigned i = 0; i < fip_client.nlanes; i++) {
args[i].fip = fip;
args[i].lane = i;
THREAD_CREATE(&flush_thread[i], NULL,
flush_thread_func, &args[i]);
}
for (unsigned i = 0; i < fip_client.nlanes; i++)
THREAD_JOIN(&flush_thread[i], NULL);
ret = rpmem_fip_read(fip, rpool, POOL_SIZE, 0, 0);
UT_ASSERTeq(ret, 0);
client_close_begin(client);
ret = rpmem_fip_close(fip);
UT_ASSERTeq(ret, 0);
client_close_end(client);
rpmem_fip_fini(fip);
FREE(flush_thread);
FREE(args);
ret = memcmp(rpool, lpool, POOL_SIZE);
UT_ASSERTeq(ret, 0);
rpmem_target_free(info);
return 3;
}
/*
* client_flush -- test case for single-threaded flush / drain operation
*/
int
client_flush(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
flush_common(target, prov_name, persist_method, client_flush_thread);
return 3;
}
/*
* client_flush_mt -- test case for multi-threaded flush / drain operation
*/
int
client_flush_mt(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
flush_common_mt(target, prov_name, persist_method, client_flush_thread);
return 3;
}
/*
* client_persist -- test case for single-threaded persist operation
*/
int
client_persist(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
flush_common(target, prov_name, persist_method, client_persist_thread);
return 3;
}
/*
* client_persist_mt -- test case for multi-threaded persist operation
*/
int
client_persist_mt(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
flush_common_mt(target, prov_name, persist_method,
client_persist_thread);
return 3;
}
/*
* client_read -- test case for read operation
*/
int
client_read(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>",
tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
set_rpmem_cmd("server_process %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
int ret;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
set_pool_data(lpool, 0);
set_pool_data(rpool, 1);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
ret = rpmem_fip_connect(fip);
UT_ASSERTeq(ret, 0);
/* read with len == 0 should always succeed */
ret = rpmem_fip_read(fip, lpool, 0, 0, 0);
UT_ASSERTeq(ret, 0);
ret = rpmem_fip_read(fip, lpool, POOL_SIZE, 0, 0);
UT_ASSERTeq(ret, 0);
client_close_begin(client);
ret = rpmem_fip_close(fip);
UT_ASSERTeq(ret, 0);
client_close_end(client);
rpmem_fip_fini(fip);
ret = memcmp(rpool, lpool, POOL_SIZE);
UT_ASSERTeq(ret, 0);
rpmem_target_free(info);
return 3;
}
#define LT_MAX_WQ_SIZE "LT_MAX_WQ_SIZE" /* < max_wq_size */
#define EQ_MAX_WQ_SIZE "EQ_MAX_WQ_SIZE" /* == max_wq_size */
#define GT_MAX_WQ_SIZE "GT_MAX_WQ_SIZE" /* > max_wq_size */
/*
* client_wq_size -- test case for WQ size adjustment
*/
int
client_wq_size(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 3)
UT_FATAL("usage: %s <target> <provider> <persist method>"
"<wq_size>", tc->name);
char *target = argv[0];
char *prov_name = argv[1];
char *persist_method = argv[2];
char *wq_size_env_str = argv[3];
set_rpmem_cmd("server_process %s", persist_method);
char fip_service[NI_MAXSERV];
struct rpmem_target_info *info;
int ret;
info = rpmem_target_parse(target);
UT_ASSERTne(info, NULL);
struct fip_client fip_client = FIP_CLIENT_DEFAULT;
get_provider(info->node, prov_name, &fip_client);
rpmem_util_get_env_max_nlanes(&fip_client.nlanes);
client_t *client;
struct rpmem_resp_attr resp;
client = client_exchange(info, fip_client.nlanes, fip_client.provider,
&resp);
struct rpmem_fip_attr attr = {
.provider = fip_client.provider,
.max_wq_size = fip_client.max_wq_size,
.persist_method = resp.persist_method,
.laddr = lpool,
.size = POOL_SIZE,
.nlanes = resp.nlanes,
.raddr = (void *)resp.raddr,
.rkey = resp.rkey,
};
ssize_t sret = SNPRINTF(fip_service, NI_MAXSERV, "%u", resp.port);
UT_ASSERT(sret > 0);
/* check RPMEM_WORK_QUEUE_SIZE env processing */
unsigned wq_size_default = Rpmem_wq_size;
if (strcmp(wq_size_env_str, LT_MAX_WQ_SIZE) == 0) {
Rpmem_wq_size = fip_client.max_wq_size - 1;
} else if (strcmp(wq_size_env_str, EQ_MAX_WQ_SIZE) == 0) {
Rpmem_wq_size = fip_client.max_wq_size;
} else if (strcmp(wq_size_env_str, GT_MAX_WQ_SIZE) == 0) {
Rpmem_wq_size = fip_client.max_wq_size + 1;
} else {
long wq_size_env = STRTOL(wq_size_env_str, NULL, 10);
rpmem_util_get_env_wq_size(&Rpmem_wq_size);
if (wq_size_env > 0) {
if (wq_size_env < UINT_MAX)
UT_ASSERT(Rpmem_wq_size == wq_size_env);
else
UT_ASSERT(Rpmem_wq_size == UINT_MAX);
} else
UT_ASSERT(Rpmem_wq_size == wq_size_default);
}
struct rpmem_fip *fip;
fip = rpmem_fip_init(info->node, fip_service, &attr,
&fip_client.nlanes);
UT_ASSERTne(fip, NULL);
size_t req_wq_size = rpmem_fip_wq_size(
resp.persist_method, RPMEM_FIP_NODE_CLIENT);
size_t eff_wq_size = rpmem_fip_get_wq_size(fip);
/* max supported meets minimal requirements */
UT_ASSERT(fip_client.max_wq_size >= req_wq_size);
/* calculated meets minimal requirements */
UT_ASSERT(eff_wq_size >= req_wq_size);
/* calculated is supported */
UT_ASSERT(eff_wq_size <= fip_client.max_wq_size);
/* if forced by env meets minimal requirements */
if (Rpmem_wq_size > req_wq_size) {
/* and it is supported */
if (Rpmem_wq_size <= fip_client.max_wq_size) {
/* calculated is >= to forced */
UT_ASSERT(eff_wq_size >= Rpmem_wq_size);
} else {
/* calculated is clipped to max supported */
UT_ASSERT(eff_wq_size == fip_client.max_wq_size);
}
}
ret = rpmem_fip_connect(fip);
UT_ASSERTeq(ret, 0);
client_close_begin(client);
ret = rpmem_fip_close(fip);
UT_ASSERTeq(ret, 0);
client_close_end(client);
rpmem_fip_fini(fip);
rpmem_target_free(info);
return 4;
}
/*
* test_cases -- available test cases
*/
static struct test_case test_cases[] = {
TEST_CASE(client_init),
TEST_CASE(server_init),
TEST_CASE(client_connect),
TEST_CASE(server_connect),
TEST_CASE(client_flush),
TEST_CASE(client_flush_mt),
TEST_CASE(client_persist),
TEST_CASE(client_persist_mt),
TEST_CASE(server_process),
TEST_CASE(client_read),
TEST_CASE(client_wq_size)
};
#define NTESTS (sizeof(test_cases) / sizeof(test_cases[0]))
int
main(int argc, char *argv[])
{
/* workaround for left-opened files by libfabric */
rpmem_fip_probe_get("localhost", NULL);
START(argc, argv, "rpmem_obc");
common_init("rpmem_fip",
"RPMEM_LOG_LEVEL",
"RPMEM_LOG_FILE", 0, 0);
rpmem_util_cmds_init();
rpmemd_log_init("rpmemd", os_getenv("RPMEMD_LOG_FILE"), 0);
rpmemd_log_level = rpmemd_log_level_from_str(
os_getenv("RPMEMD_LOG_LEVEL"));
TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS);
common_fini();
rpmemd_log_close();
rpmem_util_cmds_fini();
DONE(NULL);
}
| 22,586 | 21.97762 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmem_fip/config.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2017, Intel Corporation
#
#
# src/test/rpmem_fip/config.sh -- test configuration
#
CONF_GLOBAL_FS_TYPE=none
CONF_GLOBAL_BUILD_TYPE="debug nondebug"
CONF_GLOBAL_RPMEM_PROVIDER=all
CONF_GLOBAL_RPMEM_PMETHOD=all
| 288 | 19.642857 | 52 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmem_fip/rpmem_fip_oob.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* rpmem_fip_sock.h -- simple oob connection implementation for exchanging
* required RDMA related data
*/
#include <stdint.h>
#include <netinet/in.h>
typedef struct rpmem_ssh client_t;
client_t *client_exchange(struct rpmem_target_info *info,
unsigned nlanes,
enum rpmem_provider provider,
struct rpmem_resp_attr *resp);
void client_close_begin(client_t *c);
void client_close_end(client_t *c);
void server_exchange_begin(unsigned *lanes, enum rpmem_provider *provider,
char **addr);
void server_exchange_end(struct rpmem_resp_attr resp);
void server_close_begin(void);
void server_close_end(void);
void set_rpmem_cmd(const char *fmt, ...);
| 743 | 24.655172 | 74 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmem_fip/setup.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2019, Intel Corporation
#
# src/test/rpmem_fip/setup.sh -- common setup for rpmem_fip tests
#
set -e
require_nodes 2
require_node_libfabric 0 $RPMEM_PROVIDER
require_node_libfabric 1 $RPMEM_PROVIDER
require_node_log_files 0 $RPMEM_LOG_FILE $RPMEMD_LOG_FILE
require_node_log_files 1 $RPMEM_LOG_FILE $RPMEMD_LOG_FILE
SRV=srv${UNITTEST_NUM}.pid
clean_remote_node 0 $SRV
RPMEM_CMD="\"cd ${NODE_TEST_DIR[0]} && RPMEMD_LOG_LEVEL=\$RPMEMD_LOG_LEVEL RPMEMD_LOG_FILE=\$RPMEMD_LOG_FILE UNITTEST_FORCE_QUIET=1 \
LD_LIBRARY_PATH=${NODE_LD_LIBRARY_PATH[0]}:$REMOTE_LD_LIBRARY_PATH \
./rpmem_fip$EXESUFFIX\""
export_vars_node 1 RPMEM_CMD
if [ -n ${RPMEM_MAX_NLANES+x} ]; then
export_vars_node 1 RPMEM_MAX_NLANES
fi
| 786 | 28.148148 | 133 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmem_fip/rpmem_fip_oob.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmem_fip_oob.c -- simple oob connection implementation for exchanging
* required RDMA related data
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include "rpmem_common.h"
#include "rpmem_proto.h"
#include "rpmem_fip_oob.h"
#include "rpmem_ssh.h"
#include "unittest.h"
#include "rpmem_util.h"
#include "os.h"
#define CMD_BUFF_SIZE 4096
static const char *rpmem_cmd;
/*
* set_rpmem_cmd -- set RPMEM_CMD variable
*/
void
set_rpmem_cmd(const char *fmt, ...)
{
static char cmd_buff[CMD_BUFF_SIZE];
if (!rpmem_cmd) {
char *cmd = os_getenv(RPMEM_CMD_ENV);
UT_ASSERTne(cmd, NULL);
rpmem_cmd = STRDUP(cmd);
}
ssize_t ret;
size_t cnt = 0;
va_list ap;
va_start(ap, fmt);
ret = SNPRINTF(&cmd_buff[cnt], CMD_BUFF_SIZE - cnt, "%s ", rpmem_cmd);
UT_ASSERT(ret > 0);
cnt += (size_t)ret;
ret = vsnprintf(&cmd_buff[cnt], CMD_BUFF_SIZE - cnt, fmt, ap);
UT_ASSERT(ret > 0);
cnt += (size_t)ret;
va_end(ap);
ret = os_setenv(RPMEM_CMD_ENV, cmd_buff, 1);
UT_ASSERTeq(ret, 0);
/*
* Rpmem has internal RPMEM_CMD variable copy and it is assumed
* RPMEMD_CMD will not change its value during execution. To refresh the
* internal copy it must be destroyed and a instance must be initialized
* manually.
*/
rpmem_util_cmds_fini();
rpmem_util_cmds_init();
}
/*
* client_exchange -- connect to remote host and exchange required information
*/
client_t *
client_exchange(struct rpmem_target_info *info,
unsigned nlanes,
enum rpmem_provider provider,
struct rpmem_resp_attr *resp)
{
struct rpmem_ssh *ssh = rpmem_ssh_open(info);
UT_ASSERTne(ssh, NULL);
int ret;
ret = rpmem_ssh_send(ssh, &nlanes, sizeof(nlanes));
UT_ASSERTeq(ret, 0);
ret = rpmem_ssh_send(ssh, &provider, sizeof(provider));
UT_ASSERTeq(ret, 0);
ret = rpmem_ssh_recv(ssh, resp, sizeof(*resp));
UT_ASSERTeq(ret, 0);
return ssh;
}
/*
* client_close_begin -- begin closing connection
*/
void
client_close_begin(client_t *c)
{
int cmd = 1;
int ret;
ret = rpmem_ssh_send(c, &cmd, sizeof(cmd));
UT_ASSERTeq(ret, 0);
ret = rpmem_ssh_recv(c, &cmd, sizeof(cmd));
UT_ASSERTeq(ret, 0);
UT_ASSERTeq(cmd, 0);
}
/*
* client_close_end -- end closing connection
*/
void
client_close_end(client_t *c)
{
rpmem_ssh_close(c);
}
/*
* server_exchange_begin -- accept a connection and read required information
*/
void
server_exchange_begin(unsigned *lanes, enum rpmem_provider *provider,
char **addr)
{
UT_ASSERTne(addr, NULL);
char *conn = rpmem_get_ssh_conn_addr();
UT_ASSERTne(conn, NULL);
*addr = strdup(conn);
UT_ASSERTne(*addr, NULL);
uint32_t status = 0;
WRITE(STDOUT_FILENO, &status, sizeof(status));
READ(STDIN_FILENO, lanes, sizeof(*lanes));
READ(STDIN_FILENO, provider, sizeof(*provider));
}
/*
* server_exchange_end -- send response to client
*/
void
server_exchange_end(struct rpmem_resp_attr resp)
{
WRITE(STDOUT_FILENO, &resp, sizeof(resp));
}
/*
* server_close_begin -- wait for close command
*/
void
server_close_begin(void)
{
int cmd = 0;
READ(STDIN_FILENO, &cmd, sizeof(cmd));
UT_ASSERTeq(cmd, 1);
}
/*
* server_close_end -- send close response and wait for disconnect
*/
void
server_close_end(void)
{
int cmd = 0;
WRITE(STDOUT_FILENO, &cmd, sizeof(cmd));
}
| 3,345 | 18.567251 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/rpmemd_log/rpmemd_log_test.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2017, Intel Corporation */
/*
* rpmemd_log_test.c -- unit tests for rpmemd_log
*/
#include <stddef.h>
#include <sys/param.h>
#include <syslog.h>
#include "unittest.h"
#include "rpmemd_log.h"
#define PREFIX "prefix"
static FILE *syslog_fh;
/*
* openlog -- mock for openlog function which logs its usage
*/
FUNC_MOCK(openlog, void, const char *ident, int option, int facility)
FUNC_MOCK_RUN_DEFAULT {
UT_OUT("openlog: ident = %s, option = %d, facility = %d",
ident, option, facility);
}
FUNC_MOCK_END
/*
* closelog -- mock for closelog function which logs its usage
*/
FUNC_MOCK(closelog, void, void)
FUNC_MOCK_RUN_DEFAULT {
UT_OUT("closelog");
}
FUNC_MOCK_END
/*
* syslog -- mock for syslog function which redirects message to a file
*/
FUNC_MOCK(syslog, void, int priority, const char *format, ...)
FUNC_MOCK_RUN_DEFAULT {
UT_ASSERT(priority == LOG_ERR ||
priority == LOG_WARNING ||
priority == LOG_NOTICE ||
priority == LOG_INFO ||
priority == LOG_DEBUG);
va_list ap;
va_start(ap, format);
vfprintf(syslog_fh, format, ap);
va_end(ap);
}
FUNC_MOCK_END
/*
* vsyslog -- mock for vsyslog function which redirects message to a file
*/
FUNC_MOCK(vsyslog, void, int priority, const char *format, va_list ap)
FUNC_MOCK_RUN_DEFAULT {
UT_ASSERT(priority == LOG_ERR ||
priority == LOG_WARNING ||
priority == LOG_NOTICE ||
priority == LOG_INFO ||
priority == LOG_DEBUG);
vfprintf(syslog_fh, format, ap);
}
FUNC_MOCK_END
/*
* l2s -- level to string
*/
static const char *
l2s(enum rpmemd_log_level level)
{
return rpmemd_log_level_to_str(level);
}
/*
* test_log_messages -- test log messages on specified level
*/
static void
test_log_messages(enum rpmemd_log_level level)
{
rpmemd_log_level = level;
RPMEMD_LOG(ERR, "ERR message on %s level", l2s(level));
RPMEMD_LOG(WARN, "WARN message on %s level", l2s(level));
RPMEMD_LOG(NOTICE, "NOTICE message on %s level", l2s(level));
RPMEMD_LOG(INFO, "INFO message on %s level", l2s(level));
RPMEMD_DBG("DBG message on %s level", l2s(level));
}
/*
* test_all_log_messages -- test log messages on all levels, with and without
* a prefix.
*/
static void
test_all_log_messages(void)
{
rpmemd_prefix(NULL);
test_log_messages(RPD_LOG_ERR);
test_log_messages(RPD_LOG_WARN);
test_log_messages(RPD_LOG_NOTICE);
test_log_messages(RPD_LOG_INFO);
test_log_messages(_RPD_LOG_DBG);
rpmemd_prefix("[%s]", PREFIX);
test_log_messages(RPD_LOG_ERR);
test_log_messages(RPD_LOG_WARN);
test_log_messages(RPD_LOG_NOTICE);
test_log_messages(RPD_LOG_INFO);
test_log_messages(_RPD_LOG_DBG);
}
#define USAGE() do {\
UT_ERR("usage: %s fatal|log|assert "\
"stderr|file|syslog <file>", argv[0]);\
} while (0)
enum test_log_type {
TEST_STDERR,
TEST_FILE,
TEST_SYSLOG,
};
int
main(int argc, char *argv[])
{
START(argc, argv, "rpmemd_log");
if (argc < 4) {
USAGE();
return 1;
}
const char *log_op = argv[1];
const char *log_type = argv[2];
const char *file = argv[3];
int do_fatal = 0;
int do_assert = 0;
if (strcmp(log_op, "fatal") == 0) {
do_fatal = 1;
} else if (strcmp(log_op, "assert") == 0) {
do_assert = 1;
} else if (strcmp(log_op, "log") == 0) {
} else {
USAGE();
return 1;
}
enum test_log_type type;
if (strcmp(log_type, "stderr") == 0) {
type = TEST_STDERR;
} else if (strcmp(log_type, "file") == 0) {
type = TEST_FILE;
} else if (strcmp(log_type, "syslog") == 0) {
type = TEST_SYSLOG;
} else {
USAGE();
return 1;
}
int fd_stderr = -1;
FILE *stderr_fh = NULL;
switch (type) {
case TEST_STDERR:
/*
* Duplicate stdout file descriptor in order to preserve
* the file list after redirecting the stdout to a file.
*/
fd_stderr = dup(2);
UT_ASSERTne(fd_stderr, -1);
os_close(2);
stderr_fh = os_fopen(file, "a");
UT_ASSERTne(stderr_fh, NULL);
break;
case TEST_SYSLOG:
syslog_fh = os_fopen(file, "a");
UT_ASSERTne(syslog_fh, NULL);
break;
default:
break;
}
int ret;
switch (type) {
case TEST_STDERR:
ret = rpmemd_log_init("rpmemd_log", NULL, 0);
UT_ASSERTeq(ret, 0);
break;
case TEST_SYSLOG:
ret = rpmemd_log_init("rpmemd_log", NULL, 1);
UT_ASSERTeq(ret, 0);
break;
case TEST_FILE:
ret = rpmemd_log_init("rpmemd_log", file, 0);
UT_ASSERTeq(ret, 0);
break;
}
if (do_fatal) {
RPMEMD_FATAL("fatal");
} else if (do_assert) {
RPMEMD_ASSERT(1);
RPMEMD_ASSERT(0);
} else {
test_all_log_messages();
}
rpmemd_log_close();
switch (type) {
case TEST_STDERR:
/* restore the original stdout file descriptor */
fclose(stderr_fh);
UT_ASSERTeq(dup2(fd_stderr, 2), 2);
os_close(fd_stderr);
break;
case TEST_SYSLOG:
fclose(syslog_fh);
break;
default:
break;
}
DONE(NULL);
}
| 4,755 | 19.5 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_source/TESTS.py
|
#!../env.py
#
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2020, Intel Corporation
import testframework as t
from testframework import granularity as g
@g.require_granularity(g.ANY)
class PMEM2_SOURCE(t.Test):
test_type = t.Short
def run(self, ctx):
filepath = ctx.create_holey_file(16 * t.MiB, 'testfile1')
ctx.exec('pmem2_source', self.test_case, filepath)
@g.no_testdir()
class PMEM2_SOURCE_NO_DIR(t.Test):
test_type = t.Short
def run(self, ctx):
ctx.exec('pmem2_source', self.test_case)
class TEST0(PMEM2_SOURCE):
"""setting a read + write file descriptor in pmem2_source"""
test_case = "test_set_rw_fd"
class TEST1(PMEM2_SOURCE):
"""setting a read only file descriptor in pmem2_source"""
test_case = "test_set_ro_fd"
class TEST2(PMEM2_SOURCE):
"""setting invalid (closed) file descriptor in pmem2_source"""
test_case = "test_set_invalid_fd"
class TEST3(PMEM2_SOURCE):
"""setting a write only file descriptor in pmem2_source"""
test_case = "test_set_wronly_fd"
class TEST4(PMEM2_SOURCE):
"""allocation of pmem2_source in case of missing memory in system"""
test_case = "test_alloc_src_enomem"
class TEST5(PMEM2_SOURCE_NO_DIR):
"""deleting null pmem2_source"""
test_case = "test_delete_null_config"
@t.windows_only
class TEST6(PMEM2_SOURCE):
"""set handle in the source"""
test_case = "test_set_handle"
@t.windows_only
class TEST7(PMEM2_SOURCE_NO_DIR):
"""set INVALID_HANLE_VALUE in the source"""
test_case = "test_set_null_handle"
@t.windows_only
class TEST8(PMEM2_SOURCE):
"""set invalid handle in the source"""
test_case = "test_set_invalid_handle"
@t.windows_only
class TEST9(PMEM2_SOURCE):
"""set handle to a directory in the source"""
test_case = "test_set_directory_handle"
def run(self, ctx):
ctx.exec('pmem2_source', self.test_case, ctx.testdir)
@t.windows_only
class TEST10(PMEM2_SOURCE_NO_DIR):
"""set handle to a mutex in the source"""
test_case = "test_set_mutex_handle"
@t.windows_exclude
class TEST11(PMEM2_SOURCE):
"""set directory's fd in the source"""
test_case = "test_set_directory_fd"
def run(self, ctx):
ctx.exec('pmem2_source', self.test_case, ctx.testdir)
| 2,283 | 22.546392 | 72 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_source/pmem2_source.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* pmem2_source.c -- pmem2_source unittests
*/
#include "fault_injection.h"
#include "libpmem2.h"
#include "unittest.h"
#include "ut_pmem2_utils.h"
#include "ut_pmem2_config.h"
#include "source.h"
#include "out.h"
/*
* verify_fd -- verify value fd or handle in source
*/
static void
verify_fd(struct pmem2_source *src, int fd)
{
#ifdef WIN32
UT_ASSERTeq(src->type, PMEM2_SOURCE_HANDLE);
UT_ASSERTeq(src->value.handle, fd != INVALID_FD ?
(HANDLE)_get_osfhandle(fd) : INVALID_HANDLE_VALUE);
#else
UT_ASSERTeq(src->type, PMEM2_SOURCE_FD);
UT_ASSERTeq(src->value.fd, fd);
#endif
}
/*
* test_set_rw_fd - test setting O_RDWR fd
*/
static int
test_set_rw_fd(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_rw_fd <file>");
char *file = argv[0];
int fd = OPEN(file, O_RDWR);
struct pmem2_source *src;
int ret = pmem2_source_from_fd(&src, fd);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTne(src, NULL);
verify_fd(src, fd);
ret = pmem2_source_delete(&src);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src, NULL);
CLOSE(fd);
return 1;
}
/*
* test_set_ro_fd - test setting O_RDONLY fd
*/
static int
test_set_ro_fd(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_ro_fd <file>");
char *file = argv[0];
int fd = OPEN(file, O_RDONLY);
struct pmem2_source *src;
int ret = pmem2_source_from_fd(&src, fd);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTne(src, NULL);
verify_fd(src, fd);
ret = pmem2_source_delete(&src);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src, NULL);
CLOSE(fd);
return 1;
}
/*
* test_set_invalid_fd - test setting invalid fd
*/
static int
test_set_invalid_fd(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_invalid_fd <file>");
char *file = argv[0];
/* open and close the file to get invalid fd */
int fd = OPEN(file, O_WRONLY);
CLOSE(fd);
ut_suppress_crt_assert();
struct pmem2_source *src;
int ret = pmem2_source_from_fd(&src, fd);
ut_unsuppress_crt_assert();
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_HANDLE);
UT_ASSERTeq(src, NULL);
return 1;
}
/*
* test_set_wronly_fd - test setting wronly fd
*/
static int
test_set_wronly_fd(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_wronly_fd <file>");
char *file = argv[0];
int fd = OPEN(file, O_WRONLY);
struct pmem2_source *src;
int ret = pmem2_source_from_fd(&src, fd);
#ifdef _WIN32
/* windows doesn't validate open flags */
UT_PMEM2_EXPECT_RETURN(ret, 0);
verify_fd(src, fd);
ret = pmem2_source_delete(&src);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src, NULL);
#else
UT_ASSERTeq(src, NULL);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_HANDLE);
#endif
CLOSE(fd);
return 1;
}
/*
* test_alloc_src_enomem - test pmem2_source allocation with error injection
*/
static int
test_alloc_src_enomem(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_alloc_src_enomem <file>");
char *file = argv[0];
struct pmem2_source *src;
if (!core_fault_injection_enabled()) {
return 1;
}
int fd = OPEN(file, O_RDWR);
core_inject_fault_at(PMEM_MALLOC, 1, "pmem2_malloc");
int ret = pmem2_source_from_fd(&src, fd);
UT_PMEM2_EXPECT_RETURN(ret, -ENOMEM);
UT_ASSERTeq(src, NULL);
CLOSE(fd);
return 1;
}
/*
* test_delete_null_config - test pmem2_source_delete on NULL config
*/
static int
test_delete_null_config(const struct test_case *tc, int argc,
char *argv[])
{
struct pmem2_source *src = NULL;
/* should not crash */
int ret = pmem2_source_delete(&src);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src, NULL);
return 0;
}
#ifdef WIN32
/*
* test_set_handle - test setting valid handle
*/
static int
test_set_handle(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_handle <file>");
char *file = argv[0];
HANDLE h = CreateFile(file, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_ALWAYS, 0, NULL);
UT_ASSERTne(h, INVALID_HANDLE_VALUE);
struct pmem2_source *src;
int ret = pmem2_source_from_handle(&src, h);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src->value.handle, h);
CloseHandle(h);
pmem2_source_delete(&src);
UT_PMEM2_EXPECT_RETURN(ret, 0);
UT_ASSERTeq(src, NULL);
return 1;
}
/*
* test_set_null_handle - test resetting handle
*/
static int
test_set_null_handle(const struct test_case *tc, int argc, char *argv[])
{
struct pmem2_source *src;
int ret = pmem2_source_from_handle(&src, INVALID_HANDLE_VALUE);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_HANDLE);
UT_ASSERTeq(src, NULL);
return 0;
}
/*
* test_set_invalid_handle - test setting invalid handle
*/
static int
test_set_invalid_handle(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_invalid_handle <file>");
char *file = argv[0];
struct pmem2_source *src;
HANDLE h = CreateFile(file, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_ALWAYS, 0, NULL);
UT_ASSERTne(h, INVALID_HANDLE_VALUE);
CloseHandle(h);
int ret = pmem2_source_from_handle(&src, h);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_HANDLE);
return 1;
}
/*
* test_set_directory_handle - test setting a directory handle
*/
static int
test_set_directory_handle(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_directory_handle <file>");
char *file = argv[0];
struct pmem2_source *src;
HANDLE h = CreateFile(file, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_ALWAYS, FILE_FLAG_BACKUP_SEMANTICS, NULL);
UT_ASSERTne(h, INVALID_HANDLE_VALUE);
int ret = pmem2_source_from_handle(&src, h);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_TYPE);
UT_ASSERTeq(src, NULL);
CloseHandle(h);
return 1;
}
/*
* test_set_directory_handle - test setting a mutex handle
*/
static int
test_set_mutex_handle(const struct test_case *tc, int argc, char *argv[])
{
struct pmem2_source *src;
HANDLE h = CreateMutex(NULL, FALSE, NULL);
UT_ASSERTne(h, INVALID_HANDLE_VALUE);
int ret = pmem2_source_from_handle(&src, h);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_HANDLE);
UT_ASSERTeq(src, NULL);
CloseHandle(h);
return 0;
}
#else
/*
* test_set_directory_handle - test setting directory's fd
*/
static int
test_set_directory_fd(const struct test_case *tc, int argc, char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_set_directory_fd <file>");
char *file = argv[0];
struct pmem2_source *src;
int fd = OPEN(file, O_RDONLY);
int ret = pmem2_source_from_fd(&src, fd);
UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_INVALID_FILE_TYPE);
CLOSE(fd);
return 1;
}
#endif
/*
* test_cases -- available test cases
*/
static struct test_case test_cases[] = {
TEST_CASE(test_set_rw_fd),
TEST_CASE(test_set_ro_fd),
TEST_CASE(test_set_invalid_fd),
TEST_CASE(test_set_wronly_fd),
TEST_CASE(test_alloc_src_enomem),
TEST_CASE(test_delete_null_config),
#ifdef _WIN32
TEST_CASE(test_set_handle),
TEST_CASE(test_set_null_handle),
TEST_CASE(test_set_invalid_handle),
TEST_CASE(test_set_directory_handle),
TEST_CASE(test_set_mutex_handle),
#else
TEST_CASE(test_set_directory_fd),
#endif
};
#define NTESTS (sizeof(test_cases) / sizeof(test_cases[0]))
int
main(int argc, char **argv)
{
START(argc, argv, "pmem2_source");
util_init();
out_init("pmem2_source", "TEST_LOG_LEVEL", "TEST_LOG_FILE", 0, 0);
TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS);
out_fini();
DONE(NULL);
}
| 7,608 | 20.433803 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_source_alignment/pmem2_source_alignment.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* pmem2_source_alignment.c -- pmem2_source_alignment unittests
*/
#include <fcntl.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "libpmem2.h"
#include "unittest.h"
#include "ut_pmem2.h"
#include "config.h"
#include "out.h"
/*
* test_get_alignment_success - simply checks returned value
*/
static int
test_get_alignment_success(const struct test_case *tc, int argc,
char *argv[])
{
if (argc < 1)
UT_FATAL("usage: test_get_alignment_success"
" <file> [alignment]");
int ret = 1;
char *file = argv[0];
int fd = OPEN(file, O_RDWR);
struct pmem2_source *src;
PMEM2_SOURCE_FROM_FD(&src, fd);
size_t alignment;
PMEM2_SOURCE_ALIGNMENT(src, &alignment);
size_t ref_alignment = Ut_mmap_align;
/* let's check if it is DEVDAX test */
if (argc >= 2) {
ref_alignment = ATOUL(argv[1]);
ret = 2;
}
UT_ASSERTeq(ref_alignment, alignment);
PMEM2_SOURCE_DELETE(&src);
CLOSE(fd);
return ret;
}
/*
* test_cases -- available test cases
*/
static struct test_case test_cases[] = {
TEST_CASE(test_get_alignment_success),
};
#define NTESTS (sizeof(test_cases) / sizeof(test_cases[0]))
int
main(int argc, char **argv)
{
START(argc, argv, "pmem2_source_alignment");
util_init();
out_init("pmem2_source_alignment", "TEST_LOG_LEVEL",
"TEST_LOG_FILE", 0, 0);
TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS);
out_fini();
DONE(NULL);
}
| 1,486 | 17.822785 | 64 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_source_alignment/TESTS.py
|
#!../env.py
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
#
import testframework as t
class TEST0(t.Test):
test_type = t.Short
def run(self, ctx):
filepath = ctx.create_holey_file(16 * t.MiB, 'testfile')
ctx.exec('pmem2_source_alignment',
'test_get_alignment_success', filepath)
class PMEM2_SOURCE_ALIGNMENT_DEV_DAX(t.Test):
test_type = t.Short
test_case = "test_get_alignment_success"
def run(self, ctx):
dd = ctx.devdaxes.devdax
ctx.exec('pmem2_source_alignment',
self.test_case, dd.path, dd.alignment)
@t.windows_exclude
@t.require_devdax(t.DevDax('devdax', alignment=2 * t.MiB))
class TEST1(PMEM2_SOURCE_ALIGNMENT_DEV_DAX):
pass
@t.windows_exclude
@t.require_devdax(t.DevDax('devdax', alignment=4 * t.KiB))
class TEST2(PMEM2_SOURCE_ALIGNMENT_DEV_DAX):
pass
| 902 | 22.153846 | 64 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/log_pool_win/log_pool_win.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2019, Intel Corporation */
/*
* log_pool.c -- unit test for pmemlog_create() and pmemlog_open()
*
* usage: log_pool op path [poolsize mode]
*
* op can be:
* c - create
* o - open
*
* "poolsize" and "mode" arguments are ignored for "open"
*/
#include "unittest.h"
#define MB ((size_t)1 << 20)
static void
pool_create(const wchar_t *path, size_t poolsize, unsigned mode)
{
char *upath = ut_toUTF8(path);
PMEMlogpool *plp = pmemlog_createW(path, poolsize, mode);
if (plp == NULL)
UT_OUT("!%s: pmemlog_create", upath);
else {
os_stat_t stbuf;
STATW(path, &stbuf);
UT_OUT("%s: file size %zu usable space %zu mode 0%o",
upath, stbuf.st_size,
pmemlog_nbyte(plp),
stbuf.st_mode & 0777);
pmemlog_close(plp);
int result = pmemlog_checkW(path);
if (result < 0)
UT_OUT("!%s: pmemlog_check", upath);
else if (result == 0)
UT_OUT("%s: pmemlog_check: not consistent", upath);
}
free(upath);
}
static void
pool_open(const wchar_t *path)
{
char *upath = ut_toUTF8(path);
PMEMlogpool *plp = pmemlog_openW(path);
if (plp == NULL)
UT_OUT("!%s: pmemlog_open", upath);
else {
UT_OUT("%s: pmemlog_open: Success", upath);
pmemlog_close(plp);
}
free(upath);
}
int
wmain(int argc, wchar_t *argv[])
{
STARTW(argc, argv, "log_pool_win");
if (argc < 3)
UT_FATAL("usage: %s op path [poolsize mode]",
ut_toUTF8(argv[0]));
size_t poolsize;
unsigned mode;
switch (argv[1][0]) {
case 'c':
poolsize = wcstoul(argv[3], NULL, 0) * MB; /* in megabytes */
mode = wcstoul(argv[4], NULL, 8);
pool_create(argv[2], poolsize, mode);
break;
case 'o':
pool_open(argv[2]);
break;
default:
UT_FATAL("unknown operation");
}
DONEW(NULL);
}
| 1,761 | 17.946237 | 66 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/util_poolset_size/util_poolset_size.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* util_poolset_size.c -- unit test for util_poolset_size
*
* usage: util_poolset_size file...
*/
#include "unittest.h"
#include "set.h"
#include "pmemcommon.h"
#include <errno.h>
#define LOG_PREFIX "ut"
#define LOG_LEVEL_VAR "TEST_LOG_LEVEL"
#define LOG_FILE_VAR "TEST_LOG_FILE"
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
int
main(int argc, char *argv[])
{
START(argc, argv, "util_poolset_size");
common_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR,
MAJOR_VERSION, MINOR_VERSION);
if (argc < 2)
UT_FATAL("usage: %s file...",
argv[0]);
for (int i = 1; i < argc; i++) {
char *fname = argv[i];
size_t size = util_poolset_size(fname);
UT_OUT("util_poolset_size(%s): %lu", fname, size);
}
common_fini();
DONE(NULL);
}
| 836 | 18.465116 | 57 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/pmemobjcli/pmemobjcli.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* pmemobjcli.c -- CLI interface for pmemobj API
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdbool.h>
#include <limits.h>
#include <setjmp.h>
#include <inttypes.h>
#include <getopt.h>
#include <libpmemobj.h>
#include "common.h"
#include "os.h"
#include "vec.h"
#define POCLI_ENV_EXIT_ON_ERROR "PMEMOBJCLI_EXIT_ON_ERROR"
#define POCLI_ENV_ECHO_MODE "PMEMOBJCLI_ECHO_MODE"
#define POCLI_ENV_COMMENTS "PMEMOBJCLI_COMMENTS"
#define POCLI_ENV_EMPTY_CMDS "PMEMOBJCLI_EMPTY_CMDS"
#define POCLI_ENV_LONG_NAMES "PMEMOBJCLI_LONG_NAMES"
#define POCLI_ENV_HELP "PMEMOBJCLI_HELP"
#define POCLI_CMD_DELIM " "
#define POCLI_CMD_PROMPT "pmemobjcli $ "
#define POCLI_INBUF_LEN 4096
struct pocli;
TOID_DECLARE(struct item, 1);
/*
* item -- structure used to connect elements in lists.
*/
struct item {
POBJ_LIST_ENTRY(struct item) field;
};
/*
* plist -- structure used as a list entry.
*/
POBJ_LIST_HEAD(plist, struct item);
/*
* struct pocli_ctx -- pmemobjcli context structure for commands
*/
struct pocli_ctx {
PMEMobjpool *pop;
PMEMoid root;
FILE *err;
FILE *out;
struct pocli *pocli;
bool tx_aborted;
VEC(, struct pocli_args *) free_on_abort;
};
/*
* struct pocli_args -- arguments for pmemobjcli command
*/
struct pocli_args {
int argc;
char *argv[];
};
/*
* enum pocli_ret -- return values
*/
enum pocli_ret {
POCLI_RET_OK,
POCLI_ERR_ARGS,
POCLI_ERR_PARS,
POCLI_ERR_CMD,
POCLI_ERR_MALLOC,
POCLI_RET_QUIT,
};
/*
* pocli_cmd_fn -- function prototype for pmemobjcli commands
*/
typedef enum pocli_ret (*pocli_cmd_fn)(struct pocli_ctx *ctx,
struct pocli_args *args);
/*
* struct pocli_cmd -- pmemobjcli command descriptor
*/
struct pocli_cmd {
const char *name; /* long name of command */
const char *name_short; /* short name of command */
const char *usage; /* usage string */
pocli_cmd_fn func; /* command's entry point */
};
/*
* struct pocli_opts -- configuration options for pmemobjcli
*/
struct pocli_opts {
bool exit_on_error; /* exit when error occurred */
bool echo_mode; /* print every command from input */
bool enable_comments; /* enable comments on input */
bool enable_empty_cmds; /* enable empty lines */
bool enable_long_names; /* enable long names */
bool enable_help; /* enable printing help */
};
/*
* struct pocli -- main context of pmemobjcli
*/
struct pocli {
FILE *in; /* input file handle */
const char *fname; /* pool's file name */
char *inbuf; /* input buffer */
size_t inbuf_len; /* input buffer length */
struct pocli_ctx ctx; /* context for commands */
const struct pocli_cmd *cmds; /* available commands */
size_t ncmds; /* number of available commands */
int istty; /* stdout is tty */
struct pocli_opts opts; /* configuration options */
bool print_only; /* don't execute, just print */
};
int pocli_process(struct pocli *pcli);
/*
* pocli_err -- print error message
*/
static enum pocli_ret
pocli_err(struct pocli_ctx *ctx, enum pocli_ret ret, const char *fmt, ...)
{
fprintf(ctx->err, "error: ");
va_list ap;
va_start(ap, fmt);
vfprintf(ctx->err, fmt, ap);
va_end(ap);
return ret;
}
/*
* pocli_printf -- print message
*/
static void
pocli_printf(struct pocli_ctx *ctx, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(ctx->out, fmt, ap);
va_end(ap);
}
/*
* pocli_args_number -- parse type number
*/
static enum pocli_ret
pocli_args_number(struct pocli_args *args, int arg, uint64_t *type_num)
{
assert(args != NULL);
assert(arg >= 0 && arg < args->argc);
assert(type_num != NULL);
uint64_t tn;
char c;
int ret = sscanf(args->argv[arg], "%" SCNu64 "%c", &tn, &c);
if (ret != 1)
return POCLI_ERR_PARS;
*type_num = tn;
return POCLI_RET_OK;
}
/*
* pocli_args_size -- parse size
*/
static enum pocli_ret
pocli_args_size(struct pocli_args *args, int arg, size_t *sizep)
{
assert(args != NULL);
assert(arg >= 0 && arg < args->argc);
assert(sizep != NULL);
if (util_parse_size(args->argv[arg], sizep))
return POCLI_ERR_PARS;
return POCLI_RET_OK;
}
/*
* pocli_args_alloc -- split line into array of arguments
*/
static struct pocli_args *
pocli_args_alloc(char *cmdstr, char *argstr, char *delim)
{
size_t size = sizeof(struct pocli_args);
struct pocli_args *args = NULL;
if (cmdstr) {
size += sizeof(char *);
args = (struct pocli_args *)malloc(size);
if (!args)
return NULL;
args->argc = 1;
args->argv[0] = cmdstr;
}
char *n = strtok(argstr, delim);
while (n) {
int cur = args ? args->argc++ : 0;
size += sizeof(char *);
struct pocli_args *nargs =
(struct pocli_args *)realloc(args, size);
if (!nargs) {
free(args);
return NULL;
}
if (!args)
nargs->argc = 1;
args = nargs;
args->argv[cur] = n;
n = strtok(NULL, delim);
}
return args;
}
/*
* pocli_args_obj_root -- parse object's descriptor from root object
*/
static enum pocli_ret
pocli_args_obj_root(struct pocli_ctx *ctx, char *in, PMEMoid **oidp)
{
char *input = strdup(in);
if (!input)
return POCLI_ERR_MALLOC;
if (!oidp)
return POCLI_ERR_PARS;
struct pocli_args *args = pocli_args_alloc(NULL, input, ".");
if (!args)
return POCLI_ERR_PARS;
enum pocli_ret ret = POCLI_RET_OK;
if (strcmp(args->argv[0], "r") != 0) {
ret = POCLI_ERR_PARS;
goto out;
}
PMEMoid *oid = &ctx->root;
size_t size = pmemobj_root_size(ctx->pop);
for (int i = 1; i < args->argc; i++) {
unsigned ind;
char c;
int n = sscanf(args->argv[i], "%u%c", &ind, &c);
if (n != 1) {
ret = POCLI_ERR_PARS;
goto out;
}
size_t max_ind = size / sizeof(PMEMoid);
if (!max_ind || ind >= max_ind) {
ret = POCLI_ERR_PARS;
goto out;
}
PMEMoid *oids = (PMEMoid *)pmemobj_direct(*oid);
oid = &oids[ind];
size = pmemobj_alloc_usable_size(*oid);
}
*oidp = oid;
out:
free(input);
free(args);
return ret;
}
/*
* pocli_args_obj -- parse object's descriptor
*/
static enum pocli_ret
pocli_args_obj(struct pocli_ctx *ctx, struct pocli_args *args,
int arg, PMEMoid **oidp)
{
assert(args != NULL);
assert(arg >= 0 && arg < args->argc);
assert(oidp != NULL);
assert(ctx != NULL);
char *objs = args->argv[arg];
if (strcmp(objs, "r") == 0) {
*oidp = &ctx->root;
} else if (strcmp(objs, "0") == 0) {
*oidp = NULL;
} else if (strcmp(objs, "NULL") == 0) {
*oidp = NULL;
} else if (objs[0] == 'r') {
return pocli_args_obj_root(ctx, args->argv[arg], oidp);
} else {
return pocli_err(ctx, POCLI_ERR_PARS,
"invalid object specified -- '%s'\n", objs);
}
return POCLI_RET_OK;
}
/*
* pocli_args_list_elm -- parse object's descriptor and checks if it's on list
*/
static enum pocli_ret
pocli_args_list_elm(struct pocli_ctx *ctx, struct pocli_args *args,
int arg, PMEMoid **oidp, struct plist *head)
{
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, arg, oidp);
if (ret)
return ret;
if (*oidp == NULL)
return POCLI_RET_OK;
TOID(struct item) tmp;
POBJ_LIST_FOREACH(tmp, head, field) {
if (OID_EQUALS(tmp.oid, **oidp))
return POCLI_RET_OK;
}
return pocli_err(ctx, POCLI_ERR_PARS,
"object %s is not member of given list\n", args->argv[arg]);
}
/*
* parse_stage -- return proper string variable referring to transaction state
*/
static const char *
parse_stage(void)
{
enum pobj_tx_stage st = pmemobj_tx_stage();
const char *stage = "";
switch (st) {
case TX_STAGE_NONE:
stage = "TX_STAGE_NONE";
break;
case TX_STAGE_WORK:
stage = "TX_STAGE_WORK";
break;
case TX_STAGE_ONCOMMIT:
stage = "TX_STAGE_ONCOMMIT";
break;
case TX_STAGE_ONABORT:
stage = "TX_STAGE_ONABORT";
break;
case TX_STAGE_FINALLY:
stage = "TX_STAGE_FINALLY";
break;
default:
assert(0); /* unreachable */
break;
}
return stage;
}
/*
* pocli_pmemobj_direct -- pmemobj_direct() command
*/
static enum pocli_ret
pocli_pmemobj_direct(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
void *obj = pmemobj_direct(*oidp);
pocli_printf(ctx, "%s(%s): off = 0x%jx uuid = 0x%jx ptr = %p\n",
args->argv[0], args->argv[1],
oidp->off, oidp->pool_uuid_lo, obj);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_type_num -- pmemobj_type_num() command
*/
static enum pocli_ret
pocli_pmemobj_type_num(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
uint64_t type_num = pmemobj_type_num(*oidp);
pocli_printf(ctx, "%s(%s): type num = %llu\n",
args->argv[0], args->argv[1], type_num);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_alloc_usable_size -- pmemobj_alloc_usable_size() command
*/
static enum pocli_ret
pocli_pmemobj_alloc_usable_size(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
size_t size = pmemobj_alloc_usable_size(*oidp);
pocli_printf(ctx, "%s(%s): size = %zu\n",
args->argv[0], args->argv[1], size);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_root -- pmemobj_root() command
*/
static enum pocli_ret
pocli_pmemobj_root(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_size(args, 1, &size);
if (ret)
return ret;
PMEMoid root = pmemobj_root(ctx->pop, size);
if (OID_IS_NULL(root))
return pocli_err(ctx, POCLI_ERR_CMD, "pmemobj_root failed\n");
ctx->root = root;
pocli_printf(ctx, "%s(%zu): off = 0x%jx uuid = 0x%jx\n",
args->argv[0], size, ctx->root.off,
ctx->root.pool_uuid_lo);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_root_size -- pmemobj_root_size() command
*/
static enum pocli_ret
pocli_pmemobj_root_size(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
size_t size = pmemobj_root_size(ctx->pop);
pocli_printf(ctx, "%s: size = %lu\n",
args->argv[0], size);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_do_alloc -- pmemobj_alloc and pmemobj_zalloc() common part
*/
static enum pocli_ret
pocli_pmemobj_do_alloc(struct pocli_ctx *ctx, struct pocli_args *args,
int (fn_alloc)(PMEMobjpool *pop, PMEMoid *oid, size_t size,
uint64_t type_num))
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
uint64_t type_num = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot allocate to root object\n");
ret = pocli_args_number(args, 2, &type_num);
if (ret)
return ret;
ret = pocli_args_size(args, 3, &size);
if (ret)
return ret;
int r = fn_alloc(ctx->pop, oidp, size, type_num);
pocli_printf(ctx, "%s(%s, %zu, %llu): %d\n",
args->argv[0], args->argv[1], size, type_num, r);
return ret;
}
/*
* do_alloc -- wrapper for pmemobj_alloc() function with default constructor.
*/
static int
do_alloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size, uint64_t type_num)
{
return pmemobj_alloc(pop, oidp, size, type_num, NULL, NULL);
}
/*
* pocli_pmemobj_alloc -- pmemobj_alloc() command
*/
static enum pocli_ret
pocli_pmemobj_alloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_alloc(ctx, args, do_alloc);
}
/*
* pocli_pmemobj_zalloc -- pmemobj_zalloc() command
*/
static enum pocli_ret
pocli_pmemobj_zalloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_alloc(ctx, args, pmemobj_zalloc);
}
/*
* pocli_pmemobj_do_realloc -- pmemobj_realloc and pmemobj_zrealloc() commands
* common part
*/
static enum pocli_ret
pocli_pmemobj_do_realloc(struct pocli_ctx *ctx, struct pocli_args *args,
int (*fn_realloc)(PMEMobjpool *pop, PMEMoid *oid, size_t size,
uint64_t type_num))
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
uint64_t type_num = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot realloc with NULL oid pointer\n");
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot reallocate to root object\n");
ret = pocli_args_number(args, 2, &type_num);
if (ret)
return ret;
ret = pocli_args_size(args, 3, &size);
if (ret)
return ret;
int r = fn_realloc(ctx->pop, oidp, size, type_num);
pocli_printf(ctx, "%s(%s, %zu, %llu): %d off = 0x%llx uuid = 0x%llx\n",
args->argv[0], args->argv[1], size, type_num,
r, oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_realloc -- pmemobj_realloc() command
*/
static enum pocli_ret
pocli_pmemobj_realloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_realloc(ctx, args, pmemobj_realloc);
}
/*
* pocli_pmemobj_zrealloc -- pmemobj_zrealloc() command
*/
static enum pocli_ret
pocli_pmemobj_zrealloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_realloc(ctx, args, pmemobj_zrealloc);
}
/*
* pocli_pmemobj_free -- pmemobj_free() command
*/
static enum pocli_ret
pocli_pmemobj_free(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"NULL pointer not allowed here\n");
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot free root object\n");
void *oidp_tmp = pmemobj_direct(*oidp);
pmemobj_free(oidp);
pocli_printf(ctx, "%s(%p): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], oidp_tmp, oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_strdup -- pmemobj_strdup() command
*/
static enum pocli_ret
pocli_pmemobj_strdup(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
uint64_t type_num;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use root object\n");
ret = pocli_args_number(args, 3, &type_num);
if (ret)
return ret;
int r = pmemobj_strdup(ctx->pop, oidp, args->argv[2], type_num);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_strdup() failed\n");
pocli_printf(ctx, "%s(%s, %s, %llu): %d\n",
args->argv[0], args->argv[1], args->argv[2],
type_num, r);
return ret;
}
/*
* pocli_str_root_copy -- copy a string into a root object data
*/
static enum pocli_ret
pocli_str_root_copy(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 3)
return POCLI_ERR_ARGS;
size_t offset = 0;
enum pocli_ret ret = pocli_args_size(args, 1, &offset);
if (ret)
return ret;
const char *str = args->argv[2];
if (str == NULL)
return POCLI_ERR_ARGS;
size_t len = strlen(str);
size_t root_size = pmemobj_root_size(ctx->pop);
if (offset + len > root_size)
return POCLI_ERR_ARGS;
PMEMoid root = pmemobj_root(ctx->pop, root_size);
assert(!OID_IS_NULL(root));
char *root_data = (char *)pmemobj_direct(root);
pmemobj_memcpy_persist(ctx->pop, root_data + offset, str, len);
return ret;
}
/*
* pocli_str_root_print -- print a string stored in the root object data
*/
static enum pocli_ret
pocli_str_root_print(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 3)
return POCLI_ERR_ARGS;
size_t offset = 0;
enum pocli_ret ret = pocli_args_size(args, 1, &offset);
if (ret)
return ret;
size_t len = 0;
ret = pocli_args_number(args, 2, &len);
if (ret)
return ret;
size_t root_size = pmemobj_root_size(ctx->pop);
if (offset + len > root_size)
return POCLI_ERR_ARGS;
PMEMoid root = pmemobj_root(ctx->pop, root_size);
assert(!OID_IS_NULL(root));
char *root_data = (char *)pmemobj_direct(root);
char *buff = (char *)malloc(len + 1);
assert(buff != NULL);
memcpy(buff, root_data + offset, len);
buff[len] = '\0';
printf("%s\n", buff);
free(buff);
return ret;
}
/*
* pocli_pmemobj_first -- pmemobj_first() command
*/
static enum pocli_ret
pocli_pmemobj_first(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
PMEMoid oidp = pmemobj_first(ctx->pop);
if (OID_IS_NULL(oidp))
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_first() failed\n");
pocli_printf(ctx, "%s: off = 0x%llx uuid = 0x%llx\n",
args->argv[0], oidp.off, oidp.pool_uuid_lo);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_next -- pmemobj_next() command
*/
static enum pocli_ret
pocli_pmemobj_next(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
PMEMoid oidp_next;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
oidp_next = pmemobj_next(*oidp);
pocli_printf(ctx, "%s(%p): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], pmemobj_direct(*oidp), oidp_next.off,
oidp_next.pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_memcpy_persist -- pmemobj_memcpy_persist() command
*/
static enum pocli_ret
pocli_pmemobj_memcpy_persist(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 6)
return POCLI_ERR_ARGS;
PMEMoid *dest = NULL;
PMEMoid *src;
enum pocli_ret ret;
uint64_t offset;
uint64_t len;
if ((ret = pocli_args_obj(ctx, args, 1, &dest)))
return ret;
if ((ret = pocli_args_number(args, 2, &offset)))
return ret;
if (dest == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
char *dest_p = (char *)pmemobj_direct(*dest);
dest_p += offset;
if ((ret = pocli_args_obj(ctx, args, 3, &src)))
return ret;
if ((ret = pocli_args_number(args, 4, &offset)))
return ret;
if (src == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[3]);
char *src_p = (char *)pmemobj_direct(*src);
src_p += offset;
if ((ret = pocli_args_number(args, 5, &len)))
return ret;
void *result = pmemobj_memcpy_persist(ctx->pop, dest_p, src_p, len);
pocli_printf(ctx, "%s(%p, %p, %u): ptr = %p\n",
args->argv[0], dest_p, src_p, len, result);
return ret;
}
/*
* pocli_pmemobj_memset_persist -- pmemobj_memset_persist() command
*/
static enum pocli_ret
pocli_pmemobj_memset_persist(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 5)
return POCLI_ERR_ARGS;
PMEMoid *oid = NULL;
enum pocli_ret ret;
uint64_t offset;
uint64_t len;
uint64_t c;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if ((ret = pocli_args_number(args, 2, &offset)))
return ret;
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
char *dest_p = (char *)pmemobj_direct(*oid);
dest_p += offset;
if ((ret = pocli_args_number(args, 3, &c)))
return ret;
if ((ret = pocli_args_number(args, 4, &len)))
return ret;
if (len == UINT64_MAX)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[4]);
void *result = pmemobj_memset_persist(ctx->pop, dest_p, (int)c, len);
pocli_printf(ctx, "%s(%p, %u, %d): ptr = %p\n",
args->argv[0], dest_p, c, len, result);
return ret;
}
/*
* pocli_pmemobj_do_persist -- common part of pmemobj_persist() and
* pmemobj_flush() command
*/
static enum pocli_ret
pocli_pmemobj_do_persist(struct pocli_ctx *ctx, struct pocli_args *args,
void (*fn_persist)(PMEMobjpool *pop, const void *addr, size_t len))
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oid = NULL;
enum pocli_ret ret;
uint64_t offset;
uint64_t len;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if ((ret = pocli_args_number(args, 2, &offset)))
return ret;
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
char *dest_p = (char *)pmemobj_direct(*oid);
dest_p += offset;
if ((ret = pocli_args_number(args, 3, &len)))
return ret;
fn_persist(ctx->pop, dest_p, len);
pocli_printf(ctx, "%s(%p, %u)\n",
args->argv[0], dest_p, len);
return ret;
}
/*
* pocli_pmemobj_persist -- pmemobj_persist() command
*/
static enum pocli_ret
pocli_pmemobj_persist(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_persist(ctx, args, pmemobj_persist);
}
/*
* pocli_pmemobj_flush -- pmemobj_flush() command
*/
static enum pocli_ret
pocli_pmemobj_flush(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_persist(ctx, args, pmemobj_flush);
}
/*
* pocli_pmemobj_drain -- pmemobj_drain() command
*/
static enum pocli_ret
pocli_pmemobj_drain(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
pmemobj_drain(ctx->pop);
pocli_printf(ctx, "%s\n", args->argv[0]);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_pool_by_ptr -- pmemobj_pool_by_ptr() command
*/
static enum pocli_ret
pocli_pmemobj_pool_by_ptr(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 3)
return POCLI_ERR_ARGS;
PMEMoid *oid = NULL;
enum pocli_ret ret;
uint64_t offset;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if ((ret = pocli_args_number(args, 2, &offset)))
return ret;
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
char *dest_p = (char *)pmemobj_direct(*oid);
dest_p += offset;
PMEMobjpool *pop = pmemobj_pool_by_ptr(dest_p);
pocli_printf(ctx, "%s(%p): uuid = 0x%llx\n",
args->argv[0], dest_p, pop->uuid_lo);
return ret;
}
/*
* pocli_pmemobj_pool_by_oid -- pmemobj_pool_by_oid() command
*/
static enum pocli_ret
pocli_pmemobj_pool_by_oid(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
PMEMoid *oid = NULL;
enum pocli_ret ret;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
PMEMobjpool *pop = pmemobj_pool_by_oid(*oid);
pocli_printf(ctx, "%s(%p): uuid = 0x%llx\n",
args->argv[0], pmemobj_direct(*oid), pop->uuid_lo);
return ret;
}
/*
* pocli_pmemobj_list_insert -- pmemobj_list_insert() command
*/
static enum pocli_ret
pocli_pmemobj_list_insert(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 5)
return POCLI_ERR_ARGS;
PMEMoid nulloid = OID_NULL;
PMEMoid *dest;
PMEMoid *oid = NULL;
PMEMoid *head_oid;
enum pocli_ret ret;
uint64_t before;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if (pocli_args_obj(ctx, args, 2, &head_oid))
return ret;
if (head_oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[2]);
struct plist *head = (struct plist *)pmemobj_direct(*head_oid);
if ((ret = pocli_args_list_elm(ctx, args, 3, &dest, head)))
return ret;
if (dest == NULL)
dest = &nulloid;
if ((ret = pocli_args_number(args, 4, &before)))
return ret;
if (before > 1)
return pocli_err(ctx, POCLI_ERR_ARGS,
"Before flag different than 0 or 1\n");
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
int r = pmemobj_list_insert(ctx->pop, offsetof(struct item, field),
head, *dest, (int)before, *oid);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_list_insert() failed\n");
pocli_printf(ctx, "%s(%p, %s, %p, %u): %d\n",
args->argv[0], pmemobj_direct(*oid), args->argv[2],
dest, before, r);
return ret;
}
/*
* pocli_pmemobj_list_insert_new -- pmemobj_list_insert_new() command
*/
static enum pocli_ret
pocli_pmemobj_list_insert_new(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 7)
return POCLI_ERR_ARGS;
PMEMoid nulloid = OID_NULL;
PMEMoid *dest;
PMEMoid *oid = NULL;
PMEMoid *head_oid;
enum pocli_ret ret;
uint64_t before;
uint64_t type_num;
uint64_t size;
if ((ret = pocli_args_obj(ctx, args, 1, &oid)))
return ret;
if (oid == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot allocate to root object\n");
if ((ret = pocli_args_obj(ctx, args, 2, &head_oid)))
return ret;
if (head_oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[2]);
struct plist *head = (struct plist *)pmemobj_direct(*head_oid);
if ((ret = pocli_args_list_elm(ctx, args, 3, &dest, head)))
return ret;
if (dest == NULL)
dest = &nulloid;
if ((ret = pocli_args_number(args, 4, &before)))
return ret;
if (before > 1)
return pocli_err(ctx, POCLI_ERR_ARGS,
"Before flag different than 0 or 1\n");
if ((ret = pocli_args_number(args, 5, &type_num)))
return ret;
if ((ret = pocli_args_number(args, 6, &size)))
return ret;
*oid = pmemobj_list_insert_new(ctx->pop, offsetof(struct item, field),
head, *dest, (int)before, size, type_num, NULL, NULL);
pmemobj_persist(ctx->pop, oid, sizeof(PMEMoid));
if (OID_IS_NULL(*oid))
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_list_insert_new() failed\n");
pocli_printf(ctx, "%s(%s, %p, %u, %llu, %zu): off = 0x%jx uuid = 0x%jx"
" ptr = %p\n", args->argv[0], args->argv[2],
dest, before, type_num, size, oid->off,
oid->pool_uuid_lo, pmemobj_direct(*oid));
return ret;
}
/*
* pocli_pmemobj_list_remove -- pmemobj_list_remove() command
*/
static enum pocli_ret
pocli_pmemobj_list_remove(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oid;
PMEMoid *head_oid = NULL;
enum pocli_ret ret;
uint64_t if_free;
if ((ret = pocli_args_obj(ctx, args, 2, &head_oid)))
return ret;
if (head_oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[2]);
struct plist *head = (struct plist *)pmemobj_direct(*head_oid);
if ((ret = pocli_args_list_elm(ctx, args, 1, &oid, head)))
return ret;
if ((ret = pocli_args_number(args, 3, &if_free)))
return ret;
if (if_free > 1)
return pocli_err(ctx, POCLI_ERR_ARGS,
"Free flag different than 0 or 1\n");
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
void *oidp = pmemobj_direct(*oid);
int r = pmemobj_list_remove(ctx->pop, offsetof(struct item, field),
head, *oid, (int)if_free);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_list_remove() failed\n");
if (if_free) {
*oid = OID_NULL;
pmemobj_persist(ctx->pop, oid, sizeof(PMEMoid));
}
pocli_printf(ctx, "%s(%p, %s, %u): off = 0x%jx uuid = 0x%jx\n",
args->argv[0], oidp, args->argv[2], if_free,
oid->off, oid->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_list_move -- pmemobj_list_move() command
*/
static enum pocli_ret
pocli_pmemobj_list_move(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 6)
return POCLI_ERR_ARGS;
PMEMoid nulloid = OID_NULL;
PMEMoid *dest;
PMEMoid *oid;
PMEMoid *head_oid;
enum pocli_ret ret;
uint64_t before;
size_t offset = offsetof(struct item, field);
if ((ret = pocli_args_obj(ctx, args, 2, &head_oid)))
return ret;
if (head_oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[2]);
struct plist *head_src = (struct plist *)pmemobj_direct(*head_oid);
if ((ret = pocli_args_obj(ctx, args, 3, &head_oid)))
return ret;
if (head_oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[3]);
struct plist *head_dest = (struct plist *)pmemobj_direct(*head_oid);
if ((ret = pocli_args_list_elm(ctx, args, 1, &oid, head_src)))
return ret;
if ((ret = pocli_args_list_elm(ctx, args, 4, &dest, head_dest)))
return ret;
if (dest == NULL)
dest = &nulloid;
if ((ret = pocli_args_number(args, 5, &before)))
return ret;
if (before > 1)
return pocli_err(ctx, POCLI_ERR_ARGS,
"Before flag different than 0 or 1\n");
if (oid == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
int r = pmemobj_list_move(ctx->pop, offset, head_src, offset, head_dest,
*dest, (int)before, *oid);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_list_move() failed\n");
pocli_printf(ctx, "%s(%p, %s, %s, %p, %u): %d\n", args->argv[0],
pmemobj_direct(*oid), args->argv[2], args->argv[3],
pmemobj_direct(*dest), before, r);
return ret;
}
/*
* pocli_pmemobj_tx_begin -- pmemobj_tx_begin() command
*/
static enum pocli_ret
pocli_pmemobj_tx_begin(struct pocli_ctx *ctx, struct pocli_args *args)
{
enum pocli_ret ret = POCLI_RET_OK;
int r;
switch (args->argc) {
case 1: {
r = pmemobj_tx_begin(ctx->pop, NULL, TX_PARAM_NONE);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_tx_begin() failed");
pocli_printf(ctx, "%s: %d\n", args->argv[0], r);
}
break;
case 2: {
if (strcmp(args->argv[1], "jmp") != 0)
return POCLI_ERR_ARGS;
jmp_buf jmp;
if (setjmp(jmp)) {
const char *command = ctx->tx_aborted ?
"pmemobj_tx_abort" : "pmemobj_tx_end";
pocli_printf(ctx, "%s: %d\n",
command, pmemobj_tx_errno());
/*
* Free all objects, except the one we currently
* use.
*/
while (VEC_SIZE(&ctx->free_on_abort) > 1) {
free(VEC_BACK(&ctx->free_on_abort));
VEC_POP_BACK(&ctx->free_on_abort);
}
return POCLI_RET_OK;
} else {
r = pmemobj_tx_begin(ctx->pop, jmp,
TX_PARAM_NONE);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_tx_begin() failed");
}
pocli_printf(ctx, "%s(jmp): %d\n", args->argv[0], r);
ret = (enum pocli_ret)pocli_process(ctx->pocli);
if (ret)
return ret;
}
break;
default:
return POCLI_ERR_ARGS;
}
return ret;
}
/*
* pocli_pmemobj_tx_end -- pmemobj_tx_end() command
*/
static enum pocli_ret
pocli_pmemobj_tx_end(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() == TX_STAGE_NONE ||
pmemobj_tx_stage() == TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"transaction in improper stage\n");
ctx->tx_aborted = false;
int ret = pmemobj_tx_end();
pocli_printf(ctx, "%s: %d\n", args->argv[0], ret);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_tx_commit -- pmemobj_tx_commit() command
*/
static enum pocli_ret
pocli_pmemobj_tx_commit(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
pmemobj_tx_commit();
pocli_printf(ctx, "%s\n", args->argv[0]);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_tx_abort -- pmemobj_tx_abort() command
*/
static enum pocli_ret
pocli_pmemobj_tx_abort(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
int err;
int count = sscanf(args->argv[1], "%d", &err);
if (count != 1)
return POCLI_ERR_PARS;
ctx->tx_aborted = true;
pmemobj_tx_abort(err);
pocli_printf(ctx, "pmemobj_tx_abort: %d", err);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_tx_stage -- pmemobj_tx_stage() command
*/
static enum pocli_ret
pocli_pmemobj_tx_stage(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
pocli_printf(ctx, "%s: %s\n", args->argv[0], parse_stage());
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_tx_add_range -- pmemobj_tx_add_range() command
*/
static enum pocli_ret
pocli_pmemobj_tx_add_range(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
size_t offset = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot add NULL pointer\n");
ret = pocli_args_size(args, 2, &offset);
if (ret)
return ret;
ret = pocli_args_size(args, 3, &size);
if (ret)
return ret;
int r = pmemobj_tx_add_range(*oidp, offset, size);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_tx_add_range() failed");
pocli_printf(ctx, "%s(%s, %zu, %zu): %d\n", args->argv[0],
args->argv[1], offset, size, ret, r);
return ret;
}
/*
* pocli_pmemobj_tx_add_range_direct -- pmemobj_tx_add_range_direct() command
*/
static enum pocli_ret
pocli_pmemobj_tx_add_range_direct(struct pocli_ctx *ctx,
struct pocli_args *args)
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
PMEMoid *oidp = NULL;
size_t off = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot add NULL pointer\n");
char *ptr = (char *)pmemobj_direct(*oidp);
ret = pocli_args_size(args, 2, &off);
if (ret)
return ret;
ret = pocli_args_size(args, 3, &size);
if (ret)
return ret;
int r = pmemobj_tx_add_range_direct((void *)(ptr + off), size);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_tx_add_range_direct() failed");
pocli_printf(ctx, "%s(%p, %zu, %zu): %d\n", args->argv[0], ptr,
off, size, r);
return ret;
}
/*
* pocli_pmemobj_do_tx_alloc -- pmemobj_tx_zalloc() and pmemobj_tx_zalloc()
* commands common part
*/
static enum pocli_ret
pocli_pmemobj_do_tx_alloc(struct pocli_ctx *ctx, struct pocli_args *args,
PMEMoid (*fn_alloc)(size_t size, uint64_t type_num))
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
PMEMoid *oidp = NULL;
uint64_t type_num = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot allocate to root object\n");
ret = pocli_args_size(args, 2, &size);
if (ret)
return ret;
ret = pocli_args_number(args, 3, &type_num);
if (ret)
return ret;
*oidp = fn_alloc(size, type_num);
pocli_printf(ctx, "%s(%zu, %llu): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], size, type_num, oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_tx_alloc -- pmemobj_tx_alloc() command
*/
static enum pocli_ret
pocli_pmemobj_tx_alloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_tx_alloc(ctx, args, pmemobj_tx_alloc);
}
/*
* pocli_pmemobj_tx_zalloc -- pmemobj_tx_zalloc() command
*/
static enum pocli_ret
pocli_pmemobj_tx_zalloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_tx_alloc(ctx, args, pmemobj_tx_zalloc);
}
/*
* pocli_pmemobj_do_tx_realloc -- pmemobj_tx_zrealloc() and
* pmemobj_tx_zrealloc() commands common part
*/
static enum pocli_ret
pocli_pmemobj_do_tx_realloc(struct pocli_ctx *ctx, struct pocli_args *args,
PMEMoid (*fn_realloc)(PMEMoid oid, size_t size, uint64_t type_num))
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
PMEMoid *oidp = NULL;
uint64_t type_num = 0;
size_t size = 0;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot reallocate root object\n");
ret = pocli_args_size(args, 2, &size);
if (ret)
return ret;
ret = pocli_args_number(args, 3, &type_num);
if (ret)
return ret;
*oidp = fn_realloc(*oidp, size, type_num);
pocli_printf(ctx, "%s(%p, %zu, %llu): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], oidp, size, type_num,
oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_tx_realloc -- pmemobj_tx_realloc() command
*/
static enum pocli_ret
pocli_pmemobj_tx_realloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_tx_realloc(ctx, args, pmemobj_tx_realloc);
}
/*
* pocli_pmemobj_tx_zrealloc -- pmemobj_tx_zrealloc() command
*/
static enum pocli_ret
pocli_pmemobj_tx_zrealloc(struct pocli_ctx *ctx, struct pocli_args *args)
{
return pocli_pmemobj_do_tx_realloc(ctx, args, pmemobj_tx_zrealloc);
}
/*
* pocli_pmemobj_tx_free -- pmemobj_tx_free() command
*/
static enum pocli_ret
pocli_pmemobj_tx_free(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 2)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
PMEMoid *oidp = NULL;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot free root object\n");
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
int r = pmemobj_tx_free(*oidp);
if (r != POCLI_RET_OK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"pmemobj_tx_free() failed\n");
else
*oidp = OID_NULL;
pocli_printf(ctx, "%s(%p): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], oidp,
oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_tx_strdup -- pmemobj_tx_strdup() command
*/
static enum pocli_ret
pocli_pmemobj_tx_strdup(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 4)
return POCLI_ERR_ARGS;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use in stage different than TX_STAGE_WORK\n");
PMEMoid *oidp = NULL;
uint64_t type_num;
enum pocli_ret ret;
ret = pocli_args_obj(ctx, args, 1, &oidp);
if (ret)
return ret;
if (oidp == &ctx->root)
return pocli_err(ctx, POCLI_ERR_ARGS,
"cannot use root object\n");
ret = pocli_args_number(args, 3, &type_num);
if (ret)
return ret;
if (oidp == NULL)
return pocli_err(ctx, POCLI_ERR_ARGS,
"invalid object -- '%s'\n", args->argv[1]);
*oidp = pmemobj_tx_strdup(args->argv[2], type_num);
pocli_printf(ctx, "%s(%s, %llu): off = 0x%llx uuid = 0x%llx\n",
args->argv[0], args->argv[2], type_num,
oidp->off, oidp->pool_uuid_lo);
return ret;
}
/*
* pocli_pmemobj_tx_process -- pmemobj_tx_process() command
*/
static enum pocli_ret
pocli_pmemobj_tx_process(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
pmemobj_tx_process();
pocli_printf(ctx, "%s\n", args->argv[0]);
return POCLI_RET_OK;
}
/*
* pocli_pmemobj_tx_errno -- pmemobj_tx_errno() command
*/
static enum pocli_ret
pocli_pmemobj_tx_errno(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
pocli_printf(ctx, "%s: %d\n", args->argv[0], pmemobj_tx_errno());
return POCLI_RET_OK;
}
/*
* pocli_get_cmd -- find command of given name
*/
static const struct pocli_cmd *
pocli_get_cmd(struct pocli *pcli, const char *cmds)
{
for (size_t i = 0; i < pcli->ncmds; i++) {
const char *name = pcli->cmds[i].name;
const char *name_short = pcli->cmds[i].name_short;
if (strcmp(cmds, name_short) == 0 ||
(pcli->opts.enable_long_names &&
strcmp(cmds, name) == 0)) {
return &pcli->cmds[i];
}
}
return NULL;
}
static enum pocli_ret
pocli_print(struct pocli_ctx *ctx, struct pocli_args *args)
{
const struct pocli_cmd *cmd = pocli_get_cmd(ctx->pocli, args->argv[0]);
if (!cmd)
return POCLI_ERR_PARS;
printf("%s", cmd->name_short);
if (args->argc == 1) {
printf("\n");
return POCLI_RET_OK;
}
for (int i = 1; i < args->argc; i++)
printf(" %s", args->argv[i]);
printf("\n");
return POCLI_RET_OK;
}
static struct pocli_cmd print_cmd = {"", "", "", pocli_print};
/*
* pocli_print_cmd -- print description of specified command
*/
static void
pocli_print_cmd(struct pocli_ctx *ctx, const struct pocli_cmd *cmd)
{
pocli_printf(ctx, "[%-5s] %-32s - usage: %s %s\n",
cmd->name_short,
cmd->name,
cmd->name,
cmd->usage);
}
/*
* pocli_print_cmd_usage -- print usage of specified command
*/
static void
pocli_print_cmd_usage(struct pocli_ctx *ctx, const struct pocli_cmd *cmd)
{
pocli_printf(ctx, "usage: %s %s\n",
cmd->name,
cmd->usage);
}
/*
* pocli_help -- help command
*/
static enum pocli_ret
pocli_help(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (!ctx->pocli->opts.enable_help)
return POCLI_ERR_CMD;
if (args->argc != 2 && args->argc != 1)
return POCLI_ERR_ARGS;
if (args->argc == 1) {
for (size_t i = 0; i < ctx->pocli->ncmds; i++)
pocli_print_cmd(ctx, &ctx->pocli->cmds[i]);
} else {
const struct pocli_cmd *cmd =
pocli_get_cmd(ctx->pocli, args->argv[1]);
if (!cmd)
return POCLI_ERR_PARS;
pocli_print_cmd_usage(ctx, cmd);
}
return POCLI_RET_OK;
}
/*
* pocli_quit -- quit command
*/
static enum pocli_ret
pocli_quit(struct pocli_ctx *ctx, struct pocli_args *args)
{
if (args->argc != 1)
return POCLI_ERR_ARGS;
return POCLI_RET_QUIT;
}
/*
* pocli_commands -- list of available commands
*/
static struct pocli_cmd pocli_commands[] = {
{
"help", /* name */
"h", /* name_short */
"[<cmd>]", /* usage */
pocli_help, /* func */
},
{
"quit",
"q",
"",
pocli_quit,
},
{
"pmemobj_root",
"pr",
"<size>",
pocli_pmemobj_root,
},
{
"pmemobj_root_size",
"prs",
"",
pocli_pmemobj_root_size,
},
{
"pmemobj_direct",
"pdr",
"<obj>",
pocli_pmemobj_direct,
},
{
"pmemobj_alloc_usable_size",
"paus",
"<obj>",
pocli_pmemobj_alloc_usable_size,
},
{
"pmemobj_alloc",
"pa",
"<obj> <type_num> <size>",
pocli_pmemobj_alloc,
},
{
"pmemobj_zalloc",
"pza",
"<obj> <type_num> <size>",
pocli_pmemobj_zalloc,
},
{
"pmemobj_realloc",
"pre",
"<obj> <type_num> <size>",
pocli_pmemobj_realloc,
},
{
"pmemobj_zrealloc",
"pzre",
"<obj> <type_num> <size>",
pocli_pmemobj_zrealloc,
},
{
"pmemobj_free",
"pf",
"<obj>",
pocli_pmemobj_free,
},
{
"pmemobj_type_num",
"ptn",
"<obj>",
pocli_pmemobj_type_num,
},
{
"pmemobj_strdup",
"psd",
"<obj> <string> <type_num>",
pocli_pmemobj_strdup,
},
{
"pmemobj_first",
"pfi",
"<type_num>",
pocli_pmemobj_first,
},
{
"pmemobj_next",
"pn",
"<obj>",
pocli_pmemobj_next,
},
{
"pmemobj_memcpy_persist",
"pmcp",
"<dest> <off_dest> <src> <off_src> <len>",
pocli_pmemobj_memcpy_persist,
},
{
"pmemobj_memset_persist",
"pmsp",
"<obj> <offset> <pattern> <len>",
pocli_pmemobj_memset_persist,
},
{
"pmemobj_persist",
"pp",
"<obj> <offset> <len>",
pocli_pmemobj_persist,
},
{
"pmemobj_flush",
"pfl",
"<obj> <offset> <len>",
pocli_pmemobj_flush,
},
{
"pmemobj_drain",
"pd",
"",
pocli_pmemobj_drain,
},
{
"pmemobj_pool_by_oid",
"ppbo",
"<obj>",
pocli_pmemobj_pool_by_oid,
},
{
"pmemobj_pool_by_ptr",
"ppbp",
"<obj> <offset>",
pocli_pmemobj_pool_by_ptr,
},
{
"pmemobj_list_insert",
"pli",
"<obj> <head> <dest> <before>",
pocli_pmemobj_list_insert,
},
{
"pmemobj_list_insert_new",
"plin",
"<obj> <head> <dest> <before>"
" <size> <type_num>",
pocli_pmemobj_list_insert_new,
},
{
"pmemobj_list_remove",
"plr",
"<obj> <head> <free>",
pocli_pmemobj_list_remove,
},
{
"pmemobj_list_move",
"plm",
"<obj> <head_src> <head_dest> "
"<dest> <before>",
pocli_pmemobj_list_move,
},
{
"pmemobj_tx_begin",
"ptb",
"[<jmp>]",
pocli_pmemobj_tx_begin,
},
{
"pmemobj_tx_end",
"pte",
"",
pocli_pmemobj_tx_end,
},
{
"pmemobj_tx_abort",
"ptab",
"<errnum>",
pocli_pmemobj_tx_abort,
},
{
"pmemobj_tx_commit",
"ptc",
"",
pocli_pmemobj_tx_commit,
},
{
"pmemobj_tx_stage",
"pts",
"",
pocli_pmemobj_tx_stage,
},
{
"pmemobj_tx_add_range",
"ptar",
"<obj> <offset> <size>",
pocli_pmemobj_tx_add_range,
},
{
"pmemobj_tx_add_range_direct",
"ptard",
"<obj> <offset> <size>",
pocli_pmemobj_tx_add_range_direct,
},
{
"pmemobj_tx_process",
"ptp",
"",
pocli_pmemobj_tx_process,
},
{
"pmemobj_tx_alloc",
"ptal",
"<obj> <size> <type_num>",
pocli_pmemobj_tx_alloc,
},
{
"pmemobj_tx_zalloc",
"ptzal",
"<obj> <size> <type_num>",
pocli_pmemobj_tx_zalloc,
},
{
"pmemobj_tx_realloc",
"ptre",
"<obj> <size> <type_num>",
pocli_pmemobj_tx_realloc,
},
{
"pmemobj_tx_zrealloc",
"ptzre",
"<obj> <size> <type_num>",
pocli_pmemobj_tx_zrealloc,
},
{
"pmemobj_tx_strdup",
"ptsd",
"<obj> <string> <type_num>",
pocli_pmemobj_tx_strdup,
},
{
"pmemobj_tx_free",
"ptf",
"<obj>",
pocli_pmemobj_tx_free,
},
{
"pmemobj_tx_errno",
"pter",
"",
pocli_pmemobj_tx_errno,
},
{
"str_root_copy",
"srcp",
"<size> <string>",
pocli_str_root_copy,
},
{
"str_root_print",
"srpr",
"<size> <size>",
pocli_str_root_print,
}
};
#define POCLI_NCOMMANDS (sizeof(pocli_commands) / sizeof(pocli_commands[0]))
/*
* pocli_evn_parse_bool -- parse environment variable as boolean (1/0)
*/
static int
pocli_env_parse_bool(const char *envname, bool *value)
{
char *env = os_getenv(envname);
if (!env)
return 0;
if (strlen(env) > 1 || (env[0] != '0' && env[0] != '1')) {
fprintf(stderr, "invalid value specified for %s -- '%s'\n",
envname, env);
return -1;
}
*value = env[0] != '0';
return 0;
}
/*
* pocli_read_opts -- read options from env variables
*/
static int
pocli_read_opts(struct pocli_opts *opts)
{
/* default values */
opts->exit_on_error = false;
opts->echo_mode = false;
opts->enable_comments = true;
opts->enable_empty_cmds = true;
opts->enable_long_names = true;
opts->enable_help = true;
int ret;
ret = pocli_env_parse_bool(POCLI_ENV_EXIT_ON_ERROR,
&opts->exit_on_error);
if (ret)
return ret;
ret = pocli_env_parse_bool(POCLI_ENV_ECHO_MODE,
&opts->echo_mode);
if (ret)
return ret;
ret = pocli_env_parse_bool(POCLI_ENV_COMMENTS,
&opts->enable_comments);
if (ret)
return ret;
ret = pocli_env_parse_bool(POCLI_ENV_EMPTY_CMDS,
&opts->enable_empty_cmds);
if (ret)
return ret;
ret = pocli_env_parse_bool(POCLI_ENV_LONG_NAMES,
&opts->enable_long_names);
if (ret)
return ret;
ret = pocli_env_parse_bool(POCLI_ENV_HELP,
&opts->enable_help);
if (ret)
return ret;
return 0;
}
/*
* pocli_alloc -- allocate main context
*/
static struct pocli *
pocli_alloc(FILE *input, const char *fname, const struct pocli_cmd *cmds,
size_t ncmds, size_t inbuf_len, bool print_only)
{
assert(inbuf_len < INT_MAX);
struct pocli_opts opts;
if (pocli_read_opts(&opts))
return NULL;
struct pocli *pcli = (struct pocli *)calloc(1, sizeof(*pcli));
if (!pcli)
return NULL;
memcpy(&pcli->opts, &opts, sizeof(pcli->opts));
pcli->in = input;
pcli->istty = isatty(fileno(pcli->in));
pcli->cmds = cmds;
pcli->ncmds = ncmds;
pcli->print_only = print_only;
pcli->ctx.pocli = pcli;
pcli->ctx.err = stderr;
pcli->ctx.out = stdout;
if (!print_only) {
pcli->ctx.pop = pmemobj_open(fname, NULL);
if (!pcli->ctx.pop) {
fprintf(stderr, "%s: %s\n", fname, pmemobj_errormsg());
goto err_free_pcli;
}
size_t root_size = pmemobj_root_size(pcli->ctx.pop);
if (root_size)
pcli->ctx.root = pmemobj_root(pcli->ctx.pop, root_size);
}
pcli->inbuf_len = inbuf_len;
pcli->inbuf = (char *)malloc(inbuf_len);
if (!pcli->inbuf)
goto err_close_pool;
return pcli;
err_close_pool:
pmemobj_close(pcli->ctx.pop);
err_free_pcli:
free(pcli);
return NULL;
}
/*
* pocli_free -- free main context
*/
static void
pocli_free(struct pocli *pcli)
{
while (pmemobj_tx_stage() != TX_STAGE_NONE) {
while (pmemobj_tx_stage() != TX_STAGE_NONE)
pmemobj_tx_process();
pmemobj_tx_end();
}
VEC_DELETE(&pcli->ctx.free_on_abort);
if (pcli->ctx.pop)
pmemobj_close(pcli->ctx.pop);
free(pcli->inbuf);
free(pcli);
}
/*
* pocli_prompt -- print prompt
*/
static void
pocli_prompt(struct pocli *pcli)
{
if (pcli->istty)
printf(POCLI_CMD_PROMPT);
}
/*
* pocli_process -- process input commands
*/
int
pocli_process(struct pocli *pcli)
{
while (1) {
pocli_prompt(pcli);
if (!fgets(pcli->inbuf, (int)pcli->inbuf_len, pcli->in))
return 0;
char *nl = strchr(pcli->inbuf, '\n');
if (!nl)
return 1;
*nl = '\0';
char *hash = strchr(pcli->inbuf, '#');
if (hash) {
if (pcli->opts.enable_comments)
*hash = '\0';
else
return 1;
}
if (pcli->inbuf[0] == 0 || pcli->inbuf[0] == '\n') {
if (pcli->opts.enable_empty_cmds)
continue;
else
return 1;
}
if (pcli->opts.echo_mode)
pocli_printf(&pcli->ctx, "%s\n", pcli->inbuf);
char *argstr = strchr(pcli->inbuf, ' ');
if (argstr) {
*argstr = '\0';
argstr++;
}
char *cmds = pcli->inbuf;
const struct pocli_cmd *cmd;
if (pcli->print_only)
cmd = &print_cmd;
else
cmd = pocli_get_cmd(pcli, cmds);
if (!cmd) {
pocli_err(&pcli->ctx, POCLI_RET_OK, /* XXX */
"unknown command -- '%s'\n", cmds);
if (pcli->opts.exit_on_error)
return 1;
else
continue;
}
if (!argstr)
argstr = cmds + strlen(pcli->inbuf) + 1;
struct pocli_args *args = pocli_args_alloc(pcli->inbuf,
argstr, POCLI_CMD_DELIM);
if (!args)
return 1;
/*
* Put the args object on the stack, just in case we are
* in transaction, cmd->func will abort it and skip free(args).
*/
VEC_PUSH_BACK(&pcli->ctx.free_on_abort, args);
enum pocli_ret ret = cmd->func(&pcli->ctx, args);
free(args);
/* Take args off the stack. */
VEC_POP_BACK(&pcli->ctx.free_on_abort);
if (ret != POCLI_RET_OK)
return (int)ret;
}
}
/*
* pocli_do_process -- process input commands and return value
*/
static int
pocli_do_process(struct pocli *pcli)
{
enum pocli_ret ret = (enum pocli_ret)pocli_process(pcli);
if (ret == POCLI_RET_QUIT || ret == POCLI_RET_OK)
return 0;
else
return 1;
}
/*
* print_usage -- print usage of program
*/
static void
print_usage(const char *name)
{
printf("Usage: %s [-s <script>] -p|<file>\n", name);
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
fprintf(stderr, "Error during arguments conversion\n");
return 1;
}
}
#endif
int opt;
int ret = 1;
const char *fname = NULL;
FILE *input = stdin;
bool print_only = false;
while ((opt = getopt(argc, argv, "s:p")) != -1) {
switch (opt) {
case 's':
input = os_fopen(optarg, "r");
if (!input) {
perror(optarg);
goto out;
}
break;
case 'p':
print_only = true;
break;
default:
print_usage(argv[0]);
ret = 1;
goto out;
}
}
if (optind < argc) {
fname = argv[optind];
} else if (!print_only) {
print_usage(argv[0]);
goto out;
}
struct pocli *pcli = pocli_alloc(input, fname, pocli_commands,
POCLI_NCOMMANDS, POCLI_INBUF_LEN, print_only);
if (!pcli) {
perror("pocli_alloc");
goto out;
}
ret = pocli_do_process(pcli);
pocli_free(pcli);
fclose(input);
out:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 52,057 | 20.717981 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/ddmap/ddmap.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* ddmap.c -- simple app for reading and writing data from/to a regular file or
* dax device using mmap instead of file io API
*/
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include "common.h"
#include "output.h"
#include "mmap.h"
#include "file.h"
#include "util.h"
#include "os.h"
/*
* ddmap_context -- context and arguments
*/
struct ddmap_context {
char *file_in; /* input file name */
char *file_out; /* output file name */
char *str; /* string data to write */
size_t offset_in; /* offset from beginning of input file for */
/* read/write operations expressed in blocks */
size_t offset_out; /* offset from beginning of output file for */
/* read/write operations expressed in blocks */
size_t bytes; /* size of blocks to write at the time */
size_t count; /* number of blocks to read/write */
int checksum; /* compute checksum */
int runlen; /* print bytes as runlen/char sequence */
};
/*
* the default context, with all fields initialized to zero or NULL
*/
static struct ddmap_context ddmap_default;
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
printf("Usage: ddmap [option] ...\n");
printf("Valid options:\n");
printf("-i FILE - read from FILE\n");
printf("-o FILE - write to FILE\n");
printf("-d STRING - STRING to be written\n");
printf("-s N - skip N blocks at start of input\n");
printf("-q N - skip N blocks at start of output\n");
printf("-b N - read/write N bytes at a time\n");
printf("-n N - copy N input blocks\n");
printf("-c - compute checksum\n");
printf("-r - print file content as runlen/char pairs\n");
printf("-h - print this usage info\n");
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"input-file", required_argument, NULL, 'i'},
{"output-file", required_argument, NULL, 'o'},
{"string", required_argument, NULL, 'd'},
{"offset-in", required_argument, NULL, 's'},
{"offset-out", required_argument, NULL, 'q'},
{"block-size", required_argument, NULL, 'b'},
{"count", required_argument, NULL, 'n'},
{"checksum", no_argument, NULL, 'c'},
{"runlen", no_argument, NULL, 'r'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* ddmap_print_char -- (internal) print single char
*
* Printable ASCII characters are printed normally,
* NUL character is printed as a little circle (the degree symbol),
* non-printable ASCII characters are printed as centered dots.
*/
static void
ddmap_print_char(char c)
{
if (c == '\0')
/* print the degree symbol for NUL */
printf("\u00B0");
else if (c >= ' ' && c <= '~')
/* print printable ASCII character */
printf("%c", c);
else
/* print centered dot for non-printable character */
printf("\u00B7");
}
/*
* ddmap_print_runlen -- (internal) print file content as length/char pairs
*
* For each sequence of chars of the same value (could be just 1 byte)
* print length of the sequence and the char value.
*/
static void
ddmap_print_runlen(char *addr, size_t len)
{
char c = '\0';
ssize_t cnt = 0;
for (size_t i = 0; i < len; i++) {
if (i > 0 && c != addr[i] && cnt != 0) {
printf("%zd ", cnt);
ddmap_print_char(c);
printf("\n");
cnt = 0;
}
c = addr[i];
cnt++;
}
if (cnt) {
printf("%zd ", cnt);
ddmap_print_char(c);
printf("\n");
}
}
/*
* ddmap_print_bytes -- (internal) print array of bytes
*/
static void
ddmap_print_bytes(const char *data, size_t len)
{
for (size_t i = 0; i < len; ++i) {
ddmap_print_char(data[i]);
}
printf("\n");
}
/*
* ddmap_read -- (internal) read a string from the file at the offset and
* print it to stdout
*/
static int
ddmap_read(const char *path, size_t offset_in, size_t bytes, size_t count,
int runlen)
{
size_t len = bytes * count;
os_off_t offset = (os_off_t)(bytes * offset_in);
char *read_buff = Zalloc(len + 1);
if (read_buff == NULL) {
outv_err("Zalloc(%zu) failed\n", len + 1);
return -1;
}
ssize_t read_len = util_file_pread(path, read_buff, len, offset);
if (read_len < 0) {
outv_err("pread failed");
Free(read_buff);
return -1;
} else if ((size_t)read_len < len) {
outv(1, "read less bytes than requested: %zd vs. %zu\n",
read_len, len);
}
if (runlen)
ddmap_print_runlen(read_buff, (size_t)read_len);
else
ddmap_print_bytes(read_buff, (size_t)read_len);
Free(read_buff);
return 0;
}
/*
* ddmap_zero -- (internal) zero a range of data in the file
*/
static int
ddmap_zero(const char *path, size_t offset, size_t len)
{
void *addr;
ssize_t filesize = util_file_get_size(path);
if (filesize < 0) {
outv_err("invalid file size");
return -1;
}
if (offset + len > (size_t)filesize)
len = (size_t)filesize - offset;
addr = util_file_map_whole(path);
if (addr == NULL) {
outv_err("map failed");
return -1;
}
memset((char *)addr + offset, 0, len);
util_unmap(addr, (size_t)filesize);
return 0;
}
/*
* ddmap_write_data -- (internal) write data to a file
*/
static int
ddmap_write_data(const char *path, const char *data,
os_off_t offset, size_t len)
{
if (util_file_pwrite(path, data, len, offset) < 0) {
outv_err("pwrite for dax device failed: path %s,"
" len %zu, offset %zd", path, len, offset);
return -1;
}
return 0;
}
/*
* ddmap_write_from_file -- (internal) write data from file to dax device or
* file
*/
static int
ddmap_write_from_file(const char *path_in, const char *path_out,
size_t offset_in, size_t offset_out, size_t bytes,
size_t count)
{
char *src, *tmp_src;
os_off_t offset;
ssize_t file_in_size = util_file_get_size(path_in);
size_t data_left, len;
util_init();
src = util_file_map_whole(path_in);
src += (os_off_t)(offset_in * bytes);
offset = (os_off_t)(offset_out * bytes);
data_left = (size_t)file_in_size;
tmp_src = src;
do {
len = MIN(data_left, bytes);
ddmap_write_data(path_out, tmp_src, offset, len);
tmp_src += len;
data_left -= len;
if (data_left == 0) {
data_left = (size_t)file_in_size;
tmp_src = src;
}
offset += (os_off_t)len;
count--;
} while (count > 0);
util_unmap(src, (size_t)file_in_size);
return 0;
}
/*
* ddmap_write -- (internal) write the string to the file
*/
static int
ddmap_write(const char *path, const char *str, size_t offset_in, size_t bytes,
size_t count)
{
/* calculate how many characters from the string are to be written */
size_t length;
size_t str_len = (str != NULL) ? strlen(str) + 1 : 0;
os_off_t offset = (os_off_t)(bytes * offset_in);
size_t len = bytes * count;
if (len == 0)
length = str_len;
else
length = min(len, str_len);
/* write the string */
if (length > 0) {
if (ddmap_write_data(path, str, offset, length))
return -1;
}
/* zero the rest of requested range */
if (length < len) {
if (ddmap_zero(path, (size_t)offset + length, len - length))
return -1;
}
return 0;
}
/*
* ddmap_checksum -- (internal) compute checksum of a slice of an input file
*/
static int
ddmap_checksum(const char *path, size_t bytes, size_t count, size_t offset_in)
{
char *src;
uint64_t checksum;
ssize_t filesize = util_file_get_size(path);
os_off_t offset = (os_off_t)(bytes * offset_in);
size_t len = bytes * count;
if ((size_t)filesize < len + (size_t)offset) {
outv_err("offset with length exceed file size");
return -1;
}
util_init();
src = util_file_map_whole(path);
util_checksum(src + offset, len, &checksum, 1, 0);
util_unmap(src, (size_t)filesize);
printf("%" PRIu64 "\n", checksum);
return 0;
}
/*
* parse_args -- (internal) parse command line arguments
*/
static int
parse_args(struct ddmap_context *ctx, int argc, char *argv[])
{
int opt;
char *endptr;
size_t offset;
size_t count;
size_t bytes;
while ((opt = getopt_long(argc, argv, "i:o:d:s:q:b:n:crhv",
long_options, NULL)) != -1) {
switch (opt) {
case 'i':
ctx->file_in = optarg;
break;
case 'o':
ctx->file_out = optarg;
break;
case 'd':
ctx->str = optarg;
if (ctx->count == 0)
ctx->count = strlen(ctx->str);
if (ctx->bytes == 0)
ctx->bytes = 1;
break;
case 's':
errno = 0;
offset = strtoul(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno) {
outv_err("'%s' -- invalid input offset",
optarg);
return -1;
}
ctx->offset_in = offset;
break;
case 'q':
errno = 0;
offset = strtoul(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno) {
outv_err("'%s' -- invalid output offset",
optarg);
return -1;
}
ctx->offset_out = offset;
break;
case 'b':
errno = 0;
bytes = strtoull(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno) {
outv_err("'%s' -- invalid block size", optarg);
return -1;
}
ctx->bytes = bytes;
break;
case 'n':
errno = 0;
count = strtoull(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno) {
outv_err("'%s' -- invalid count", optarg);
return -1;
}
ctx->count = count;
break;
case 'c':
ctx->checksum = 1;
break;
case 'r':
ctx->runlen = 1;
break;
case 'h':
print_usage();
exit(EXIT_SUCCESS);
case 'v':
out_set_vlevel(1);
break;
default:
print_usage();
exit(EXIT_FAILURE);
}
}
return 0;
}
/*
* validate_args -- (internal) validate arguments
*/
static int
validate_args(struct ddmap_context *ctx)
{
if ((ctx->file_in == NULL) && (ctx->file_out == NULL)) {
outv_err("an input file and/or an output file must be "
"provided");
return -1;
} else if (ctx->file_out == NULL) {
if (ctx->bytes == 0) {
outv_err("number of bytes to read has to be provided");
return -1;
}
} else if (ctx->file_in == NULL) {
/* ddmap_write requirements */
if (ctx->str == NULL && (ctx->count * ctx->bytes) == 0) {
outv_err("when writing, 'data' or 'count' and 'bytes' "
"have to be provided");
return -1;
}
} else {
/* scenarios other than ddmap_write requirement */
if ((ctx->bytes * ctx->count) == 0) {
outv_err("number of bytes and count must be provided");
return -1;
}
}
return 0;
}
/*
* do_ddmap -- (internal) perform ddmap
*/
static int
do_ddmap(struct ddmap_context *ctx)
{
if ((ctx->file_in != NULL) && (ctx->file_out != NULL)) {
if (ddmap_write_from_file(ctx->file_in, ctx->file_out,
ctx->offset_in, ctx->offset_out, ctx->bytes,
ctx->count))
return -1;
return 0;
}
if ((ctx->checksum == 1) && (ctx->file_in != NULL)) {
if (ddmap_checksum(ctx->file_in, ctx->bytes, ctx->count,
ctx->offset_in))
return -1;
return 0;
}
if (ctx->file_in != NULL) {
if (ddmap_read(ctx->file_in, ctx->offset_in, ctx->bytes,
ctx->count, ctx->runlen))
return -1;
} else { /* ctx->file_out != NULL */
if (ddmap_write(ctx->file_out, ctx->str, ctx->offset_in,
ctx->bytes, ctx->count))
return -1;
}
return 0;
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
outv_err("Error during arguments conversion\n");
return 1;
}
}
#endif
int ret = 0;
struct ddmap_context ctx = ddmap_default;
if ((ret = parse_args(&ctx, argc, argv)))
goto out;
if ((ret = validate_args(&ctx)))
goto out;
if ((ret = do_ddmap(&ctx))) {
outv_err("failed to perform ddmap\n");
if (errno)
outv_err("errno: %s\n", strerror(errno));
ret = -1;
goto out;
}
out:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 11,872 | 22.280392 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/bttcreate/bttcreate.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* bttcreate.c -- tool for generating BTT layout
*/
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include "set.h"
#include "pool_hdr.h"
#include "btt.h"
#include "btt_layout.h"
#include "pmemcommon.h"
#include "os.h"
#include "util.h"
#include "page_size.h"
#define BTT_CREATE_DEF_SIZE (20 * 1UL << 20) /* 20 MB */
#define BTT_CREATE_DEF_BLK_SIZE 512UL
#define BTT_CREATE_DEF_OFFSET_SIZE PMEM_PAGESIZE
struct btt_context {
void *addr;
uint64_t len;
};
struct bbtcreate_options {
const char *fpath;
size_t poolsize;
uint32_t blocksize;
unsigned maxlanes;
uuid_t uuid;
bool trunc;
bool verbose;
bool user_uuid;
};
/*
* nsread -- btt callback for reading
*/
static int
nsread(void *ns, unsigned lane, void *buf, size_t count,
uint64_t off)
{
struct btt_context *nsc = (struct btt_context *)ns;
if (off + count > nsc->len) {
errno = EINVAL;
return -1;
}
memcpy(buf, (char *)nsc->addr + off, count);
return 0;
}
/*
* nswrite -- btt callback for writing
*/
static int
nswrite(void *ns, unsigned lane, const void *buf,
size_t count, uint64_t off)
{
struct btt_context *nsc = (struct btt_context *)ns;
if (off + count > nsc->len) {
errno = EINVAL;
return -1;
}
memcpy((char *)nsc->addr + off, buf, count);
return 0;
}
/*
* nsmap -- btt callback for memory mapping
*/
static ssize_t
nsmap(void *ns, unsigned lane, void **addrp, size_t len,
uint64_t off)
{
struct btt_context *nsc = (struct btt_context *)ns;
assert((ssize_t)len >= 0);
if (off + len >= nsc->len) {
errno = EINVAL;
return -1;
}
/*
* Since the entire file is memory-mapped, this callback
* can always provide the entire length requested.
*/
*addrp = (char *)nsc->addr + off;
return (ssize_t)len;
}
/*
* nssync -- btt callback for memory synchronization
*/
static void
nssync(void *ns, unsigned lane, void *addr, size_t len)
{
/* do nothing */
}
/*
* nszero -- btt callback for zeroing memory
*/
static int
nszero(void *ns, unsigned lane, size_t len, uint64_t off)
{
struct btt_context *nsc = (struct btt_context *)ns;
if (off + len >= nsc->len) {
errno = EINVAL;
return -1;
}
memset((char *)nsc->addr + off, 0, len);
return 0;
}
/*
* print_usage -- print usage of program
*/
static void
print_usage(char *name)
{
printf("Usage: %s [-s <pool_file_size>] [-b <block_size>] "
"[-l <max_lanes>] [-u <uuid>] [-t] [-v] "
"<pool_name>\n", name);
}
/*
* file_error -- handle file errors
*/
static int
file_error(const int fd, const char *fpath)
{
if (fd != -1)
(void) os_close(fd);
os_unlink(fpath);
return -1;
}
/*
* print_uuid -- print uuid
*/
static void
print_uuid(uuid_t uuid)
{
char uuidstr[POOL_HDR_UUID_STR_LEN];
if (util_uuid_to_string(uuid, uuidstr) == 0) {
printf("uuid\t\t%s\n", uuidstr);
}
}
/*
* print_result -- print result if verbose option is on
*/
static void
print_result(struct bbtcreate_options *opts)
{
if (opts->verbose) {
printf("BTT successfully created: %s\n", opts->fpath);
printf("poolsize\t%zuB\n", opts->poolsize);
printf("blocksize\t%uB\n", opts->blocksize);
printf("maxlanes\t%u\n", opts->maxlanes);
print_uuid(opts->uuid);
putchar('\n');
}
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
fprintf(stderr, "Error during arguments conversion\n");
return 1;
}
}
#endif
common_init("", "", "", 0, 0);
int opt;
size_t size;
int fd;
int res = 0;
struct bbtcreate_options opts = {
.poolsize = BTT_CREATE_DEF_SIZE,
.blocksize = BTT_CREATE_DEF_BLK_SIZE,
.maxlanes = BTT_DEFAULT_NFREE,
.trunc = false,
.verbose = false,
.user_uuid = false
};
/* parse option */
while ((opt = getopt(argc, argv, "s:b:l:u:tv")) != -1) {
switch (opt) {
case 's':
if (util_parse_size(optarg, &size) == 0) {
opts.poolsize = size;
} else {
fprintf(stderr, "Wrong size format in pool"
" size option\n");
res = 1;
goto out;
}
break;
case 'b':
if (util_parse_size(optarg, &size) == 0) {
opts.blocksize = (uint32_t)size;
} else {
fprintf(stderr, "Wrong size format in block"
" size option\n");
res = 1;
goto out;
}
break;
case 'l':
opts.maxlanes = (unsigned)strtoul(optarg, NULL, 0);
break;
case 'u':
if (util_uuid_from_string(optarg,
(struct uuid *)&opts.uuid) == 0) {
opts.user_uuid = true;
} else {
fprintf(stderr, "Wrong uuid format.");
res = 1;
goto out;
}
break;
case 't':
opts.trunc = true;
break;
case 'v':
opts.verbose = true;
break;
default:
print_usage(argv[0]);
res = 1;
goto out;
}
}
if (optind < argc) {
opts.fpath = argv[optind];
} else {
print_usage(argv[0]);
res = 1;
goto out;
}
/* check sizes */
if (opts.poolsize - BTT_CREATE_DEF_OFFSET_SIZE < BTT_MIN_SIZE) {
fprintf(stderr, "Pool size is less then %d MB\n",
BTT_MIN_SIZE >> 20);
res = 1;
goto out;
}
if (opts.blocksize < BTT_MIN_LBA_SIZE) {
fprintf(stderr, "Block size is less then %zu B\n",
BTT_MIN_LBA_SIZE);
res = 1;
goto out;
}
/* open file */
if ((fd = os_open(opts.fpath, O_RDWR|O_CREAT,
S_IRUSR|S_IWUSR)) < 0) {
perror(opts.fpath);
res = 1;
goto out;
}
/* allocate file */
if (!opts.trunc) {
if (os_posix_fallocate(fd, 0,
(os_off_t)opts.poolsize) != 0) {
perror("posix_fallocate");
res = file_error(fd, opts.fpath);
goto error;
}
} else {
if (os_ftruncate(fd, (os_off_t)opts.poolsize) != 0) {
perror("ftruncate");
res = file_error(fd, opts.fpath);
goto error;
}
}
/* map created file */
void *base = util_map(fd, 0, opts.poolsize, MAP_SHARED, 0, 0, NULL);
if (!base) {
perror("util_map");
res = file_error(fd, opts.fpath);
goto error_map;
}
/* setup btt context */
struct btt_context btt_context = {
.addr = (void *)((uint64_t)base + BTT_CREATE_DEF_OFFSET_SIZE),
.len = opts.poolsize - BTT_CREATE_DEF_OFFSET_SIZE
};
/* generate uuid */
if (!opts.user_uuid) {
if (util_uuid_generate(opts.uuid) < 0) {
perror("util_uuid_generate");
res = -1;
goto error_map;
}
}
/* init callback structure */
static struct ns_callback btt_ns_callback = {
.nsread = nsread,
.nswrite = nswrite,
.nsmap = nsmap,
.nssync = nssync,
.nszero = nszero,
};
/* init btt in requested area */
struct btt *bttp = btt_init(opts.poolsize - BTT_CREATE_DEF_OFFSET_SIZE,
opts.blocksize, opts.uuid, opts.maxlanes,
(void *)&btt_context,
&btt_ns_callback);
if (!bttp) {
printf("Error: Cannot initialize BTT layer\n");
res = -1;
goto error_map;
}
/* initialize metadata */
if (btt_set_error(bttp, 0, 0)) {
perror("btt_set_error");
res = -1;
goto error_btt;
}
if (btt_set_zero(bttp, 0, 0)) {
perror("btt_set_zero");
res = -1;
goto error_btt;
}
/* print results */
print_result(&opts);
error_btt:
btt_fini(bttp);
if (util_unmap(base, opts.poolsize) < 0) {
perror("!util_unmap");
res = -1;
}
error_map:
common_fini();
error:
os_close(fd);
out:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return res;
}
| 7,494 | 18.671916 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/dllview/dllview.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* dllview.c -- a simple utility displaying the list of symbols exported by DLL
*
* usage: dllview filename
*/
#include <windows.h>
#include <stdio.h>
#include <winnt.h>
#include <imagehlp.h>
#include "util.h"
int
main(int argc, char *argv[])
{
util_suppress_errmsg();
if (argc < 2) {
fprintf(stderr, "usage: %s dllname\n", argv[0]);
exit(1);
}
const char *dllname = argv[1];
LOADED_IMAGE img;
if (MapAndLoad(dllname, NULL, &img, 1, 1) == FALSE) {
fprintf(stderr, "cannot load DLL image\n");
exit(2);
}
IMAGE_EXPORT_DIRECTORY *dir;
ULONG dirsize;
dir = (IMAGE_EXPORT_DIRECTORY *)ImageDirectoryEntryToData(
img.MappedAddress, 0 /* mapped as image */,
IMAGE_DIRECTORY_ENTRY_EXPORT, &dirsize);
if (dir == NULL) {
fprintf(stderr, "cannot read image directory\n");
UnMapAndLoad(&img);
exit(3);
}
DWORD *rva;
rva = (DWORD *)ImageRvaToVa(img.FileHeader, img.MappedAddress,
dir->AddressOfNames, NULL);
for (DWORD i = 0; i < dir->NumberOfNames; i++) {
char *name = (char *)ImageRvaToVa(img.FileHeader,
img.MappedAddress, rva[i], NULL);
printf("%s\n", name);
}
UnMapAndLoad(&img);
return 0;
}
| 1,233 | 20.649123 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/usc_permission_check/usc_permission_check.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* usc_permission_check.c -- checks whether it's possible to read usc
* with current permissions
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <libpmem2.h>
#include "os.h"
/*
* This program returns:
* - 0 when usc can be read with current permissions
* - 1 when permissions are not sufficient or when usc is not supported
* - 2 when other error occurs
*/
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return 2;
}
uint64_t usc;
int fd = os_open(argv[0], O_RDONLY);
if (fd < 0) {
perror("open");
return 2;
}
struct pmem2_source *src;
if (pmem2_source_from_fd(&src, fd)) {
pmem2_perror("pmem2_source_from_fd");
return 2;
}
int ret = pmem2_source_device_usc(src, &usc);
if (ret == 0)
return 0;
else if (ret == -EACCES || ret == PMEM2_E_NOSUPP)
return 1;
else
return 2;
}
| 1,033 | 18.148148 | 71 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/gran_detecto/gran_detecto.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* gran_detecto.c -- detect available store/flush granularity
*/
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "libpmem2.h"
#include "file.h"
#include "os.h"
#include "util.h"
#define KILOBYTE (1 << 10)
#define NOT_SET_FD (-1)
enum gran_detecto_mode {
NOT_SET,
VALIDATE,
DETECT,
};
/*
* tool_ctx -- essential parameters used by gran_detecto
*/
struct tool_ctx
{
enum pmem2_granularity actual_granularity;
char *probe_file_path;
int fd;
enum gran_detecto_mode state;
/* user arguments */
enum pmem2_granularity expected_granularity;
char *path;
};
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
printf("Usage: gran_detecto -h\n"
" gran_detecto <-b|-c|-d|-p> <path>\n"
"Available options:\n"
"-b, --byte - check if <path> has byte granularity\n"
"-c, --cache-line - check if <path> has cache line granularity\n"
"-d, --detect - detect the smallest available granularity for <path>\n"
"-p, --page - check if <path> has page granularity\n"
"-h, --help - print this usage info\n");
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"byte", no_argument, NULL, 'b'},
{"cache-line", no_argument, NULL, 'c'},
{"detect", no_argument, NULL, 'd'},
{"page", no_argument, NULL, 'p'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0},
};
/*
* parse_args -- parse command line arguments
*/
static int
parse_args(int argc, char *argv[], struct tool_ctx *ctx)
{
/* tool context initialization */
ctx->expected_granularity = PMEM2_GRANULARITY_PAGE;
ctx->actual_granularity = PMEM2_GRANULARITY_PAGE;
ctx->fd = NOT_SET_FD;
ctx->state = NOT_SET;
ctx->probe_file_path = NULL;
ctx->path = NULL;
int opt;
while ((opt = getopt_long(argc, argv, "bcdhp", long_options, NULL)) !=
-1) {
switch (opt) {
case 'b':
ctx->state = VALIDATE;
ctx->expected_granularity =
PMEM2_GRANULARITY_BYTE;
break;
case 'c':
ctx->state = VALIDATE;
ctx->expected_granularity =
PMEM2_GRANULARITY_CACHE_LINE;
break;
case 'd':
ctx->state = DETECT;
break;
case 'p':
ctx->state = VALIDATE;
ctx->expected_granularity =
PMEM2_GRANULARITY_PAGE;
break;
case 'h':
print_usage();
exit(0);
default:
print_usage();
return 1;
}
}
if (ctx->state == NOT_SET) {
print_usage();
return 1;
}
if (optind < argc) {
ctx->path = argv[optind];
} else {
fprintf(stderr, "gran_detecto: path cannot be empty.\n");
print_usage();
return 1;
}
return 0;
}
/*
* cleanup_file -- close the file descriptor and remove the file and free file
* name variable if applicable
*/
#ifdef __linux__
static void
cleanup_file(struct tool_ctx *ctx)
{
assert(ctx->fd != NOT_SET_FD);
os_close(ctx->fd);
ctx->fd = NOT_SET_FD;
}
#else
static void
cleanup_file(struct tool_ctx *ctx)
{
if (ctx->fd != NOT_SET_FD) {
os_close(ctx->fd);
ctx->fd = NOT_SET_FD;
os_unlink(ctx->probe_file_path);
}
free(ctx->probe_file_path);
}
#endif
/*
* prepare_file -- create, prepare a file
*/
#ifdef __linux__
static void
prepare_file(struct tool_ctx *ctx)
{
ctx->fd = os_open(ctx->path, O_TMPFILE | O_RDWR, 0640);
if (ctx->fd < 0) {
perror("os_open");
return;
}
int ret = os_ftruncate(ctx->fd, 16 * KILOBYTE);
if (ret) {
perror("os_ftruncate");
goto cleanup_file;
}
return;
cleanup_file:
cleanup_file(ctx);
}
#else
static void
prepare_file(struct tool_ctx *ctx)
{
ctx->probe_file_path = malloc(PATH_MAX * sizeof(char));
if (!ctx->probe_file_path) {
perror("malloc");
return;
}
int ret = snprintf(ctx->probe_file_path, PATH_MAX,
"%s" OS_DIR_SEP_STR "temp_grandetecto", ctx->path);
if (ret < 0) {
perror("snprintf");
goto cleanup_file;
} else if (ret >= PATH_MAX) {
fprintf(stderr,
"snprintf: number of characters exceeds PATH_MAX.\n");
goto cleanup_file;
}
ctx->fd = os_open(ctx->probe_file_path, O_CREAT | O_RDWR, 0640);
if (ctx->fd < 0) {
perror("os_open");
ctx->fd = NOT_SET_FD;
goto cleanup_file;
}
const char *message =
"This file was created by gran_detecto. It can be safely removed.";
ssize_t sret = util_write(ctx->fd, message, strlen(message));
if (sret == -1) {
perror("util_write");
goto cleanup_file;
}
return;
cleanup_file:
cleanup_file(ctx);
}
#endif
/*
* gran_detecto -- try to map file and get the smallest available granularity
*/
static int
gran_detecto(struct tool_ctx *ctx)
{
int ret = 0;
prepare_file(ctx);
if (ctx->fd == NOT_SET_FD)
return 1;
/* fill config in minimal scope */
struct pmem2_config *cfg;
if (pmem2_config_new(&cfg)) {
pmem2_perror("pmem2_config_new");
ret = 1;
goto cleanup_file;
}
struct pmem2_source *src;
if (pmem2_source_from_fd(&src, ctx->fd)) {
pmem2_perror("pmem2_source_from_fd");
ret = 1;
goto free_config;
}
if (pmem2_config_set_required_store_granularity(cfg,
PMEM2_GRANULARITY_PAGE)) {
pmem2_perror("pmem2_config_set_required_store_granularity");
ret = 1;
goto free_both;
}
struct pmem2_map *map;
if (pmem2_map(cfg, src, &map)) {
pmem2_perror("pmem2_map");
ret = 1;
goto free_both;
}
ctx->actual_granularity = pmem2_map_get_store_granularity(map);
if (pmem2_unmap(&map)) {
pmem2_perror("pmem2_unmap");
ret = 1;
}
free_both:
pmem2_source_delete(&src);
free_config:
pmem2_config_delete(&cfg);
cleanup_file:
cleanup_file(ctx);
return ret;
}
static const char *PMEM2_GRANULARITIES[] = {
"byte",
"cache line",
"page"};
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
fprintf(stderr,
"gran_detecto: error during arguments conversion\n");
return 1;
}
}
#endif
struct tool_ctx ctx;
int ret = 0;
if (parse_args(argc, argv, &ctx)) {
ret = 1;
goto out;
}
if (gran_detecto(&ctx)) {
ret = 1;
goto out;
}
if (ctx.state == DETECT) {
printf(
"gran_detecto: the smallest available granularity for %s is %s\n",
ctx.path,
PMEM2_GRANULARITIES[ctx.actual_granularity]);
goto out;
}
ret = ctx.expected_granularity == ctx.actual_granularity ? 0 : 1;
out:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 6,690 | 18.679412 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/pmemalloc/pmemalloc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* pmemmalloc.c -- simple tool for allocating objects from pmemobj
*
* usage: pmemalloc [-r <size>] [-o <size>] [-t <type_num>]
* [-c <count>] [-e <num>] <file>
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "libpmemobj.h"
#include "util.h"
#define USAGE()\
printf("usage: pmemalloc"\
" [-r <size>] [-o <size>] [-t <type_num>]"\
" [-s] [-f] [-e a|f|s] <file>\n")
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
fprintf(stderr, "Error during arguments conversion\n");
return 1;
}
}
#endif
int opt;
int tmpi;
long long tmpl;
int ret = 0;
size_t size = 0;
size_t root_size = 0;
unsigned type_num = 0;
char exit_at = '\0';
int do_set = 0;
int do_free = 0;
size_t alloc_class_size = 0;
if (argc < 2) {
USAGE();
ret = 1;
goto end;
}
while ((opt = getopt(argc, argv, "r:o:c:t:e:sf")) != -1) {
switch (opt) {
case 'r':
tmpl = atoll(optarg);
if (tmpl < 0) {
USAGE();
ret = 1;
goto end;
}
root_size = (size_t)tmpl;
break;
case 'o':
tmpl = atoll(optarg);
if (tmpl < 0) {
USAGE();
ret = 1;
goto end;
}
size = (size_t)tmpl;
break;
case 'c':
tmpl = atoll(optarg);
if (tmpl < 0) {
USAGE();
ret = 1;
goto end;
}
alloc_class_size = (size_t)tmpl;
break;
case 't':
tmpi = atoi(optarg);
if (tmpi < 0) {
USAGE();
ret = 1;
goto end;
}
type_num = (unsigned)tmpi;
break;
case 'e':
exit_at = optarg[0];
break;
case 's':
do_set = 1;
break;
case 'f':
do_free = 1;
break;
default:
USAGE();
ret = 1;
goto end;
}
}
char *file = argv[optind];
PMEMobjpool *pop;
if ((pop = pmemobj_open(file, NULL)) == NULL) {
fprintf(stderr, "pmemobj_open: %s\n", pmemobj_errormsg());
ret = 1;
goto end;
}
if (root_size) {
PMEMoid oid = pmemobj_root(pop, root_size);
if (OID_IS_NULL(oid)) {
fprintf(stderr, "pmemobj_root: %s\n",
pmemobj_errormsg());
ret = 1;
goto end;
}
}
if (alloc_class_size) {
PMEMoid oid;
struct pobj_alloc_class_desc desc;
desc.alignment = 0;
desc.class_id = 0;
desc.header_type = POBJ_HEADER_COMPACT;
desc.unit_size = alloc_class_size;
desc.units_per_block = 1;
ret = pmemobj_ctl_set(pop, "heap.alloc_class.new.desc", &desc);
if (ret != 0)
goto end;
ret = pmemobj_xalloc(pop, &oid, 1, type_num,
POBJ_CLASS_ID(desc.class_id), NULL, NULL);
if (ret != 0)
goto end;
}
if (size) {
PMEMoid oid;
TX_BEGIN(pop) {
oid = pmemobj_tx_alloc(size, type_num);
if (exit_at == 'a')
exit(1);
} TX_END
if (OID_IS_NULL(oid)) {
fprintf(stderr, "pmemobj_tx_alloc: %s\n",
pmemobj_errormsg());
ret = 1;
goto end;
}
if (do_set) {
TX_BEGIN(pop) {
pmemobj_tx_add_range(oid, 0, size);
if (exit_at == 's')
exit(1);
} TX_END
}
if (do_free) {
TX_BEGIN(pop) {
pmemobj_tx_free(oid);
if (exit_at == 'f')
exit(1);
} TX_END
}
}
pmemobj_close(pop);
end:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 3,381 | 17.085561 | 66 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/anonymous_mmap/anonymous_mmap.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018, Intel Corporation */
/*
* anonymous_mmap.c -- tool for verifying if given memory length can be
* anonymously mmapped
*/
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
#include "out.h"
int
main(int argc, char *argv[])
{
out_init("ANONYMOUS_MMAP", "ANONYMOUS_MMAP", "", 1, 0);
if (argc != 2) {
out("Usage: %s <length>", argv[0]);
return -1;
}
const size_t length = (size_t)atoll(argv[1]);
char *addr = mmap(NULL, length, PROT_READ,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
out("anonymous_mmap.c: Failed to mmap length=%lu of memory, "
"errno=%d", length, errno);
return errno;
}
out_fini();
return 0;
}
| 732 | 18.289474 | 71 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/anonymous_mmap/check_max_mmap.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018, Intel Corporation
#
# src/test/tools/anonymous_mmap/check_max_mmap.sh -- checks how many DAX
# devices can be mapped under Valgrind and saves the number in
# src/test/tools/anonymous_mmap/max_dax_devices.
#
DIR_CHECK_MAX_MMAP="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
FILE_MAX_DAX_DEVICES="$DIR_CHECK_MAX_MMAP/max_dax_devices"
ANONYMOUS_MMAP="$DIR_CHECK_MAX_MMAP/anonymous_mmap.static-nondebug"
source "$DIR_CHECK_MAX_MMAP/../../testconfig.sh"
#
# get_devdax_size -- get the size of a device dax
#
function get_devdax_size() {
local device=$1
local path=${DEVICE_DAX_PATH[$device]}
local major_hex=$(stat -c "%t" $path)
local minor_hex=$(stat -c "%T" $path)
local major_dec=$((16#$major_hex))
local minor_dec=$((16#$minor_hex))
cat /sys/dev/char/$major_dec:$minor_dec/size
}
function msg_skip() {
echo "0" > "$FILE_MAX_DAX_DEVICES"
echo "$0: SKIP: $*"
exit 0
}
function msg_failed() {
echo "$0: FATAL: $*" >&2
exit 1
}
# check if DEVICE_DAX_PATH specifies at least one DAX device
if [ ${#DEVICE_DAX_PATH[@]} -lt 1 ]; then
msg_skip "DEVICE_DAX_PATH does not specify path to DAX device."
fi
# check if valgrind package is installed
VALGRINDEXE=`which valgrind 2>/dev/null`
ret=$?
if [ $ret -ne 0 ]; then
msg_skip "Valgrind required."
fi
# check if memcheck tool is installed
$VALGRINDEXE --tool=memcheck --help 2>&1 | grep -qi "memcheck is Copyright (c)" && true
if [ $? -ne 0 ]; then
msg_skip "Valgrind with memcheck required."
fi
# check if anonymous_mmap tool is built
if [ ! -f "${ANONYMOUS_MMAP}" ]; then
msg_failed "${ANONYMOUS_MMAP} does not exist"
fi
# checks how many DAX devices can be mmapped under Valgrind and save the number
# in $FILE_MAX_DAX_DEVICES file
bytes="0"
max_devices="0"
for index in ${!DEVICE_DAX_PATH[@]}
do
if [ ! -e "${DEVICE_DAX_PATH[$index]}" ]; then
msg_failed "${DEVICE_DAX_PATH[$index]} does not exist"
fi
curr=$(get_devdax_size $index)
if [[ curr -eq 0 ]]; then
msg_failed "size of DAX device pointed by DEVICE_DAX_PATH[$index] equals 0."
fi
$VALGRINDEXE --tool=memcheck --quiet $ANONYMOUS_MMAP $((bytes + curr))
status=$?
if [[ status -ne 0 ]]; then
break
fi
bytes=$((bytes + curr))
max_devices=$((max_devices + 1))
done
echo "$max_devices" > "$FILE_MAX_DAX_DEVICES"
echo "$0: maximum possible anonymous mmap under Valgrind: $bytes bytes, equals to size of $max_devices DAX device(s). Value saved in $FILE_MAX_DAX_DEVICES."
| 2,524 | 26.445652 | 156 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/pmemdetect/pmemdetect.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* pmemdetect.c -- detect PMEM/Device DAX device or Device DAX alignment
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include "mmap.h"
#include "libpmem.h"
#include "file.h"
#include "os.h"
#include "util.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#define SIZE 4096
#define DEVDAX_DETECT (1 << 0)
#define DEVDAX_ALIGN (1 << 1)
#define MAP_SYNC_SUPP (1 << 2)
#define DAX_REGION_DETECT (1 << 3)
#define FILE_SIZE (1 << 4)
#define err(fmt, ...) fprintf(stderr, "pmemdetect: " fmt, __VA_ARGS__)
/* arguments */
static int Opts;
static char *Path;
static size_t Align;
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
printf("Usage: pmemdetect [options] <path>\n");
printf("Valid options:\n");
printf("-d, --devdax - check if <path> is Device DAX\n");
printf("-a, --align=N - check Device DAX alignment\n");
printf("-r, --dax-region - check if Dev DAX <path> has region id\n");
printf("-s, --map-sync - check if <path> supports MAP_SYNC\n");
printf("-z, --size - print file/Device DAX size\n");
printf("-h, --help - print this usage info\n");
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"devdax", no_argument, NULL, 'd'},
{"align", required_argument, NULL, 'a'},
{"dax-region", no_argument, NULL, 'r'},
{"map-sync", no_argument, NULL, 's'},
{"size", no_argument, NULL, 'z'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* parse_args -- (internal) parse command line arguments
*/
static int
parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "a:dshrz",
long_options, NULL)) != -1) {
switch (opt) {
case 'd':
Opts |= DEVDAX_DETECT;
break;
case 'r':
Opts |= DAX_REGION_DETECT;
break;
case 'a':
Opts |= DEVDAX_ALIGN;
char *endptr;
errno = 0;
size_t align = strtoull(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno) {
err("'%s' -- invalid alignment", optarg);
return -1;
}
Align = align;
break;
case 's':
Opts |= MAP_SYNC_SUPP;
break;
case 'z':
Opts |= FILE_SIZE;
break;
case 'h':
print_usage();
exit(EXIT_SUCCESS);
default:
print_usage();
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
Path = argv[optind];
} else {
print_usage();
exit(EXIT_FAILURE);
}
return 0;
}
/*
* get_params -- get parameters for pmem_map_file
*/
static int
get_params(const char *path, int *flags, size_t *size)
{
int ret;
os_stat_t buf;
ret = os_stat(path, &buf);
if (ret && errno != ENOENT) {
/* error other than no such file */
perror(path);
return -1;
}
if (ret) {
/* no such file */
*flags = PMEM_FILE_CREATE;
*size = SIZE;
} else if (S_ISDIR(buf.st_mode)) {
*flags = PMEM_FILE_CREATE | PMEM_FILE_TMPFILE;
*size = SIZE;
} else {
/* file exist */
*size = 0;
*flags = 0;
}
return 0;
}
/*
* is_pmem -- checks if given path points to pmem-aware filesystem
*/
static int
is_pmem(const char *path)
{
int ret;
int flags;
size_t size;
ret = get_params(path, &flags, &size);
if (ret)
return ret;
int is_pmem;
void *addr = pmem_map_file(path, size, flags, 0, &size, &is_pmem);
if (addr == NULL) {
perror("pmem_map_file failed");
return -1;
}
pmem_unmap(addr, size);
return is_pmem;
}
/*
* is_dev_dax -- checks if given path points to Device DAX
*/
static int
is_dev_dax(const char *path)
{
enum file_type type = util_file_get_type(path);
if (type < 0) {
printf("%s -- not accessible\n", path);
return -1;
}
if (os_access(path, W_OK|R_OK)) {
printf("%s -- permission denied\n", path);
return -1;
}
if (type == TYPE_DEVDAX)
return 1;
printf("%s -- not device dax\n", path);
return 0;
}
/*
* is_dev_dax_align -- checks if Device DAX alignment is as specified
*/
static int
is_dev_dax_align(const char *path, size_t req_align)
{
if (is_dev_dax(path) != 1)
return -1;
size_t align = util_file_device_dax_alignment(path);
return (req_align == align) ? 1 : 0;
}
/*
* supports_map_sync -- checks if MAP_SYNC is supported on a filesystem
* from given path
*/
static int
supports_map_sync(const char *path)
{
int ret;
int flags;
size_t size;
ret = get_params(path, &flags, &size);
if (ret)
return ret;
int fd;
if (flags & PMEM_FILE_TMPFILE)
fd = util_tmpfile(path, "/pmemdetect.XXXXXX", 0);
else if (flags & PMEM_FILE_CREATE)
fd = os_open(path, O_CREAT|O_RDWR, S_IWUSR|S_IRUSR);
else
fd = os_open(path, O_RDWR);
if (fd < 0) {
perror(path);
return -1;
}
if (flags & PMEM_FILE_CREATE) {
ret = os_ftruncate(fd, (off_t)size);
if (ret) {
perror(path);
os_close(fd);
return -1;
}
}
void *addr = mmap(NULL, size, PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_SYNC|MAP_SHARED_VALIDATE, fd, 0);
if (addr != MAP_FAILED) {
ret = 1;
} else if (addr == MAP_FAILED &&
(errno == EOPNOTSUPP || errno == EINVAL)) {
ret = 0;
} else {
err("mmap: %s\n", strerror(errno));
ret = -1;
}
os_close(fd);
if (flags & PMEM_FILE_CREATE && !(flags & PMEM_FILE_TMPFILE))
util_unlink(path);
return ret;
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
err("error during arguments conversion\n");
return 2;
}
}
#endif
int ret;
if (parse_args(argc, argv)) {
ret = 2;
goto out;
}
util_init();
util_mmap_init();
if (Opts & DEVDAX_DETECT)
ret = is_dev_dax(Path);
else if (Opts & DAX_REGION_DETECT) {
unsigned region_id;
ret = util_ddax_region_find(Path, ®ion_id);
if (ret < 0) {
printf("Sysfs id file for dax_region is not supported:"
" %s\n", Path);
ret = 0;
} else {
ret = 1;
}
} else if (Opts & DEVDAX_ALIGN) {
ret = is_dev_dax_align(Path, Align);
} else if (Opts & FILE_SIZE) {
printf("%zu", (size_t)util_file_get_size(Path));
ret = 1;
} else if (Opts & MAP_SYNC_SUPP) {
ret = supports_map_sync(Path);
} else {
ret = is_pmem(Path);
}
/*
* Return 0 on 'true'. Otherwise return 1.
* If any problem occurred return 2.
*/
switch (ret) {
case 0:
ret = 1;
break;
case 1:
ret = 0;
break;
default:
ret = 2;
break;
}
util_mmap_fini();
out:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 6,682 | 18.148997 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/pmemspoil/spoil.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* spoil.c -- pmempool spoil command source file
*/
#include <features.h>
#ifndef __FreeBSD__
#define __USE_UNIX98
#endif
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <libgen.h>
#include <err.h>
#include <assert.h>
#include <endian.h>
#include <libpmem.h>
#include "common.h"
#include "output.h"
#include "btt.h"
#include "set.h"
#include "util.h"
#define STR(x) #x
/*
* Set of macros for parsing structures and fields.
*
* Example:
*
* PROCESS_BEGIN(psp, pfp) {
* PARSE_FIELD(my_struct, my_field, uint32_t);
* PARSE(struct_name, arg, max_index)
* } PROCESS_END
*
* return PROCESS_RET
*
* The PROCESS_STATE holds the state of processing.
* The PROCESS_INDEX holds the index of current field.
*/
/*
* State of processing fields.
*/
enum process_state {
PROCESS_STATE_NOT_FOUND,
PROCESS_STATE_FOUND,
PROCESS_STATE_FIELD,
PROCESS_STATE_FUNC,
PROCESS_STATE_ERROR_MSG,
PROCESS_STATE_ERROR,
};
#define PROCESS_BEGIN(psp, pfp) \
enum process_state PROCESS_STATE = PROCESS_STATE_NOT_FOUND;\
struct pmemspoil *_psp = (psp);\
struct pmemspoil_list *_pfp = (pfp);\
#define PROCESS_RET ((PROCESS_STATE == PROCESS_STATE_FOUND ||\
PROCESS_STATE == PROCESS_STATE_FIELD ||\
PROCESS_STATE == PROCESS_STATE_FUNC) ? 0 : -1)
#define PROCESS_INDEX (_pfp->cur->index)
#define PROCESS_END \
_process_end:\
switch (PROCESS_STATE) {\
case PROCESS_STATE_NOT_FOUND:\
outv_err("unknown field '%s'\n", _pfp->cur->name);\
break;\
case PROCESS_STATE_FIELD:\
outv(2, "spoil: %s\n", _pfp->str);\
break;\
case PROCESS_STATE_FUNC:\
outv(2, "spoil: %s\n", _pfp->str);\
break;\
case PROCESS_STATE_ERROR_MSG:\
outv_err("processing '%s'\n", _pfp->str);\
PROCESS_STATE = PROCESS_STATE_ERROR;\
break;\
default:\
break;\
}
/* _max - size of _arg if it is array (if not it must be 1) */
#define PROCESS(_name, _arg, _max, _type) do {\
if (pmemspoil_check_field(_pfp, STR(_name))) {\
PROCESS_STATE = PROCESS_STATE_FOUND;\
if (_pfp->cur->index >= (_max)) {\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
} else {\
_type a = _arg;\
pmemspoil_next_field(_pfp);\
if (pmemspoil_process_##_name(_psp, _pfp, a))\
PROCESS_STATE = PROCESS_STATE_ERROR;\
}\
goto _process_end;\
}\
} while (0)
#define PROCESS_FIELD(_ptr, _name, _type) do {\
if (pmemspoil_check_field(_pfp, STR(_name))) {\
pmemspoil_next_field(_pfp);\
if (pmemspoil_process_##_type(_psp, _pfp,\
(_type *)&((_ptr)->_name),\
sizeof((_ptr)->_name), 0))\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
else\
PROCESS_STATE = PROCESS_STATE_FIELD;\
goto _process_end;\
}\
} while (0)
#define PROCESS_FIELD_LE(_ptr, _name, _type) do {\
if (pmemspoil_check_field(_pfp, STR(_name))) {\
pmemspoil_next_field(_pfp);\
if (pmemspoil_process_##_type(_psp, _pfp,\
(_type *)&((_ptr)->_name),\
sizeof((_ptr)->_name), 1))\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
else\
PROCESS_STATE = PROCESS_STATE_FIELD;\
goto _process_end;\
}\
} while (0)
#define PROCESS_FUNC(_name, _func, _arg) do {\
if (pmemspoil_check_field(_pfp, (_name))) {\
PROCESS_STATE = PROCESS_STATE_FOUND;\
if (!_pfp->str) {\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
} else {\
if (pmemspoil_process_##_func(_psp, _pfp, (_arg)))\
PROCESS_STATE = PROCESS_STATE_ERROR;\
else\
PROCESS_STATE = PROCESS_STATE_FUNC;\
}\
goto _process_end;\
}\
} while (0)
#define PROCESS_FIELD_ARRAY(_ptr, _name, _type, _max) do {\
if (pmemspoil_check_field(_pfp, STR(_name))) {\
if (_pfp->cur->index >= (_max)) {\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
} else {\
uint64_t ind = PROCESS_INDEX;\
pmemspoil_next_field(_pfp);\
if (pmemspoil_process_##_type(_psp, _pfp,\
(_type *)&((_ptr)->_name[ind]),\
sizeof((_ptr)->_name), 0))\
PROCESS_STATE = PROCESS_STATE_ERROR_MSG;\
else\
PROCESS_STATE = PROCESS_STATE_FIELD;\
}\
goto _process_end;\
}\
} while (0)
/*
* struct field -- single field with name and id
*/
struct field {
struct field *next;
struct field *prev;
char *name;
uint32_t index;
int is_func;
};
/*
* struct pmemspoil_list -- all fields and value
*/
struct pmemspoil_list {
struct field *head;
struct field *tail;
struct field *cur;
char *value;
char *str;
};
/*
* struct pmemspoil -- context and args
*/
struct pmemspoil {
int verbose;
char *fname;
struct pool_set_file *pfile;
struct pmemspoil_list *args;
unsigned argc;
void *addr;
size_t size;
unsigned replica;
uint64_t arena_offset;
};
typedef enum chunk_type chunk_type_t;
/*
* struct chunk_pair -- chunk header and chunk
*/
struct chunk_pair {
struct chunk_header *hdr;
struct chunk *chunk;
};
/*
* struct list_pair -- list head and entry
*/
struct list_pair {
struct list_head *head;
struct list_entry *entry;
};
/*
* struct checksum_args -- arguments for checksum
*/
struct checksum_args {
void *ptr;
size_t len;
void *checksum;
size_t skip_off;
};
/*
* pmemspoil_default -- default context and args
*/
static const struct pmemspoil pmemspoil_default = {
.verbose = 1,
.fname = NULL,
.args = NULL,
.argc = 0,
.replica = 0,
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"%s common options:\n"
" -v, --verbose Increase verbose level\n"
" -?, --help Display this help and exit\n"
" -r, --replica <num> Replica index\n"
"\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"verbose", no_argument, NULL, 'v'},
{"help", no_argument, NULL, '?'},
{"replica", required_argument, NULL, 'r'},
{NULL, 0, NULL, 0 },
};
/*
* pmemspoil_persist -- flush data to persistence
*/
static void
pmemspoil_persist(void *addr, size_t size)
{
if (pmem_is_pmem(addr, size))
pmem_persist(addr, size);
else
pmem_msync(addr, size);
}
/*
* print_usage -- print application usage short description
*/
static void
print_usage(char *appname)
{
printf("Usage: %s <file> <field>=<value>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmemspoil_help -- print help message for spoil command
*/
static void
pmemspoil_help(char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmemspoil_read -- read data from pool
*/
static int
pmemspoil_read(struct pmemspoil *psp, void *buff, size_t nbytes, uint64_t off)
{
return pool_set_file_read(psp->pfile, buff, nbytes, off);
}
/*
* pmemspoil_write -- write data to pool
*/
static int
pmemspoil_write(struct pmemspoil *psp, void *buff, size_t nbytes, uint64_t off)
{
return pool_set_file_write(psp->pfile, buff, nbytes, off);
}
/*
* pmemspoil_parse_field -- parse field name and id from str
*/
static char *
pmemspoil_parse_field(char *str, struct field *fieldp)
{
fieldp->is_func = 0;
if (!str)
return NULL;
char *f = strchr(str, '.');
if (!f)
f = strchr(str, '=');
if (!f) {
if (str[0] == 'f' && str[1] == ':') {
f = str + 2;
fieldp->is_func = 1;
}
}
fieldp->index = 0;
fieldp->name = NULL;
if (f) {
if (fieldp->is_func)
str = f;
else
*f = '\0';
size_t len = 0;
ssize_t ret;
char *secstr = malloc(strlen(str) + 1);
uint32_t secind;
/* search for pattern: <field_name>(<index>) */
if (secstr == NULL)
err(1, NULL);
if ((ret = sscanf(str, "%[^(](%d)", secstr, &secind) == 2)) {
len = strlen(secstr);
str[len] = '\0';
fieldp->index = secind;
}
fieldp->name = str;
free(secstr);
if (fieldp->is_func)
return str + strlen(str);
return f + 1;
}
return NULL;
}
/*
* pmemspoil_free_fields -- free all fields
*/
static void
pmemspoil_free_fields(struct pmemspoil_list *fieldp)
{
struct field *cur = fieldp->head;
while (cur != NULL) {
struct field *next = cur->next;
free(cur);
cur = next;
}
free(fieldp->str);
}
/*
* pmemspoil_insert_field -- insert field
*/
static void
pmemspoil_insert_field(struct pmemspoil_list *listp, struct field *fieldp)
{
fieldp->next = NULL;
fieldp->prev = NULL;
if (listp->head == NULL) {
listp->head = fieldp;
listp->tail = fieldp;
} else {
listp->tail->next = fieldp;
fieldp->prev = listp->tail;
listp->tail = fieldp;
}
}
/*
* pmemspoil_parse_fields -- parse fields and value from str
*/
static int
pmemspoil_parse_fields(char *str, struct pmemspoil_list *listp)
{
struct field f;
char *nstr = NULL;
listp->str = strdup(str);
if (!listp->str)
return -1;
while ((nstr = pmemspoil_parse_field(str, &f)) != NULL) {
struct field *fp = malloc(sizeof(struct field));
if (!fp) {
pmemspoil_free_fields(listp);
err(1, NULL);
}
memcpy(fp, &f, sizeof(*fp));
pmemspoil_insert_field(listp, fp);
str = nstr;
}
listp->value = str;
listp->cur = listp->head;
return (listp->cur == NULL || listp->value == NULL);
}
/*
* pmempool_check_parse_args -- parse command line args
*/
static int
pmemspoil_parse_args(struct pmemspoil *psp, char *appname,
int argc, char *argv[])
{
int opt;
int t;
while ((opt = getopt_long(argc, argv, "v?r:",
long_options, NULL)) != -1) {
switch (opt) {
case 'v':
psp->verbose = 2;
break;
case '?':
pmemspoil_help(appname);
exit(EXIT_SUCCESS);
case 'r':
t = atoi(optarg);
if (t < 0) {
print_usage(appname);
exit(EXIT_FAILURE);
}
psp->replica = (unsigned)t;
break;
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
int ind = optind;
psp->fname = argv[ind];
ind++;
assert(argc >= ind);
psp->argc = (unsigned)(argc - ind);
psp->args = calloc(psp->argc, sizeof(struct pmemspoil_list));
if (!psp->args)
err(1, NULL);
unsigned i;
for (i = 0; i < psp->argc; i++) {
char *str = argv[ind];
if (pmemspoil_parse_fields(str, &psp->args[i])) {
outv_err("ivalid argument");
exit(EXIT_FAILURE);
}
ind += 1;
}
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* pmemspoil_get_arena_offset -- get offset to arena of given id
*/
static uint64_t
pmemspoil_get_arena_offset(struct pmemspoil *psp, uint32_t id,
uint64_t start_offset)
{
struct btt_info *infop = calloc(sizeof(struct btt_info), 1);
if (!infop)
err(1, NULL);
infop->nextoff = start_offset;
uint64_t offset = 0;
ssize_t ret = 0;
id++;
while (id > 0) {
if (infop->nextoff == 0) {
free(infop);
return 0;
}
offset = offset + infop->nextoff;
if ((ret = pmemspoil_read(psp, infop,
sizeof(*infop), offset))) {
free(infop);
return 0;
}
btt_info_convert2h(infop);
id--;
}
free(infop);
return offset;
}
/*
* pmemspoil_check_field -- compares field name and moves pointer if the same
*/
static int
pmemspoil_check_field(struct pmemspoil_list *pfp, const char *fname)
{
if (pfp->cur != NULL && strcmp(pfp->cur->name, fname) == 0) {
return 1;
} else {
return 0;
}
}
/*
* pmemspoil_next_field -- move to next field
*/
static void
pmemspoil_next_field(struct pmemspoil_list *pfp)
{
pfp->cur = pfp->cur->next;
}
/*
* pmemspoil_process_char -- process value as string
*/
static int
pmemspoil_process_char(struct pmemspoil *psp, struct pmemspoil_list *pfp,
char *str, size_t len, int le)
{
len = min(len, strlen(pfp->value));
memcpy(str, pfp->value, len);
pmemspoil_persist(str, len);
return 0;
}
/*
* pmemspoil_process_uint8_t -- process value as uint8
*/
static int
pmemspoil_process_uint8_t(struct pmemspoil *psp, struct pmemspoil_list *pfp,
uint8_t *valp, size_t size, int le)
{
uint8_t v;
if (sscanf(pfp->value, "0x%" SCNx8, &v) != 1 &&
sscanf(pfp->value, "%" SCNu8, &v) != 1)
return -1;
*valp = v;
pmemspoil_persist(valp, sizeof(*valp));
return 0;
}
/*
* pmemspoil_process_uint16_t -- process value as uint16
*/
static int
pmemspoil_process_uint16_t(struct pmemspoil *psp, struct pmemspoil_list *pfp,
uint16_t *valp, size_t size, int le)
{
uint16_t v;
if (sscanf(pfp->value, "0x%" SCNx16, &v) != 1 &&
sscanf(pfp->value, "%" SCNu16, &v) != 1)
return -1;
if (le)
*valp = htole16(v);
else
*valp = v;
pmemspoil_persist(valp, sizeof(*valp));
return 0;
}
/*
* pmemspoil_process_uint32_t -- process value as uint32
*/
static int
pmemspoil_process_uint32_t(struct pmemspoil *psp, struct pmemspoil_list *pfp,
uint32_t *valp, size_t size, int le)
{
uint32_t v;
if (sscanf(pfp->value, "0x%" SCNx32, &v) != 1 &&
sscanf(pfp->value, "%" SCNu32, &v) != 1)
return -1;
if (le)
*valp = htole32(v);
else
*valp = v;
pmemspoil_persist(valp, sizeof(*valp));
return 0;
}
/*
* pmemspoil_process_uint64_t -- process value as uint64
*/
static int
pmemspoil_process_uint64_t(struct pmemspoil *psp, struct pmemspoil_list *pfp,
uint64_t *valp, size_t size, int le)
{
uint64_t v;
if (sscanf(pfp->value, "0x%" SCNx64, &v) != 1 &&
sscanf(pfp->value, "%" SCNu64, &v) != 1)
return -1;
if (le)
*valp = htole64(v);
else
*valp = v;
pmemspoil_persist(valp, sizeof(*valp));
return 0;
}
/*
* pmemspoil_process_chunk_type_t -- process chunk type
*/
static int
pmemspoil_process_chunk_type_t(struct pmemspoil *psp,
struct pmemspoil_list *pfp,
enum chunk_type *valp, size_t size, int le)
{
uint64_t types = 0;
if (util_parse_chunk_types(pfp->value, &types))
return -1;
if (util_popcount64(types) != 1)
return -1;
/* ignore 'le' */
*valp = (enum chunk_type)util_lssb_index64(types);
return 0;
}
/*
* pmemspoil_process_checksum_gen -- generate checksum
*/
static int
pmemspoil_process_checksum_gen(struct pmemspoil *psp,
struct pmemspoil_list *pfp, struct checksum_args args)
{
util_checksum(args.ptr, args.len, (uint64_t *)args.checksum,
1, args.skip_off);
return 0;
}
/*
* pmemspoil_process_shutdown_state -- process shutdown_state fields
*/
static int
pmemspoil_process_shutdown_state(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
struct shutdown_state *sds = arg;
PROCESS_BEGIN(psp, pfp) {
struct checksum_args checksum_args = {
.ptr = sds,
.len = sizeof(*sds),
.checksum = &sds->checksum,
.skip_off = 0,
};
PROCESS_FIELD_LE(sds, usc, uint64_t);
PROCESS_FIELD_LE(sds, uuid, uint64_t);
PROCESS_FIELD_LE(sds, dirty, uint64_t);
PROCESS_FIELD(sds, reserved, char);
PROCESS_FIELD_LE(sds, checksum, uint64_t);
PROCESS_FUNC("checksum_gen", checksum_gen, checksum_args);
} PROCESS_END;
return PROCESS_RET;
}
/*
* pmemspoil_process_features -- process features fields
*/
static int
pmemspoil_process_features(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
features_t *features = arg;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD_LE(features, compat, uint32_t);
PROCESS_FIELD_LE(features, incompat, uint32_t);
PROCESS_FIELD_LE(features, ro_compat, uint32_t);
} PROCESS_END;
return PROCESS_RET;
}
/*
* pmemspoil_process_pool_hdr -- process pool_hdr fields
*/
static int
pmemspoil_process_pool_hdr(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
struct pool_hdr pool_hdr;
if (pmemspoil_read(psp, &pool_hdr, sizeof(pool_hdr), 0))
return -1;
PROCESS_BEGIN(psp, pfp) {
struct checksum_args checksum_args = {
.ptr = &pool_hdr,
.len = sizeof(pool_hdr),
.checksum = &pool_hdr.checksum,
.skip_off = POOL_HDR_CSUM_END_OFF(&pool_hdr),
};
PROCESS_FIELD(&pool_hdr, signature, char);
PROCESS_FIELD(&pool_hdr, poolset_uuid, char);
PROCESS_FIELD(&pool_hdr, uuid, char);
PROCESS_FIELD(&pool_hdr, prev_part_uuid, char);
PROCESS_FIELD(&pool_hdr, next_part_uuid, char);
PROCESS_FIELD(&pool_hdr, prev_repl_uuid, char);
PROCESS_FIELD(&pool_hdr, next_repl_uuid, char);
PROCESS_FIELD(&pool_hdr, unused, char);
PROCESS_FIELD(&pool_hdr, unused2, char);
PROCESS_FIELD_LE(&pool_hdr, major, uint32_t);
PROCESS(features, &pool_hdr.features, 1, features_t *);
PROCESS_FIELD_LE(&pool_hdr, crtime, uint64_t);
PROCESS_FIELD(&pool_hdr, arch_flags, char); /* XXX */
PROCESS(shutdown_state, &pool_hdr.sds, 1,
struct shutdown_state *);
PROCESS_FIELD_LE(&pool_hdr, checksum, uint64_t);
PROCESS_FUNC("checksum_gen", checksum_gen, checksum_args);
} PROCESS_END
if (PROCESS_STATE == PROCESS_STATE_FIELD ||
PROCESS_STATE == PROCESS_STATE_FUNC ||
PROCESS_STATE == PROCESS_STATE_FOUND) {
if (pmemspoil_write(psp, &pool_hdr, sizeof(pool_hdr), 0))
return -1;
}
return PROCESS_RET;
}
/*
* pmemspoil_process_btt_info_struct -- process btt_info at given offset
*/
static int
pmemspoil_process_btt_info_struct(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint64_t offset)
{
struct btt_info btt_info;
if (pmemspoil_read(psp, &btt_info, sizeof(btt_info), offset))
return -1;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD(&btt_info, sig, char);
PROCESS_FIELD(&btt_info, uuid, char);
PROCESS_FIELD(&btt_info, parent_uuid, char);
PROCESS_FIELD_LE(&btt_info, flags, uint32_t);
PROCESS_FIELD_LE(&btt_info, major, uint16_t);
PROCESS_FIELD_LE(&btt_info, minor, uint16_t);
PROCESS_FIELD_LE(&btt_info, external_lbasize, uint32_t);
PROCESS_FIELD_LE(&btt_info, external_nlba, uint32_t);
PROCESS_FIELD_LE(&btt_info, internal_lbasize, uint32_t);
PROCESS_FIELD_LE(&btt_info, internal_nlba, uint32_t);
PROCESS_FIELD_LE(&btt_info, nfree, uint32_t);
PROCESS_FIELD_LE(&btt_info, infosize, uint32_t);
PROCESS_FIELD_LE(&btt_info, nextoff, uint64_t);
PROCESS_FIELD_LE(&btt_info, dataoff, uint64_t);
PROCESS_FIELD_LE(&btt_info, mapoff, uint64_t);
PROCESS_FIELD_LE(&btt_info, flogoff, uint64_t);
PROCESS_FIELD_LE(&btt_info, infooff, uint64_t);
PROCESS_FIELD(&btt_info, unused, char);
PROCESS_FIELD_LE(&btt_info, checksum, uint64_t);
} PROCESS_END
if (PROCESS_STATE == PROCESS_STATE_FIELD) {
if (pmemspoil_write(psp, &btt_info, sizeof(btt_info), offset))
return -1;
}
return PROCESS_RET;
}
/*
* pmemspoil_process_btt_info_backup -- process btt_info backup fields
*/
static int
pmemspoil_process_btt_info_backup(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint32_t index)
{
struct btt_info btt_info_backup;
if (pmemspoil_read(psp, &btt_info_backup, sizeof(btt_info_backup),
psp->arena_offset))
return -1;
uint64_t backup_offset = psp->arena_offset +
le64toh(btt_info_backup.infooff);
return pmemspoil_process_btt_info_struct(psp, pfp, backup_offset);
}
/*
* pmemspoil_process_btt_info -- process btt_info fields
*/
static int
pmemspoil_process_btt_info(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint32_t index)
{
return pmemspoil_process_btt_info_struct(psp, pfp, psp->arena_offset);
}
/*
* pmemspoil_process_btt_map -- process btt map fields
*/
static int
pmemspoil_process_btt_map(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint32_t index)
{
struct btt_info btt_info;
if (pmemspoil_read(psp, &btt_info, sizeof(btt_info),
psp->arena_offset))
return -1;
btt_info_convert2h(&btt_info);
uint64_t mapoff = psp->arena_offset + btt_info.mapoff;
uint64_t mapsize = roundup(btt_info.external_nlba * BTT_MAP_ENTRY_SIZE,
BTT_ALIGNMENT);
uint32_t *mapp = malloc(mapsize);
if (!mapp)
err(1, NULL);
int ret = 0;
if (pmemspoil_read(psp, mapp, mapsize, mapoff)) {
ret = -1;
} else {
uint32_t v;
if (sscanf(pfp->value, "0x%x", &v) != 1 &&
sscanf(pfp->value, "%u", &v) != 1) {
ret = -1;
} else {
mapp[index] = v;
if (pmemspoil_write(psp, mapp, mapsize, mapoff))
ret = -1;
}
}
free(mapp);
return ret;
}
/*
* pmemspoil_process_btt_flog -- process btt_flog first or second fields
*/
static int
pmemspoil_process_btt_nflog(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint64_t arena_offset, int off,
uint32_t index)
{
struct btt_info btt_info;
if (pmemspoil_read(psp, &btt_info, sizeof(btt_info), arena_offset))
return -1;
btt_info_convert2h(&btt_info);
uint64_t flogoff = arena_offset + btt_info.flogoff;
uint64_t flogsize = btt_info.nfree *
roundup(2 * sizeof(struct btt_flog), BTT_FLOG_PAIR_ALIGN);
flogsize = roundup(flogsize, BTT_ALIGNMENT);
uint8_t *flogp = malloc(flogsize);
if (!flogp)
err(1, NULL);
int ret = 0;
if (pmemspoil_read(psp, flogp, flogsize, flogoff)) {
ret = -1;
goto error;
}
struct btt_flog *flog_entryp = (struct btt_flog *)(flogp +
index * BTT_FLOG_PAIR_ALIGN);
if (off)
flog_entryp++;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD_LE(flog_entryp, lba, uint32_t);
PROCESS_FIELD_LE(flog_entryp, old_map, uint32_t);
PROCESS_FIELD_LE(flog_entryp, new_map, uint32_t);
PROCESS_FIELD_LE(flog_entryp, seq, uint32_t);
} PROCESS_END
if (PROCESS_STATE == PROCESS_STATE_FIELD) {
if (pmemspoil_write(psp, flogp, flogsize, flogoff)) {
ret = -1;
goto error;
}
}
ret = PROCESS_RET;
error:
free(flogp);
return ret;
}
/*
* pmemspoil_process_btt_flog -- process first btt flog entry
*/
static int
pmemspoil_process_btt_flog(struct pmemspoil *psp, struct pmemspoil_list *pfp,
uint32_t index)
{
return pmemspoil_process_btt_nflog(psp, pfp,
psp->arena_offset, 0, index);
}
/*
* pmemspoil_process_btt_flog_prime -- process second btt flog entry
*/
static int
pmemspoil_process_btt_flog_prime(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint32_t index)
{
return pmemspoil_process_btt_nflog(psp, pfp,
psp->arena_offset, 1, index);
}
/*
* pmemspoil_process_arena -- process arena fields
*/
static int
pmemspoil_process_arena(struct pmemspoil *psp,
struct pmemspoil_list *pfp, uint64_t arena_offset)
{
if (!arena_offset)
return -1;
struct btt_info btt_info;
if (pmemspoil_read(psp, &btt_info, sizeof(btt_info), arena_offset))
return -1;
btt_info_convert2h(&btt_info);
psp->arena_offset = arena_offset;
PROCESS_BEGIN(psp, pfp) {
PROCESS(btt_info, PROCESS_INDEX, 1, uint32_t);
PROCESS(btt_info_backup, PROCESS_INDEX, 1, uint32_t);
PROCESS(btt_map, PROCESS_INDEX, btt_info.external_nlba,
uint32_t);
PROCESS(btt_flog, PROCESS_INDEX, btt_info.nfree, uint32_t);
PROCESS(btt_flog_prime, PROCESS_INDEX, btt_info.nfree,
uint32_t);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_pmemblk -- process pmemblk fields
*/
static int
pmemspoil_process_pmemblk(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
struct pmemblk pmemblk;
if (pmemspoil_read(psp, &pmemblk, sizeof(pmemblk), 0))
return -1;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD_LE(&pmemblk, bsize, uint32_t);
PROCESS(arena,
pmemspoil_get_arena_offset(psp, PROCESS_INDEX,
ALIGN_UP(sizeof(struct pmemblk),
BLK_FORMAT_DATA_ALIGN)),
UINT32_MAX, uint64_t);
} PROCESS_END
if (PROCESS_STATE == PROCESS_STATE_FIELD) {
if (pmemspoil_write(psp, &pmemblk, sizeof(pmemblk), 0))
return -1;
}
return PROCESS_RET;
}
/*
* pmemspoil_process_bttdevice -- process btt device fields
*/
static int
pmemspoil_process_bttdevice(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
PROCESS_BEGIN(psp, pfp) {
PROCESS(arena,
pmemspoil_get_arena_offset(psp, PROCESS_INDEX,
ALIGN_UP(sizeof(struct pool_hdr),
BTT_ALIGNMENT)),
UINT32_MAX, uint64_t);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_pmemlog -- process pmemlog fields
*/
static int
pmemspoil_process_pmemlog(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
struct pmemlog pmemlog;
if (pmemspoil_read(psp, &pmemlog, sizeof(pmemlog), 0))
return -1;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD_LE(&pmemlog, start_offset, uint64_t);
PROCESS_FIELD_LE(&pmemlog, end_offset, uint64_t);
PROCESS_FIELD_LE(&pmemlog, write_offset, uint64_t);
} PROCESS_END
if (PROCESS_STATE == PROCESS_STATE_FIELD) {
if (pmemspoil_write(psp, &pmemlog, sizeof(pmemlog), 0))
return -1;
}
return PROCESS_RET;
}
/*
* pmemspoil_process_run -- process pmemobj chunk as run
*/
static int
pmemspoil_process_run(struct pmemspoil *psp, struct pmemspoil_list *pfp,
struct chunk_pair cpair)
{
struct chunk_header *chdr = cpair.hdr;
struct chunk_run *run = (struct chunk_run *)cpair.chunk;
if (chdr->type != CHUNK_TYPE_RUN) {
outv_err("%s -- specified chunk is not run", pfp->str);
return -1;
}
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD(run, hdr.block_size, uint64_t);
PROCESS_FIELD_ARRAY(run, content, uint8_t, RUN_CONTENT_SIZE);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_chunk -- process pmemobj chunk structures
*/
static int
pmemspoil_process_chunk(struct pmemspoil *psp, struct pmemspoil_list *pfp,
struct chunk_pair cpair)
{
struct chunk_header *chdr = cpair.hdr;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD(chdr, type, chunk_type_t);
PROCESS_FIELD(chdr, flags, uint16_t);
PROCESS_FIELD(chdr, size_idx, uint32_t);
PROCESS(run, cpair, 1, struct chunk_pair);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_zone -- process pmemobj zone structures
*/
static int
pmemspoil_process_zone(struct pmemspoil *psp, struct pmemspoil_list *pfp,
struct zone *zone)
{
struct zone_header *zhdr = &zone->header;
PROCESS_BEGIN(psp, pfp) {
struct chunk_pair cpair = {
.hdr = &zone->chunk_headers[PROCESS_INDEX],
.chunk = &zone->chunks[PROCESS_INDEX],
};
PROCESS_FIELD(zhdr, magic, uint32_t);
PROCESS_FIELD(zhdr, size_idx, uint32_t);
PROCESS_FIELD(zhdr, reserved, char);
PROCESS(chunk, cpair, zhdr->size_idx, struct chunk_pair);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_heap -- process pmemobj heap structures
*/
static int
pmemspoil_process_heap(struct pmemspoil *psp, struct pmemspoil_list *pfp,
struct heap_layout *hlayout)
{
struct heap_header *hdr = &hlayout->header;
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD(hdr, signature, char);
PROCESS_FIELD(hdr, major, uint64_t);
PROCESS_FIELD(hdr, minor, uint64_t);
PROCESS_FIELD(hdr, unused, uint64_t);
PROCESS_FIELD(hdr, chunksize, uint64_t);
PROCESS_FIELD(hdr, chunks_per_zone, uint64_t);
PROCESS_FIELD(hdr, reserved, char);
PROCESS_FIELD(hdr, checksum, uint64_t);
PROCESS(zone, ZID_TO_ZONE(hlayout, PROCESS_INDEX),
util_heap_max_zone(psp->size), struct zone *);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_lane -- process pmemobj lanes
*/
static int
pmemspoil_process_lane(struct pmemspoil *psp, struct pmemspoil_list *pfp,
struct lane_layout *lane)
{
PROCESS_BEGIN(psp, pfp) {
PROCESS_FIELD_ARRAY(lane, undo.data,
uint8_t, LANE_UNDO_SIZE);
PROCESS_FIELD_ARRAY(lane, internal.data,
uint8_t, LANE_REDO_INTERNAL_SIZE);
PROCESS_FIELD_ARRAY(lane, external.data,
uint8_t, LANE_REDO_EXTERNAL_SIZE);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process_pmemobj -- process pmemobj data structures
*/
static int
pmemspoil_process_pmemobj(struct pmemspoil *psp,
struct pmemspoil_list *pfp, void *arg)
{
struct pmemobjpool *pop = psp->addr;
struct heap_layout *hlayout = (void *)((char *)pop + pop->heap_offset);
struct lane_layout *lanes = (void *)((char *)pop + pop->lanes_offset);
PROCESS_BEGIN(psp, pfp) {
struct checksum_args checksum_args = {
.ptr = pop,
.len = OBJ_DSC_P_SIZE,
.checksum = &pop->checksum,
.skip_off = 0,
};
PROCESS_FIELD(pop, layout, char);
PROCESS_FIELD(pop, lanes_offset, uint64_t);
PROCESS_FIELD(pop, nlanes, uint64_t);
PROCESS_FIELD(pop, heap_offset, uint64_t);
PROCESS_FIELD(pop, unused3, uint64_t);
PROCESS_FIELD(pop, unused, char);
PROCESS_FIELD(pop, checksum, uint64_t);
PROCESS_FIELD(pop, run_id, uint64_t);
PROCESS_FUNC("checksum_gen", checksum_gen, checksum_args);
PROCESS(heap, hlayout, 1, struct heap_layout *);
PROCESS(lane, &lanes[PROCESS_INDEX], pop->nlanes,
struct lane_layout *);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_process -- process headers
*/
static int
pmemspoil_process(struct pmemspoil *psp,
struct pmemspoil_list *pfp)
{
PROCESS_BEGIN(psp, pfp) {
PROCESS(pool_hdr, NULL, 1, void *);
PROCESS(pmemlog, NULL, 1, void *);
PROCESS(pmemblk, NULL, 1, void *);
PROCESS(pmemobj, NULL, 1, void *);
PROCESS(bttdevice, NULL, 1, void *);
} PROCESS_END
return PROCESS_RET;
}
/*
* pmemspoil_func -- main function for check command
*/
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
outv_err("Error during arguments conversion\n");
return 1;
}
}
#endif
char *appname = basename(argv[0]);
util_init();
int ret = 0;
struct pmemspoil *psp = malloc(sizeof(struct pmemspoil));
if (!psp)
err(1, NULL);
/* initialize command line arguments and context to default values */
memcpy(psp, &pmemspoil_default, sizeof(*psp));
/* parse command line arguments */
ret = pmemspoil_parse_args(psp, appname, argc, argv);
if (ret)
goto error;
/* set verbose level */
out_set_vlevel(psp->verbose);
if (psp->fname == NULL) {
print_usage(appname);
exit(EXIT_FAILURE);
}
psp->pfile = pool_set_file_open(psp->fname, 0, 1);
if (!psp->pfile)
err(1, "%s", psp->fname);
if (pool_set_file_set_replica(psp->pfile, psp->replica)) {
outv_err("invalid replica argument max is %u\n",
psp->pfile->poolset ?
psp->pfile->poolset->nreplicas :
0);
return 1;
}
psp->addr = pool_set_file_map(psp->pfile, 0);
psp->size = psp->pfile->size;
out_set_prefix(psp->fname);
for (unsigned i = 0; i < psp->argc; i++) {
ret = pmemspoil_process(psp, &psp->args[i]);
if (ret)
goto error;
}
error:
if (psp->args) {
for (unsigned i = 0; i < psp->argc; i++)
pmemspoil_free_fields(&psp->args[i]);
free(psp->args);
}
pool_set_file_close(psp->pfile);
free(psp);
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 29,890 | 21.576284 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/pmemwrite/write.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* write.c -- simple app for writing data to pool used by pmempool tests
*/
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
#include <inttypes.h>
#include <err.h>
#include "common.h"
#include "output.h"
#include <libpmemlog.h>
#include <libpmemblk.h>
#include "mmap.h"
#include "queue.h"
/*
* pmemwrite -- context and arguments
*/
struct pmemwrite
{
char *fname; /* file name */
int nargs; /* number of arguments */
char **args; /* list of arguments */
};
static struct pmemwrite pmemwrite = {
.fname = NULL,
.nargs = 0,
.args = NULL,
};
/*
* print_usage -- print short description of usage
*/
static void
print_usage(char *appname)
{
printf("Usage: %s <file> <args>...\n", appname);
printf("Valid arguments:\n");
printf("<blockno>:w:<string> - write <string> to <blockno> block\n");
printf("<blockno>:z - set zero flag on <blockno> block\n");
printf("<blockno>:z - set error flag on <blockno> block\n");
}
/*
* pmemwrite_log -- write data to pmemlog pool file
*/
static int
pmemwrite_log(struct pmemwrite *pwp)
{
PMEMlogpool *plp = pmemlog_open(pwp->fname);
if (!plp) {
warn("%s", pwp->fname);
return -1;
}
int i;
int ret = 0;
for (i = 0; i < pwp->nargs; i++) {
size_t len = strlen(pwp->args[i]);
if (pmemlog_append(plp, pwp->args[i], len)) {
warn("%s", pwp->fname);
ret = -1;
break;
}
}
pmemlog_close(plp);
return ret;
}
/*
* pmemwrite_blk -- write data to pmemblk pool file
*/
static int
pmemwrite_blk(struct pmemwrite *pwp)
{
PMEMblkpool *pbp = pmemblk_open(pwp->fname, 0);
if (!pbp) {
warn("%s", pwp->fname);
return -1;
}
int i;
int ret = 0;
size_t blksize = pmemblk_bsize(pbp);
char *blk = malloc(blksize);
if (!blk) {
ret = -1;
outv_err("malloc(%lu) failed\n", blksize);
goto nomem;
}
for (i = 0; i < pwp->nargs; i++) {
int64_t blockno;
char *buff;
size_t buffsize = strlen(pwp->args[i]) + 1;
buff = malloc(buffsize);
if (buff == NULL) {
ret = -1;
outv_err("malloc(%lu) failed\n", buffsize);
goto end;
}
char flag;
/* <blockno>:w:<string> - write string to <blockno> */
if (sscanf(pwp->args[i], "%" SCNi64 ":w:%[^:]",
&blockno, buff) == 2) {
memset(blk, 0, blksize);
size_t bufflen = strlen(buff);
if (bufflen == 0) {
free(buff);
goto end;
}
if (bufflen > blksize) {
outv_err("String is longer than block size. "
"Truncating.\n");
bufflen = blksize;
}
memcpy(blk, buff, bufflen);
ret = pmemblk_write(pbp, blk, blockno);
free(buff);
if (ret)
goto end;
/* <blockno>:<flag> - set <flag> flag on <blockno> */
} else if (sscanf(pwp->args[i], "%" SCNi64 ":%c",
&blockno, &flag) == 2) {
free(buff);
switch (flag) {
case 'z':
ret = pmemblk_set_zero(pbp, blockno);
break;
case 'e':
ret = pmemblk_set_error(pbp, blockno);
break;
default:
outv_err("Invalid flag '%c'\n", flag);
ret = -1;
goto end;
}
if (ret) {
warn("%s", pwp->fname);
goto end;
}
} else {
free(buff);
outv_err("Invalid argument '%s'\n", pwp->args[i]);
ret = -1;
goto end;
}
}
end:
free(blk);
nomem:
pmemblk_close(pbp);
return ret;
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
outv_err("Error during arguments conversion\n");
return 1;
}
}
#endif
int opt;
int ret = 0;
util_init();
char *appname = basename(argv[0]);
while ((opt = getopt(argc, argv, "h")) != -1) {
switch (opt) {
case 'h':
print_usage(appname);
ret = 0;
goto end;
default:
print_usage(appname);
ret = 1;
goto end;
}
}
if (optind + 1 < argc) {
pmemwrite.fname = argv[optind];
optind++;
pmemwrite.nargs = argc - optind;
pmemwrite.args = &argv[optind];
} else {
print_usage(appname);
ret = 1;
goto end;
}
out_set_vlevel(1);
struct pmem_pool_params params;
/* parse pool type from file */
pmem_pool_parse_params(pmemwrite.fname, ¶ms, 1);
switch (params.type) {
case PMEM_POOL_TYPE_BLK:
ret = pmemwrite_blk(&pmemwrite);
break;
case PMEM_POOL_TYPE_LOG:
ret = pmemwrite_log(&pmemwrite);
break;
default:
ret = 1;
}
end:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
return ret;
}
| 4,593 | 18.141667 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/extents/extents.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* extents -- extents listing
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "libpmem2.h"
#include "os.h"
#include "extent.h"
#define B2SEC(n) ((n) >> 9) /* convert bytes to sectors */
enum modes {
MODE_PRINT_ALL_EXTENTS = 0,
MODE_PRINT_ONE_PHY_OF_LOG,
};
static const char *usage_str =
"usage: %s "
"[-h] "
"[-l <logical_offset>] "
"<file>\n";
int
main(int argc, char *argv[])
{
struct extents *exts = NULL;
long unsigned offset = 0;
unsigned extent = 0;
char *error;
int ret = -1;
int opt;
enum modes mode = MODE_PRINT_ALL_EXTENTS;
while ((opt = getopt(argc, argv, "hl:")) != -1) {
switch (opt) {
case 'h':
printf(usage_str, argv[0]);
return 0;
case 'l':
mode = MODE_PRINT_ONE_PHY_OF_LOG;
errno = 0;
offset = strtoul(optarg, &error, 10 /* base */);
if (errno || *error != '\0') {
if (errno)
perror("strtoul");
if (*error != '\0') {
fprintf(stderr,
"error: invalid character(s) in the given logical offset: %s\n",
error);
}
return -1;
}
break;
default:
fprintf(stderr, usage_str, argv[0]);
return -1;
}
}
if (optind + 1 < argc) {
fprintf(stderr, "error: unknown option: %s\n",
argv[optind + 1]);
fprintf(stderr, usage_str, argv[0]);
return -1;
}
if (optind >= argc) {
fprintf(stderr, usage_str, argv[0]);
return -1;
}
const char *file = argv[optind];
int fd = os_open(file, O_RDONLY);
if (fd == -1) {
perror(file);
goto exit_free;
}
ret = pmem2_extents_create_get(fd, &exts);
if (ret)
goto exit_free;
if (exts->extents_count == 0)
goto exit_free;
switch (mode) {
case MODE_PRINT_ALL_EXTENTS:
for (unsigned e = 0; e < exts->extents_count; e++) {
/* extents are in bytes, convert them to sectors */
printf("%lu %lu\n",
B2SEC(exts->extents[e].offset_physical),
B2SEC(exts->extents[e].length));
}
break;
case MODE_PRINT_ONE_PHY_OF_LOG:
/* print the physical offset of the given logical one */
for (unsigned e = 0; e < exts->extents_count; e++) {
if (B2SEC(exts->extents[e].offset_logical) > offset)
break;
extent = e;
}
if (extent == exts->extents_count - 1) {
long unsigned max_log;
max_log = B2SEC(exts->extents[extent].offset_logical) +
B2SEC(exts->extents[extent].length);
if (offset > max_log) {
fprintf(stderr,
"error: maximum logical offset is %lu\n",
max_log);
ret = -1;
goto exit_free;
}
}
offset += B2SEC(exts->extents[extent].offset_physical) -
B2SEC(exts->extents[extent].offset_logical);
printf("%lu\n", offset);
break;
default:
fprintf(stderr, usage_str, argv[0]);
return -1;
}
exit_free:
pmem2_extents_destroy(&exts);
if (fd != -1)
close(fd);
return ret;
}
| 2,877 | 18.186667 | 70 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/fallocate_detect/fallocate_detect.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018, Intel Corporation */
/*
* fallocate_detect -- checks fallocate support on filesystem
*/
#define _GNU_SOURCE
#include "file.h"
#include "os.h"
#ifdef __linux__
#include <errno.h>
#include <fcntl.h>
#include <linux/magic.h>
#include <sys/vfs.h>
/*
* posix_fallocate on Linux is implemented using fallocate
* syscall. This syscall requires file system-specific code on
* the kernel side and not all file systems have this code.
* So when posix_fallocate gets 'not supported' error from
* fallocate it falls back to just writing zeroes.
* Detect it and return information to the caller.
*/
static int
check_fallocate(const char *file)
{
int exit_code = 0;
int fd = os_open(file, O_RDWR | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
perror("os_open");
return 2;
}
if (fallocate(fd, 0, 0, 4096)) {
if (errno == EOPNOTSUPP) {
exit_code = 1;
goto exit;
}
perror("fallocate");
exit_code = 2;
goto exit;
}
struct statfs fs;
if (!fstatfs(fd, &fs)) {
if (fs.f_type != EXT4_SUPER_MAGIC /* also ext2, ext3 */) {
/*
* On CoW filesystems, fallocate reserves _amount
* of_ space but doesn't allocate a specific block.
* As we're interested in DAX filesystems only, just
* skip these tests anywhere else.
*/
exit_code = 1;
goto exit;
}
}
exit:
os_close(fd);
os_unlink(file);
return exit_code;
}
#else
/* no support for fallocate in FreeBSD */
static int
check_fallocate(const char *file)
{
return 1;
}
#endif
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return 1;
}
return check_fallocate(argv[1]);
}
| 1,688 | 18.639535 | 62 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/cmpmap/cmpmap.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2019, Intel Corporation */
/*
* cmpmap -- a tool for comparing files using mmap
*/
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/mman.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "file.h"
#include "fcntl.h"
#include "mmap.h"
#include "os.h"
#include "util.h"
#define CMPMAP_ZERO (1<<0)
#define ADDR_SUM(vp, lp) ((void *)((char *)(vp) + (lp)))
/* arguments */
static char *File1 = NULL; /* file1 name */
static char *File2 = NULL; /* file2 name */
static size_t Length = 0; /* number of bytes to read */
static os_off_t Offset = 0; /* offset from beginning of file */
static int Opts = 0; /* options flag */
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
printf("Usage: cmpmap [options] file1 [file2]\n");
printf("Valid options:\n");
printf("-l, --length=N - compare up to N bytes\n");
printf("-o, --offset=N - skip N bytes at start of the files\n");
printf("-z, --zero - compare bytes of the file1 to NUL\n");
printf("-h, --help - print this usage info\n");
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"length", required_argument, NULL, 'l'},
{"offset", required_argument, NULL, 'o'},
{"zero", no_argument, NULL, 'z'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* parse_args -- (internal) parse command line arguments
*/
static int
parse_args(int argc, char *argv[])
{
int opt;
char *endptr;
os_off_t off;
ssize_t len;
while ((opt = getopt_long(argc, argv, "l:o:zh",
long_options, NULL)) != -1) {
switch (opt) {
case 'l':
errno = 0;
len = strtoll(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno || len < 0) {
fprintf(stderr, "'%s' -- invalid length",
optarg);
return -1;
}
Length = (size_t)len;
break;
case 'o':
errno = 0;
off = strtol(optarg, &endptr, 0);
if ((endptr && *endptr != '\0') || errno || off < 0) {
fprintf(stderr, "'%s' -- invalid offset",
optarg);
return -1;
}
Offset = off;
break;
case 'z':
Opts |= CMPMAP_ZERO;
break;
case 'h':
print_usage();
return 0;
default:
print_usage();
return -1;
}
}
if (optind < argc) {
File1 = argv[optind];
if (optind + 1 < argc)
File2 = argv[optind + 1];
} else {
print_usage();
return -1;
}
return 0;
}
/*
* validate_args -- (internal) validate arguments
*/
static int
validate_args(void)
{
if (File1 == NULL) {
fprintf(stderr, "no file provided");
return -1;
} else if (File2 == NULL && Length == 0) {
fprintf(stderr, "length of the file has to be provided");
return -1;
}
return 0;
}
/*
* do_cmpmap -- (internal) perform cmpmap
*/
static int
do_cmpmap(void)
{
int ret = 0;
int fd1;
int fd2;
size_t size1;
size_t size2;
/* open the first file */
if ((fd1 = os_open(File1, O_RDONLY)) < 0) {
fprintf(stderr, "opening %s failed, errno %d\n", File1, errno);
return -1;
}
ssize_t size_tmp = util_fd_get_size(fd1);
if (size_tmp < 0) {
fprintf(stderr, "getting size of %s failed, errno %d\n", File1,
errno);
ret = -1;
goto out_close1;
}
size1 = (size_t)size_tmp;
int flag = MAP_SHARED;
if (Opts & CMPMAP_ZERO) {
/* when checking if bytes are zeroed */
fd2 = -1;
size2 = (size_t)Offset + Length;
flag |= MAP_ANONYMOUS;
} else if (File2 != NULL) {
/* when comparing two files */
/* open the second file */
if ((fd2 = os_open(File2, O_RDONLY)) < 0) {
fprintf(stderr, "opening %s failed, errno %d\n",
File2, errno);
ret = -1;
goto out_close1;
}
size_tmp = util_fd_get_size(fd2);
if (size_tmp < 0) {
fprintf(stderr, "getting size of %s failed, errno %d\n",
File2, errno);
ret = -1;
goto out_close2;
}
size2 = (size_t)size_tmp;
/* basic check */
size_t min_size = (size1 < size2) ? size1 : size2;
if ((size_t)Offset + Length > min_size) {
if (size1 != size2) {
fprintf(stdout, "%s %s differ in size: %zu"
" %zu\n", File1, File2, size1, size2);
ret = -1;
goto out_close2;
} else {
Length = min_size - (size_t)Offset;
}
}
} else {
assert(0);
}
/* initialize utils */
util_init();
/* map the first file */
void *addr1;
if ((addr1 = util_map(fd1, 0, size1, MAP_SHARED,
1, 0, NULL)) == MAP_FAILED) {
fprintf(stderr, "mmap failed, file %s, length %zu, offset 0,"
" errno %d\n", File1, size1, errno);
ret = -1;
goto out_close2;
}
/* map the second file, or do anonymous mapping to get zeroed bytes */
void *addr2;
if ((addr2 = util_map(fd2, 0, size2, flag, 1, 0, NULL)) == MAP_FAILED) {
fprintf(stderr, "mmap failed, file %s, length %zu, errno %d\n",
File2 ? File2 : "(anonymous)", size2, errno);
ret = -1;
goto out_unmap1;
}
/* compare bytes of memory */
if ((ret = memcmp(ADDR_SUM(addr1, Offset), ADDR_SUM(addr2, Offset),
Length))) {
if (Opts & CMPMAP_ZERO)
fprintf(stderr, "%s is not zeroed\n", File1);
else
fprintf(stderr, "%s %s differ\n", File1, File2);
ret = -1;
}
munmap(addr2, size2);
out_unmap1:
munmap(addr1, size1);
out_close2:
if (File2 != NULL)
(void) os_close(fd2);
out_close1:
(void) os_close(fd1);
return ret;
}
int
main(int argc, char *argv[])
{
#ifdef _WIN32
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
fprintf(stderr, "Error during arguments conversion\n");
return 1;
}
}
#endif
int ret = EXIT_FAILURE;
if (parse_args(argc, argv))
goto end;
if (validate_args())
goto end;
if (do_cmpmap())
goto end;
ret = EXIT_SUCCESS;
end:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
exit(ret);
}
| 5,918 | 20.291367 | 73 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/fip/fip.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* fip.c -- simple application which helps detecting libfabric providers
*
* usage: fip <addr> [<provider>]
*
* If no <provider> argument is specified returns 0 if any supported provider
* from libfabric is available. Otherwise returns 1;
*
* If <provider> argument is specified returns 0 if <provider> is supported
* by libfabric. Otherwise returns 1;
*
* On error returns -1.
*/
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "rpmem_common.h"
#include "rpmem_fip_common.h"
int
main(int argc, char *argv[])
{
struct rpmem_fip_probe probe;
int ret;
if (argc > 3 || argc < 2) {
fprintf(stderr, "usage: %s <addr> [<provider>]\n", argv[0]);
return -1;
}
char *addr = argv[1];
char *prov_str = NULL;
if (argc == 3)
prov_str = argv[2];
struct rpmem_target_info *info;
info = rpmem_target_parse(addr);
if (!info) {
fprintf(stderr, "error: cannot parse address -- '%s'", addr);
return -1;
}
ret = rpmem_fip_probe_get(info->node, &probe);
if (ret) {
fprintf(stderr, "error: probing on '%s' failed\n", info->node);
return -1;
}
if (!prov_str) {
if (!rpmem_fip_probe_any(probe)) {
printf("no providers found\n");
ret = 1;
goto out;
}
ret = 0;
goto out;
}
enum rpmem_provider prov = rpmem_provider_from_str(prov_str);
if (prov == RPMEM_PROV_UNKNOWN) {
fprintf(stderr, "error: unsupported provider '%s'\n",
prov_str);
ret = -1;
goto out;
}
if (!rpmem_fip_probe(probe, prov)) {
printf("'%s' provider not available at '%s'\n",
prov_str, info->node);
ret = 1;
goto out;
}
out:
rpmem_target_free(info);
return ret;
}
| 1,729 | 19.352941 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/sparsefile/sparsefile.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* sparsefile.c -- a simple utility to create sparse files on Windows
*
* usage: sparsefile [options] filename len
* where options can be:
* -v - verbose output
* -s - do not create file if sparse files are not supported
* -f - overwrite file if already exists
*/
#include <windows.h>
#include <stdio.h>
#include <getopt.h>
#include "util.h"
#define MAXPRINT 8192
static int Verbose;
/*
* out_err_vargs -- print error message
*/
static void
out_err_vargs(const wchar_t *fmt, va_list ap)
{
wchar_t errmsg[MAXPRINT];
DWORD lasterr = GetLastError();
vfwprintf(stderr, fmt, ap);
if (lasterr) {
size_t size = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
NULL, lasterr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
errmsg, MAXPRINT, NULL);
fwprintf(stderr, L": %s", errmsg);
} else {
fwprintf(stderr, L"\n");
}
SetLastError(0);
}
/*
* out_err -- print error message
*/
static void
out_err(const wchar_t *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
out_err_vargs(fmt, ap);
va_end(ap);
}
/*
* print_file_size -- prints file size and its size on disk
*/
static void
print_file_size(HANDLE fh)
{
LARGE_INTEGER filesize;
FILE_COMPRESSION_INFO fci;
BOOL ret = GetFileSizeEx(fh, &filesize);
if (ret == FALSE) {
out_err(L"GetFileSizeEx");
return;
}
ret = GetFileInformationByHandleEx(fh, FileCompressionInfo,
&fci, sizeof(fci));
if (ret == FALSE) {
out_err(L"GetFileInformationByHandleEx");
return;
}
if (filesize.QuadPart < 65536)
fwprintf(stderr, L"\ntotal size: %lluB",
filesize.QuadPart);
else
fwprintf(stderr, L"\ntotal size: %lluKB",
filesize.QuadPart / 1024);
if (fci.CompressedFileSize.QuadPart < 65536)
fwprintf(stderr, L", actual size on disk: %lluKB\n",
fci.CompressedFileSize.QuadPart);
else
fwprintf(stderr, L", actual size on disk: %lluKB\n",
fci.CompressedFileSize.QuadPart / 1024);
}
/*
* set_file_size - set file length
*/
static int
set_file_size(HANDLE fh, size_t len)
{
LARGE_INTEGER llen;
llen.QuadPart = len;
int ret = SetFilePointerEx(fh, llen, NULL, FILE_BEGIN);
if (ret == FALSE) {
out_err(L"SetFilePointerEx");
return 1;
}
ret = SetEndOfFile(fh);
if (ret == FALSE) {
out_err(L"SetEndOfFile");
return 1;
}
return 0;
}
/*
* set_sparse_file -- creates sparse file of given size
*/
static int
set_sparse_file(HANDLE fh, int force)
{
/* check if sparse files are supported */
DWORD flags = 0;
BOOL ret = GetVolumeInformationByHandleW(fh, NULL, 0, NULL, NULL,
&flags, NULL, 0);
if (ret == FALSE) {
out_err(L"GetVolumeInformationByHandle");
return 1;
}
if ((flags & FILE_SUPPORTS_SPARSE_FILES) == 0) {
return force ? 1 : 0;
}
DWORD nbytes;
ret = DeviceIoControl(fh, FSCTL_SET_SPARSE, NULL, 0, NULL,
0, &nbytes, NULL);
if (ret == FALSE) {
out_err(L"DeviceIoControl(FSCTL_SET_SPARSE)");
return 1;
}
return 0;
}
/*
* set_compressed_file -- creates sparse file of given size
*/
static int
set_compressed_file(HANDLE fh, int force)
{
/* check if sparse files are supported */
DWORD flags = 0;
BOOL ret = GetVolumeInformationByHandleW(fh, NULL, 0, NULL, NULL,
&flags, NULL, 0);
if (ret == FALSE) {
out_err(L"GetVolumeInformationByHandle");
return 1;
}
if ((flags & FILE_FILE_COMPRESSION) == 0) {
return force ? 1 : 0;
}
DWORD nbytes;
USHORT n = 1; /* magic undocumented value */
ret = DeviceIoControl(fh, FSCTL_SET_COMPRESSION, &n, sizeof(n), NULL, 0,
&nbytes, NULL);
if (ret == FALSE) {
out_err(L"DeviceIoControl(FSCTL_SET_COMPRESSION)");
return 1;
}
return 0;
}
int
main(int argc, char *argv[])
{
util_suppress_errmsg();
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
out_err(L"Error during arguments conversion\n");
return 1;
}
}
if (argc < 2) {
fprintf(stderr, "Usage: %s filename len\n", argv[0]);
exit(1);
}
int i = 1;
int opt;
DWORD create_mode = OPEN_ALWAYS;
int compress = 0;
int sparse = 0;
int check = 0;
int force = 0;
long long len = 0;
while ((opt = getopt(argc, argv, "vnscfl:")) != -1) {
switch (opt) {
case 'p':
check = 1;
case 'v':
Verbose = 1;
break;
case 's':
sparse = 1;
break;
case 'f':
force = 1;
break;
case 'n':
create_mode = CREATE_ALWAYS;
break;
case 'c':
compress = 1;
break;
case 'l':
len = atoll(optarg);
if (len < 0) {
out_err(L"Invalid file length: %lld.\n",
len);
exit(3);
}
break;
default:
out_err(L"Unknown option: \'%c\'.", argv[i][1]);
exit(2);
}
}
wchar_t *filename = util_toUTF16(argv[optind]);
if (filename == NULL) {
out_err(L"util_toUTF16");
return 1;
}
/* create zero-length file */
HANDLE fh = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
create_mode, FILE_ATTRIBUTE_NORMAL, NULL);
util_free_UTF16(filename);
if (fh == INVALID_HANDLE_VALUE) {
out_err(L"CreateFile");
return -1;
}
if (sparse && set_sparse_file(fh, force)) {
return -1;
}
if (compress && set_compressed_file(fh, force)) {
return -1;
}
if (len && set_file_size(fh, len)) {
return -1;
}
if (Verbose)
print_file_size(fh);
CloseHandle(fh);
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
return 0;
}
| 5,489 | 18.819495 | 73 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/cpufd/cpufd.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* cpufd.c -- cpu feature detector - tool to detect
* the best SIMD extension available.
*
* Return values:
* 1 - SSE2 available
* 2 - AVX available
* 3 - AVX512 available
*/
#include "cpu.h"
int
main(int argc, char *argv[])
{
/* SSE2 by default */
int ret = 1;
if (is_cpu_avx_present())
ret = 2;
if (is_cpu_avx512f_present())
ret = 3;
return ret;
}
| 456 | 14.233333 | 51 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/obj_verify/obj_verify.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* obj_verify.c -- tool for creating and verifying a pmemobj pool
*/
#include <stddef.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "libpmemobj.h"
#include "set.h"
#include "os.h"
#define SIGNATURE_LEN 10
#define NUMBER_LEN 10
#define FILL_SIZE 245 /* so that size of one record is 1024 bytes */
#define SKIP_OFFSET offsetof(struct data_s, checksum)
static const char *Signature = "OBJ_VERIFY";
POBJ_LAYOUT_BEGIN(obj_verify);
POBJ_LAYOUT_ROOT(obj_verify, struct root_s);
POBJ_LAYOUT_ROOT(obj_verify, struct data_s);
POBJ_LAYOUT_END(obj_verify);
struct data_s {
char signature[SIGNATURE_LEN];
char number_str[NUMBER_LEN];
uint64_t number;
uint32_t fill[FILL_SIZE];
uint64_t checksum;
};
struct root_s {
uint64_t count;
};
static void
fill_data_s(struct data_s *rec, uint64_t number)
{
int value = rand();
memcpy(rec->signature, Signature, sizeof(rec->signature));
if (util_snprintf(rec->number_str, NUMBER_LEN, "%09lu", number) < 0)
abort();
rec->number = number;
memset(rec->fill, value, FILL_SIZE * sizeof(int));
util_checksum(rec, sizeof(*rec), &rec->checksum,
1 /* insert */, SKIP_OFFSET);
}
static int
alloc_objs(PMEMobjpool *pop, TOID(struct root_s) root, unsigned cnt,
unsigned class_id)
{
int aborted = 0;
TX_BEGIN(pop) {
TX_ADD_FIELD(root, count);
for (unsigned i = 0; i < cnt; ++i) {
PMEMoid oid = pmemobj_tx_xalloc(sizeof(struct data_s),
0,
POBJ_CLASS_ID(class_id));
fill_data_s(pmemobj_direct(oid),
D_RW(root)->count++);
}
} TX_ONABORT {
aborted = 1;
} TX_END
return aborted;
}
/*
* do_create -- (internal) create a pool to be verified
*/
static void
do_create(const char *path, const char *layout)
{
struct pobj_alloc_class_desc class;
PMEMobjpool *pop;
uint64_t count;
srand((unsigned int)time(NULL));
if ((pop = pmemobj_create(path, layout, 0,
S_IWUSR | S_IRUSR)) == NULL) {
if (errno != EEXIST) {
out("!%s: pmemobj_create: %s",
path, pmemobj_errormsg());
exit(-1);
}
if ((pop = pmemobj_open(path, layout)) == NULL) {
out("!%s: pmemobj_open: %s",
path, pmemobj_errormsg());
exit(-1);
}
}
TOID(struct root_s) root = POBJ_ROOT(pop, struct root_s);
class.header_type = POBJ_HEADER_NONE;
class.unit_size = sizeof(struct data_s);
class.alignment = 0;
class.units_per_block = 1000;
if (pmemobj_ctl_set(pop, "heap.alloc_class.new.desc", &class) != 0) {
pmemobj_close(pop);
out("!pmemobj_ctl_set: %s", path);
exit(-1);
}
out("create(%s): allocating records in the pool ...", path);
count = D_RO(root)->count;
while (alloc_objs(pop, root, class.units_per_block,
class.class_id) == 0)
;
count = D_RO(root)->count - count;
if (count) {
out("create(%s): allocated %lu records (of size %zu)",
path, count, sizeof(struct data_s));
} else {
out("create(%s): pool is full", path);
}
pmemobj_close(pop);
}
/*
* do_verify -- (internal) verify a poolset
*/
static void
do_verify(const char *path, const char *layout)
{
PMEMobjpool *pop;
PMEMoid oid;
uint64_t count = 0;
int error = 0;
if ((pop = pmemobj_open(path, layout)) == NULL) {
out("!%s: pmemobj_open: %s",
path, pmemobj_errormsg());
exit(-1);
}
TOID(struct root_s) root = POBJ_ROOT(pop, struct root_s);
TOID(struct data_s) rec;
POBJ_FOREACH(pop, oid) {
TOID_ASSIGN(rec, oid);
if (!util_checksum(D_RW(rec), sizeof(*D_RW(rec)),
&D_RW(rec)->checksum,
0 /* verify */, SKIP_OFFSET)) {
out("verify(%s): incorrect record: %s (#%lu)",
path, D_RW(rec)->signature, count);
error = 1;
break;
}
count++;
}
if (D_RO(root)->count != count) {
out(
"verify(%s): incorrect number of records (is: %lu, should be: %lu)",
path, count, D_RO(root)->count);
error = 1;
}
pmemobj_close(pop);
if (error) {
out("verify(%s): pool file contains error", path);
exit(-1);
}
out(
"verify(%s): pool file successfully verified (%lu records of size %zu)",
path, count, sizeof(struct data_s));
}
int
main(int argc, char *argv[])
{
util_init();
out_init("OBJ_VERIFY", "OBJ_VERIFY", "", 1, 0);
if (argc < 4) {
out("Usage: %s <obj_pool> <layout> <op:c|v>\n"
"Options:\n"
" c - create\n"
" v - verify\n",
argv[0]);
exit(-1);
}
const char *path = argv[1];
const char *layout = argv[2];
const char *op;
/*
* This application can be very time-consuming
* when it is run on an non-pmem filesystem,
* so let's set PMEM_IS_PMEM_FORCE to 1 for this case.
*/
os_setenv("PMEM_IS_PMEM_FORCE", "1", 1 /* overwrite */);
/* go through all arguments one by one */
for (int arg = 3; arg < argc; arg++) {
op = argv[arg];
if (op[1] != '\0') {
out("op must be c or v (c=create, v=verify)");
exit(-1);
}
switch (op[0]) {
case 'c': /* create and verify (no debug) */
do_create(path, layout);
break;
case 'v': /* verify (no debug) */
do_verify(path, layout);
break;
default:
out("op must be c or v (c=create, v=verify)");
exit(-1);
break;
}
}
out_fini();
return 0;
}
| 5,106 | 19.592742 | 74 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/ctrld/signals_linux.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* signals_linux.h - Signal definitions for Linux
*/
#ifndef _SIGNALS_LINUX_H
#define _SIGNALS_LINUX_H 1
#define SIGNAL_2_STR(sig) [sig] = #sig
static const char *signal2str[] = {
SIGNAL_2_STR(SIGHUP), /* 1 */
SIGNAL_2_STR(SIGINT), /* 2 */
SIGNAL_2_STR(SIGQUIT), /* 3 */
SIGNAL_2_STR(SIGILL), /* 4 */
SIGNAL_2_STR(SIGTRAP), /* 5 */
SIGNAL_2_STR(SIGABRT), /* 6 */
SIGNAL_2_STR(SIGBUS), /* 7 */
SIGNAL_2_STR(SIGFPE), /* 8 */
SIGNAL_2_STR(SIGKILL), /* 9 */
SIGNAL_2_STR(SIGUSR1), /* 10 */
SIGNAL_2_STR(SIGSEGV), /* 11 */
SIGNAL_2_STR(SIGUSR2), /* 12 */
SIGNAL_2_STR(SIGPIPE), /* 13 */
SIGNAL_2_STR(SIGALRM), /* 14 */
SIGNAL_2_STR(SIGTERM), /* 15 */
SIGNAL_2_STR(SIGSTKFLT), /* 16 */
SIGNAL_2_STR(SIGCHLD), /* 17 */
SIGNAL_2_STR(SIGCONT), /* 18 */
SIGNAL_2_STR(SIGSTOP), /* 19 */
SIGNAL_2_STR(SIGTSTP), /* 20 */
SIGNAL_2_STR(SIGTTIN), /* 21 */
SIGNAL_2_STR(SIGTTOU), /* 22 */
SIGNAL_2_STR(SIGURG), /* 23 */
SIGNAL_2_STR(SIGXCPU), /* 24 */
SIGNAL_2_STR(SIGXFSZ), /* 25 */
SIGNAL_2_STR(SIGVTALRM), /* 26 */
SIGNAL_2_STR(SIGPROF), /* 27 */
SIGNAL_2_STR(SIGWINCH), /* 28 */
SIGNAL_2_STR(SIGPOLL), /* 29 */
SIGNAL_2_STR(SIGPWR), /* 30 */
SIGNAL_2_STR(SIGSYS) /* 31 */
};
#define SIGNALMAX SIGSYS
#endif
| 1,322 | 27.148936 | 49 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/ctrld/signals_freebsd.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* signals_fbsd.h - Signal definitions for FreeBSD
*/
#ifndef _SIGNALS_FBSD_H
#define _SIGNALS_FBSD_H 1
#define SIGNAL_2_STR(sig) [sig] = #sig
static const char *signal2str[] = {
SIGNAL_2_STR(SIGHUP), /* 1 */
SIGNAL_2_STR(SIGINT), /* 2 */
SIGNAL_2_STR(SIGQUIT), /* 3 */
SIGNAL_2_STR(SIGILL), /* 4 */
SIGNAL_2_STR(SIGTRAP), /* 5 */
SIGNAL_2_STR(SIGABRT), /* 6 */
SIGNAL_2_STR(SIGEMT), /* 7 */
SIGNAL_2_STR(SIGFPE), /* 8 */
SIGNAL_2_STR(SIGKILL), /* 9 */
SIGNAL_2_STR(SIGBUS), /* 10 */
SIGNAL_2_STR(SIGSEGV), /* 11 */
SIGNAL_2_STR(SIGSYS), /* 12 */
SIGNAL_2_STR(SIGPIPE), /* 13 */
SIGNAL_2_STR(SIGALRM), /* 14 */
SIGNAL_2_STR(SIGTERM), /* 15 */
SIGNAL_2_STR(SIGURG), /* 16 */
SIGNAL_2_STR(SIGSTOP), /* 17 */
SIGNAL_2_STR(SIGTSTP), /* 18 */
SIGNAL_2_STR(SIGCONT), /* 19 */
SIGNAL_2_STR(SIGCHLD), /* 20 */
SIGNAL_2_STR(SIGTTIN), /* 21 */
SIGNAL_2_STR(SIGTTOU), /* 22 */
SIGNAL_2_STR(SIGIO), /* 23 */
SIGNAL_2_STR(SIGXCPU), /* 24 */
SIGNAL_2_STR(SIGXFSZ), /* 25 */
SIGNAL_2_STR(SIGVTALRM), /* 26 */
SIGNAL_2_STR(SIGPROF), /* 27 */
SIGNAL_2_STR(SIGWINCH), /* 28 */
SIGNAL_2_STR(SIGINFO), /* 29 */
SIGNAL_2_STR(SIGUSR1), /* 30 */
SIGNAL_2_STR(SIGUSR2), /* 31 */
SIGNAL_2_STR(SIGTHR), /* 32 */
SIGNAL_2_STR(SIGLIBRT) /* 33 */
};
#define SIGNALMAX SIGLIBRT
#endif
| 1,386 | 26.74 | 50 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/tools/ctrld/ctrld.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* ctrld.c -- simple application which helps running tests on remote node.
*
* XXX - wait_port is not supported on FreeBSD because there are currently
* no test cases that require it.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <limits.h>
#include <queue.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdarg.h>
#include "os.h"
#include "util.h"
#ifdef __FreeBSD__
#include "signals_freebsd.h"
#else
#include "signals_linux.h"
#endif
#define APP_NAME "ctrld"
#define BUFF_SIZE 4096
#define S_MINUTE (60) /* seconds in one minute */
#define S_HOUR (60 * 60) /* seconds in one hour */
#define S_DAY (60 * 60 * 24) /* seconds in one day */
static FILE *log_fh;
static void
log_err(const char *file, int lineno, const char *fmt, ...)
{
FILE *fh = log_fh ? log_fh : stderr;
va_list ap;
fprintf(fh, "[%s:%d] ", file, lineno);
char *prefix = "";
char *errstr = "";
if (*fmt == '!') {
fmt++;
prefix = ": ";
errstr = strerror(errno);
}
va_start(ap, fmt);
vfprintf(fh, fmt, ap);
va_end(ap);
fprintf(fh, "%s%s\n", prefix, errstr);
fflush(fh);
}
#define CTRLD_LOG(...) log_err(__FILE__, __LINE__, __VA_ARGS__)
struct inode_item {
PMDK_LIST_ENTRY(inode_item) next;
unsigned long inode;
};
struct inodes {
PMDK_LIST_HEAD(inode_items, inode_item) head;
};
/*
* usage -- print usage and exit with failure code
*/
static void
usage(void)
{
CTRLD_LOG("usage: %s <pid file> <cmd> [<arg>]", APP_NAME);
CTRLD_LOG("commands:");
CTRLD_LOG(" exe <command> [<args...>] -- "
"run specified command");
CTRLD_LOG(" run <timeout> <command> [<args...>] -- "
"run specified command with given timeout");
CTRLD_LOG(" wait [<timeout>] -- "
"wait for command");
#ifndef __FreeBSD_
CTRLD_LOG(" wait_port <port> -- "
"wait until a port is opened");
#endif
CTRLD_LOG(" kill <signal> -- "
"send a signal to command");
exit(EXIT_FAILURE);
}
/*
* alloc_argv -- allocate NULL terminated list of arguments at specified offset
*/
static char **
alloc_argv(unsigned argc, char *argv[], unsigned off)
{
if (argc < off)
return NULL;
unsigned nargc = argc - off;
char **nargv = malloc((nargc + 1) * sizeof(char *));
if (!nargv)
return NULL;
for (unsigned i = 0; i < nargc; i++)
nargv[i] = argv[i + off];
nargv[nargc] = NULL;
return nargv;
}
/*
* do_run_or_exe -- execute the 'run' or the 'exe' command
*
* if timeout is equal to 0 cmd will be just executed (the 'exe' command)
* otherwise it will be run and wait with timeout (the 'run' command)
*/
static int
do_run_or_exe(const char *pid_file, char *cmd, char *argv[], unsigned timeout)
{
int rv = -1;
FILE *fh = os_fopen(pid_file, "w+");
if (!fh) {
CTRLD_LOG("!%s", pid_file);
return -1;
}
int fd = fileno(fh);
if (fd == -1) {
CTRLD_LOG("!fileno");
goto err;
}
if (os_flock(fd, LOCK_EX | LOCK_NB)) {
CTRLD_LOG("!flock");
goto err;
}
if (timeout != 0) {
if (daemon(1, 0)) {
CTRLD_LOG("!daemon");
goto err;
}
}
int child = fork();
switch (child) {
case -1:
CTRLD_LOG("!fork");
fprintf(fh, "-1r%d", errno);
goto err;
case 0:
execvp(cmd, argv);
CTRLD_LOG("!execvp(%s)", cmd);
goto err;
default:
break;
}
if (fprintf(fh, "%d", child) < 0) {
CTRLD_LOG("!fprintf");
goto err;
}
if (fflush(fh)) {
CTRLD_LOG("!fflush");
goto err;
}
int child_timeout = -1;
if (timeout != 0) {
child_timeout = fork();
switch (child_timeout) {
case -1:
CTRLD_LOG("!fork");
fprintf(fh, "-1r%d", errno);
goto err;
case 0:
fclose(fh);
sleep(timeout);
return 0;
default:
break;
}
}
int ret = 0;
int pid = wait(&ret);
if (pid == child) {
if (timeout != 0) {
/* kill the timeout child */
kill(child_timeout, SIGTERM);
}
if (WIFSIGNALED(ret)) {
ret = 128 + WTERMSIG(ret);
} else {
ret = WEXITSTATUS(ret);
}
if (fseek(fh, 0, SEEK_SET)) {
CTRLD_LOG("!fseek");
goto err;
}
if (os_ftruncate(fileno(fh), 0)) {
CTRLD_LOG("!ftruncate");
goto err;
}
fprintf(fh, "%dr%d", child, ret);
} else if (timeout != 0 && pid == child_timeout) {
CTRLD_LOG("run: timeout");
if (kill(child, SIGTERM) && errno != ESRCH) {
CTRLD_LOG("!kill");
goto err;
}
CTRLD_LOG("run: process '%s' killed (PID %i)", cmd, child);
} else {
CTRLD_LOG("!wait");
goto err;
}
rv = 0;
err:
fclose(fh);
return rv;
}
/*
* do_wait -- execute the 'wait' command
*/
static int
do_wait(char *pid_file, int timeout)
{
int fd = os_open(pid_file, O_RDONLY);
if (fd < 0) {
perror(pid_file);
return 1;
}
int ret;
int t = 0;
while ((timeout == -1 || t < timeout) &&
os_flock(fd, LOCK_EX | LOCK_NB)) {
sleep(1);
t++;
}
FILE *fh = os_fdopen(fd, "r");
if (!fh) {
CTRLD_LOG("!fdopen");
ret = 1;
goto err;
}
pid_t pid;
char r;
int n = fscanf(fh, "%d%c%d", &pid, &r, &ret);
if (n < 0) {
CTRLD_LOG("!fscanf");
ret = 1;
goto err;
}
if (n == 2 || (n == 3 && r != 'r')) {
CTRLD_LOG("invalid format of PID file");
ret = 1;
goto err;
}
if (n == 1) {
if (timeout >= 0) {
ret = -1;
goto err;
} else {
CTRLD_LOG("missing return value");
ret = 1;
goto err;
}
}
err:
os_close(fd);
fclose(fh);
return ret;
}
/*
* do_kill -- execute the 'kill' command
*/
static int
do_kill(char *pid_file, int signo)
{
FILE *fh = os_fopen(pid_file, "r");
if (!fh) {
CTRLD_LOG("!%s", pid_file);
return 1;
}
int ret;
pid_t pid;
int n = fscanf(fh, "%d", &pid);
if (n == 0) {
ret = 0;
goto out;
}
/* do not fail if such process already does not exist */
if (kill(pid, signo) && errno != ESRCH) {
CTRLD_LOG("!kill");
ret = 1;
goto out;
}
ret = 0;
out:
fclose(fh);
return ret;
}
#ifndef __FreeBSD__ /* XXX wait_port support */
/*
* contains_inode -- check if list contains specified inode
*/
static int
contains_inode(struct inodes *inodes, unsigned long inode)
{
struct inode_item *inode_item;
PMDK_LIST_FOREACH(inode_item, &inodes->head, next) {
if (inode_item->inode == inode)
return 1;
}
return 0;
}
/*
* has_port_inode -- check if /proc/net/tcp has an entry with specified
* port and inode
*/
static int
has_port_inode(unsigned short port, struct inodes *inodes)
{
/* format of /proc/net/tcp entries */
const char * const tcp_fmt =
"%*d: "
"%*64[0-9A-Fa-f]:%X "
"%*64[0-9A-Fa-f]:%*X "
"%*X %*X:%*X %*X:%*X "
"%*X %*d %*d %lu %*s\n";
char buff[BUFF_SIZE];
FILE *fh = os_fopen("/proc/net/tcp", "r");
if (!fh) {
CTRLD_LOG("!%s", "/proc/net/tcp");
return -1;
}
int ret;
/* read heading */
char *s = fgets(buff, 4096, fh);
if (!s) {
ret = -1;
goto out;
}
while (1) {
s = fgets(buff, 4096, fh);
if (!s)
break;
/* read port number and inode number */
unsigned p;
unsigned long inode;
if (sscanf(s, tcp_fmt, &p, &inode) != 2) {
ret = -1;
goto out;
}
/*
* if port matches and inode is on a list
* the process has this port opened
*/
if (p == port && contains_inode(inodes, inode)) {
ret = 1;
goto out;
}
}
ret = 0;
out:
fclose(fh);
return ret;
}
/*
* get_inodes -- get list of inodes
*/
static int
get_inodes(pid_t pid, struct inodes *inodes)
{
char path[PATH_MAX];
char link[PATH_MAX];
int ret;
/* set a path to opened files of specified process */
if (util_snprintf(path, PATH_MAX, "/proc/%d/fd", pid) < 0) {
CTRLD_LOG("snprintf: %d", errno);
return -1;
}
/* open dir with all opened files */
DIR *d = opendir(path);
if (!d) {
CTRLD_LOG("!%s", path);
ret = -1;
goto out_dir;
}
/* read all directory entries */
struct dirent *dent;
while ((dent = readdir(d)) != NULL) {
/* create a full path to file */
if (util_snprintf(path, PATH_MAX,
"/proc/%d/fd/%s", pid, dent->d_name) < 0) {
CTRLD_LOG("snprintf: %d", errno);
ret = -1;
goto out_dir;
}
/* read symbolic link */
ssize_t sret = readlink(path, link, PATH_MAX - 1);
if (sret <= 0)
continue;
link[sret] = '\0';
/* check if this is a socket, read inode number if so */
unsigned long inode;
if (sscanf(link, "socket:[%lu]", &inode) != 1)
continue;
/* add inode to a list */
struct inode_item *inode_item = malloc(sizeof(*inode_item));
if (!inode_item) {
CTRLD_LOG("!malloc inode item");
exit(1);
}
inode_item->inode = inode;
PMDK_LIST_INSERT_HEAD(&inodes->head, inode_item, next);
}
ret = 0;
out_dir:
closedir(d);
return ret;
}
/*
* clear_inodes -- clear list of inodes
*/
static void
clear_inodes(struct inodes *inodes)
{
while (!PMDK_LIST_EMPTY(&inodes->head)) {
struct inode_item *inode_item = PMDK_LIST_FIRST(&inodes->head);
PMDK_LIST_REMOVE(inode_item, next);
free(inode_item);
}
}
/*
* has_port -- check if process has the specified tcp port opened
*/
static int
has_port(pid_t pid, unsigned short port)
{
struct inodes inodes;
memset(&inodes, 0, sizeof(inodes));
int ret = get_inodes(pid, &inodes);
if (ret < 0)
return -1;
if (!PMDK_LIST_EMPTY(&inodes.head)) {
ret = has_port_inode(port, &inodes);
clear_inodes(&inodes);
}
return ret;
}
/*
* do_wait_port -- wait until process opens a specified tcp port
*/
static int
do_wait_port(char *pid_file, unsigned short port)
{
FILE *fh = os_fopen(pid_file, "r");
if (!fh) {
CTRLD_LOG("!%s", pid_file);
return 1;
}
int ret;
pid_t pid;
char r;
int n = fscanf(fh, "%d%c%d", &pid, &r, &ret);
if (n < 0) {
CTRLD_LOG("!fscanf");
ret = 1;
goto err;
}
if (n == 2 || (n == 3 && r != 'r')) {
CTRLD_LOG("invalid format of PID file");
ret = 1;
goto err;
}
if (n == 3) {
CTRLD_LOG("process already terminated");
ret = 1;
goto err;
}
int hp;
do {
hp = has_port(pid, port);
if (hp < 0) {
ret = 1;
goto err;
}
} while (!hp);
return 0;
err:
fclose(fh);
return -1;
}
#endif /* __FreeBSD__ wait_port support */
/*
* convert_signal_name -- convert a signal name to a signal number
*/
static int
convert_signal_name(const char *signal_name)
{
for (int sig = SIGHUP; sig <= SIGNALMAX; sig++)
if (strcmp(signal_name, signal2str[sig]) == 0)
return sig;
return -1;
}
/*
* log_run -- print run command with arguments
*/
static void
log_run(const char *pid_file, char *cmd, char *argv[])
{
char buff[BUFF_SIZE];
buff[0] = '\0';
size_t cnt = 0;
size_t i = 0;
char *arg = argv[0];
while (arg) {
int ret = util_snprintf(&buff[cnt], BUFF_SIZE - cnt,
" %s", arg);
if (ret < 0) {
CTRLD_LOG("snprintf: %d", errno);
exit(EXIT_FAILURE);
}
cnt += (size_t)ret;
i++;
arg = argv[i];
}
CTRLD_LOG("run %s%s", pid_file, buff);
}
/*
* convert_timeout -- convert a floating point number with an optional suffix
* to unsigned integer: 's' for seconds (the default),
* 'm' for minutes, 'h' for hours or 'd' for days.
*/
static unsigned
convert_timeout(char *str)
{
char *endptr;
float ftimeout = strtof(str, &endptr);
switch (*endptr) {
case 'm':
ftimeout *= S_MINUTE;
break;
case 'h':
ftimeout *= S_HOUR;
break;
case 'd':
ftimeout *= S_DAY;
break;
default:
break;
}
return (unsigned)ftimeout;
}
int
main(int argc, char *argv[])
{
if (argc < 3)
usage();
int ret = 0;
char *pid_file = argv[1];
char *cmd = argv[2];
char buff[BUFF_SIZE];
if (util_snprintf(buff, BUFF_SIZE, "%s.%s.%s.log",
pid_file, cmd, APP_NAME) < 0) {
perror("snprintf");
return -1;
}
log_fh = os_fopen(buff, "a");
if (!log_fh) {
perror(buff);
return -1;
}
if (strcmp(cmd, "exe") == 0) {
if (argc < 4)
usage();
char *command = argv[3];
char **nargv = alloc_argv((unsigned)argc, argv, 3);
if (!nargv) {
CTRLD_LOG("!get_argv");
return 1;
}
log_run(pid_file, command, nargv);
ret = do_run_or_exe(pid_file, command, nargv, 0 /* timeout */);
free(nargv);
} else if (strcmp(cmd, "run") == 0) {
if (argc < 5)
usage();
unsigned timeout = convert_timeout(argv[3]);
char *command = argv[4];
char **nargv = alloc_argv((unsigned)argc, argv, 4);
if (!nargv) {
CTRLD_LOG("!get_argv");
return 1;
}
log_run(pid_file, command, nargv);
ret = do_run_or_exe(pid_file, command, nargv, timeout);
free(nargv);
} else if (strcmp(cmd, "wait") == 0) {
if (argc != 3 && argc != 4)
usage();
int timeout = -1;
if (argc == 4)
timeout = atoi(argv[3]);
CTRLD_LOG("wait %s %d", pid_file, timeout);
ret = do_wait(pid_file, timeout);
} else if (strcmp(cmd, "kill") == 0) {
if (argc != 4)
usage();
int signo = atoi(argv[3]);
if (signo == 0) {
signo = convert_signal_name(argv[3]);
if (signo == -1) {
CTRLD_LOG("Invalid signal name or number"
" (%s)", argv[3]);
return 1;
}
}
CTRLD_LOG("kill %s %s", pid_file, argv[3]);
ret = do_kill(pid_file, signo);
#ifndef __FreeBSD__
} else if (strcmp(cmd, "wait_port") == 0) {
if (argc != 4)
usage();
unsigned short port = (unsigned short)atoi(argv[3]);
CTRLD_LOG("wait_port %s %u", pid_file, port);
ret = do_wait_port(pid_file, port);
#endif
} else {
usage();
}
return ret;
}
| 13,283 | 17.322759 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_locks/obj_locks.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* obj_locks.c -- unit test for PMEMmutex, PMEMrwlock and PMEMcond
*/
#include <sys/param.h>
#include <string.h>
#include "unittest.h"
#include "libpmemobj.h"
#define LAYOUT_NAME "obj_locks"
#define NUM_THREADS 16
#define MAX_FUNC 5
TOID_DECLARE(struct locks, 0);
struct locks {
PMEMobjpool *pop;
PMEMmutex mtx;
PMEMrwlock rwlk;
PMEMcond cond;
int data;
};
struct thread_args {
os_thread_t t;
TOID(struct locks) lock;
int t_id;
};
typedef void *(*fn_lock)(void *arg);
static struct thread_args threads[NUM_THREADS];
/*
* do_mutex_lock -- lock and unlock the mutex
*/
static void *
do_mutex_lock(void *arg)
{
struct thread_args *t = (struct thread_args *)arg;
struct locks *lock = D_RW(t->lock);
pmemobj_mutex_lock(lock->pop, &lock->mtx);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_mutex_unlock(lock->pop, &lock->mtx);
return NULL;
}
/*
* do_rwlock_wrlock -- lock and unlock the write rwlock
*/
static void *
do_rwlock_wrlock(void *arg)
{
struct thread_args *t = (struct thread_args *)arg;
struct locks *lock = D_RW(t->lock);
pmemobj_rwlock_wrlock(lock->pop, &lock->rwlk);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_rwlock_unlock(lock->pop, &lock->rwlk);
return NULL;
}
/*
* do_rwlock_rdlock -- lock and unlock the read rwlock
*/
static void *
do_rwlock_rdlock(void *arg)
{
struct thread_args *t = (struct thread_args *)arg;
struct locks *lock = D_RW(t->lock);
pmemobj_rwlock_rdlock(lock->pop, &lock->rwlk);
pmemobj_rwlock_unlock(lock->pop, &lock->rwlk);
return NULL;
}
/*
* do_cond_signal -- lock block on a condition variables,
* and unlock them by signal
*/
static void *
do_cond_signal(void *arg)
{
struct thread_args *t = (struct thread_args *)arg;
struct locks *lock = D_RW(t->lock);
if (t->t_id == 0) {
pmemobj_mutex_lock(lock->pop, &lock->mtx);
while (lock->data < (NUM_THREADS - 1))
pmemobj_cond_wait(lock->pop, &lock->cond,
&lock->mtx);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_mutex_unlock(lock->pop, &lock->mtx);
} else {
pmemobj_mutex_lock(lock->pop, &lock->mtx);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_cond_signal(lock->pop, &lock->cond);
pmemobj_mutex_unlock(lock->pop, &lock->mtx);
}
return NULL;
}
/*
* do_cond_broadcast -- lock block on a condition variables and unlock
* by broadcasting
*/
static void *
do_cond_broadcast(void *arg)
{
struct thread_args *t = (struct thread_args *)arg;
struct locks *lock = D_RW(t->lock);
if (t->t_id < (NUM_THREADS / 2)) {
pmemobj_mutex_lock(lock->pop, &lock->mtx);
while (lock->data < (NUM_THREADS / 2))
pmemobj_cond_wait(lock->pop, &lock->cond,
&lock->mtx);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_mutex_unlock(lock->pop, &lock->mtx);
} else {
pmemobj_mutex_lock(lock->pop, &lock->mtx);
lock->data++;
pmemobj_persist(lock->pop, &lock->data, sizeof(lock->data));
pmemobj_cond_broadcast(lock->pop, &lock->cond);
pmemobj_mutex_unlock(lock->pop, &lock->mtx);
}
return NULL;
}
static fn_lock do_lock[MAX_FUNC] = {do_mutex_lock, do_rwlock_wrlock,
do_rwlock_rdlock, do_cond_signal,
do_cond_broadcast};
/*
* do_lock_init -- initialize all types of locks
*/
static void
do_lock_init(struct locks *lock)
{
pmemobj_mutex_zero(lock->pop, &lock->mtx);
pmemobj_rwlock_zero(lock->pop, &lock->rwlk);
pmemobj_cond_zero(lock->pop, &lock->cond);
}
/*
* do_lock_mt -- perform multithread lock operations
*/
static void
do_lock_mt(TOID(struct locks) lock, unsigned f_num)
{
D_RW(lock)->data = 0;
for (int i = 0; i < NUM_THREADS; ++i) {
threads[i].lock = lock;
threads[i].t_id = i;
THREAD_CREATE(&threads[i].t, NULL, do_lock[f_num],
&threads[i]);
}
for (int i = 0; i < NUM_THREADS; ++i)
THREAD_JOIN(&threads[i].t, NULL);
/*
* If all threads passed function properly and used every lock, there
* should be every element in data array incremented exactly one time
* by every thread.
*/
UT_ASSERT((D_RO(lock)->data == NUM_THREADS) ||
(D_RO(lock)->data == 0));
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_locks");
if (argc != 2)
UT_FATAL("usage: %s [file]", argv[0]);
PMEMobjpool *pop;
if ((pop = pmemobj_create(argv[1], LAYOUT_NAME, PMEMOBJ_MIN_POOL,
S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create");
TOID(struct locks) lock;
POBJ_ALLOC(pop, &lock, struct locks, sizeof(struct locks), NULL, NULL);
D_RW(lock)->pop = pop;
do_lock_init(D_RW(lock));
for (unsigned i = 0; i < MAX_FUNC; i++)
do_lock_mt(lock, i);
POBJ_FREE(&lock);
pmemobj_close(pop);
DONE(NULL);
}
| 4,821 | 22.99005 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/log_basic/log_basic.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* log_basic.c -- unit test for pmemlog_*
*
* usage: log_basic file operation:...
*
* operations are 'l' or 'h' or 'f' or 'c' or 'n' or 'a' or 'v' or 't'
* or 'r' or 'w'
*
*/
#include "unittest.h"
#include "../libpmemlog/log.h"
/*
* do_nbyte -- call pmemlog_nbyte() & print result
*/
static void
do_nbyte(PMEMlogpool *plp)
{
size_t nbyte = pmemlog_nbyte(plp);
UT_OUT("usable size: %zu", nbyte);
}
/*
* do_append -- call pmemlog_append() & print result
*/
static void
do_append(PMEMlogpool *plp)
{
const char *str[6] = {
"1st test string\n",
"2nd test string\n",
"3rd test string\n",
"4th test string\n",
"5th test string\n",
"6th test string\n"
};
for (int i = 0; i < 6; ++i) {
int rv = pmemlog_append(plp, str[i], strlen(str[i]));
switch (rv) {
case 0:
UT_OUT("append str[%i] %s", i, str[i]);
break;
case -1:
UT_OUT("!append str[%i] %s", i, str[i]);
break;
default:
UT_OUT("!append: wrong return value");
break;
}
}
}
/*
* do_appendv -- call pmemlog_appendv() & print result
*/
static void
do_appendv(PMEMlogpool *plp)
{
struct iovec iov[9] = {
{
.iov_base = "1st test string\n",
.iov_len = 16
},
{
.iov_base = "2nd test string\n",
.iov_len = 16
},
{
.iov_base = "3rd test string\n",
.iov_len = 16
},
{
.iov_base = "4th test string\n",
.iov_len = 16
},
{
.iov_base = "5th test string\n",
.iov_len = 16
},
{
.iov_base = "6th test string\n",
.iov_len = 16
},
{
.iov_base = "7th test string\n",
.iov_len = 16
},
{
.iov_base = "8th test string\n",
.iov_len = 16
},
{
.iov_base = "9th test string\n",
.iov_len = 16
}
};
int rv = pmemlog_appendv(plp, iov, 9);
switch (rv) {
case 0:
UT_OUT("appendv");
break;
case -1:
UT_OUT("!appendv");
break;
default:
UT_OUT("!appendv: wrong return value");
break;
}
rv = pmemlog_appendv(plp, iov, 0);
UT_ASSERTeq(rv, 0);
errno = 0;
rv = pmemlog_appendv(plp, iov, -3);
UT_ASSERTeq(errno, EINVAL);
UT_ASSERTeq(rv, -1);
}
/*
* do_tell -- call pmemlog_tell() & print result
*/
static void
do_tell(PMEMlogpool *plp)
{
os_off_t tell = pmemlog_tell(plp);
UT_OUT("tell %zu", tell);
}
/*
* do_rewind -- call pmemlog_rewind() & print result
*/
static void
do_rewind(PMEMlogpool *plp)
{
pmemlog_rewind(plp);
UT_OUT("rewind");
}
/*
* printit -- print out the 'buf' of length 'len'.
*
* It is a walker function for pmemlog_walk
*/
static int
printit(const void *buf, size_t len, void *arg)
{
char *str = MALLOC(len + 1);
strncpy(str, buf, len);
str[len] = '\0';
UT_OUT("%s", str);
FREE(str);
return 1;
}
/*
* do_walk -- call pmemlog_walk() & print result
*
* pmemlog_walk() is called twice: for chunk size 0 and 16
*/
static void
do_walk(PMEMlogpool *plp)
{
pmemlog_walk(plp, 0, printit, NULL);
UT_OUT("walk all at once");
pmemlog_walk(plp, 16, printit, NULL);
UT_OUT("walk by 16");
}
/*
* do_create -- call pmemlog_create() and check if it was successful
*/
static PMEMlogpool *
do_create(const char *path)
{
PMEMlogpool *_plp = pmemlog_create(path, 0, S_IWUSR | S_IRUSR);
if (_plp == NULL)
UT_FATAL("!pmemlog_create: %s", path);
return _plp;
}
/*
* do_fault_injection -- inject error in first Malloc() in pmemlog_create()
*/
static void
do_fault_injection(PMEMlogpool *plp, const char *path)
{
if (pmemlog_fault_injection_enabled()) {
pmemlog_inject_fault_at(PMEM_MALLOC, 1,
"log_runtime_init");
plp = pmemlog_create(path, 0, S_IWUSR | S_IRUSR);
UT_ASSERTeq(plp, NULL);
UT_ASSERTeq(errno, ENOMEM);
}
}
/*
* do_close -- call pmemlog_close()
*/
static void
do_close(PMEMlogpool *plp)
{
pmemlog_close(plp);
}
/*
* do_check -- call pmemlog_check() and check consistency
*/
static void
do_check(const char *path)
{
int result = pmemlog_check(path);
if (result < 0)
UT_OUT("!%s: pmemlog_check", path);
else if (result == 0)
UT_OUT("%s: pmemlog_check: not consistent", path);
}
int
main(int argc, char *argv[])
{
PMEMlogpool *plp;
START(argc, argv, "log_basic");
if (argc < 3)
UT_FATAL("usage: %s file-name op:l|h|f|c|n|a|v|t|r|w", argv[0]);
const char *path = argv[1];
/* go through all arguments one by one */
for (int arg = 2; arg < argc; arg++) {
/* Scan the character of each argument. */
if (strchr("lhfcnavtrw", argv[arg][0]) == NULL ||
argv[arg][1] != '\0')
UT_FATAL("op must be l or h or f or c or n or a or v\
or t or r or w");
switch (argv[arg][0]) {
case 'c':
plp = do_create(path);
break;
case 'n':
do_nbyte(plp);
break;
case 'a':
do_append(plp);
break;
case 'v':
do_appendv(plp);
break;
case 't':
do_tell(plp);
break;
case 'r':
do_rewind(plp);
break;
case 'w':
do_walk(plp);
break;
case 'f':
do_fault_injection(plp, path);
break;
case 'l':
do_close(plp);
break;
case 'h':
do_check(path);
break;
}
}
DONE(NULL);
}
| 5,015 | 16.296552 | 75 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/libpmempool_feature/common.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2019, Intel Corporation
#
# src/test/libpmempool_feature/common.sh -- common part of libpmempool_feature tests
#
POOL=$DIR/pool.obj
OUT=out${UNITTEST_NUM}.log
LOG=grep${UNITTEST_NUM}.log
QUERY_PATTERN="query"
ERROR_PATTERN="<1> \\[feature.c:.*\\]"
exit_func=expect_normal_exit
sds_enabled=$(is_ndctl_enabled ./libpmempool_feature$EXESUFFIX; echo $?)
# libpmempool_feature_query_abnormal -- query feature with expected
# abnormal result
#
# usage: libpmempool_feature_query_abnormal <enum-pmempool_feature>
function libpmempool_feature_query_abnormal() {
# query feature
expect_abnormal_exit ./libpmempool_feature$EXESUFFIX $POOL q $1
if [ -f "$PMEMPOOL_LOG_FILE" ]; then
cat $PMEMPOOL_LOG_FILE | grep "$ERROR_PATTERN" >> $LOG
fi
}
# libpmempool_feature_query -- query feature
#
# usage: libpmempool_feature_query <enum-pmempool_feature>
function libpmempool_feature_query() {
# query feature
expect_normal_exit ./libpmempool_feature$EXESUFFIX $POOL q $1
cat $OUT | grep "$QUERY_PATTERN" >> $LOG
# verify query with pmempool info
set +e
count=$(expect_normal_exit $PMEMPOOL$EXESUFFIX info $POOL | grep -c "$1")
set -e
if [ "$count" = "0" ]; then
echo "pmempool info: $1 is NOT set" >> $LOG
else
echo "pmempool info: $1 is set" >> $LOG
fi
# check if pool is still valid
expect_normal_exit $PMEMPOOL$EXESUFFIX check $POOL >> /dev/null
}
# libpmempool_feature_enable -- enable feature
#
# usage: libpmempool_feature_enable <enum-pmempool_feature> [no-query]
function libpmempool_feature_enable() {
$exit_func ./libpmempool_feature$EXESUFFIX $POOL e $1
if [ "$exit_func" == "expect_abnormal_exit" ]; then
if [ -f "$PMEMPOOL_LOG_FILE" ]; then
cat $PMEMPOOL_LOG_FILE | grep "$ERROR_PATTERN" >> $LOG
fi
fi
if [ "x$2" != "xno-query" ]; then
libpmempool_feature_query $1
fi
}
# libpmempool_feature_disable -- disable feature
#
# usage: libpmempool_feature_disable <enum-pmempool_feature> [no-query]
function libpmempool_feature_disable() {
$exit_func ./libpmempool_feature$EXESUFFIX $POOL d $1
if [ "$exit_func" == "expect_abnormal_exit" ]; then
if [ -f "$PMEMPOOL_LOG_FILE" ]; then
cat $PMEMPOOL_LOG_FILE | grep "$ERROR_PATTERN" >> $LOG
fi
fi
if [ "x$2" != "xno-query" ]; then
libpmempool_feature_query $1
fi
}
| 2,340 | 27.204819 | 84 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/libpmempool_feature/libpmempool_feature.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* libpmempool_feature -- pmempool_feature_(enable|disable|query) test
*
*/
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include "libpmempool.h"
#include "pool_hdr.h"
#include "unittest.h"
#define EMPTY_FLAGS 0
/*
* print_usage -- print usage of program
*/
static void
print_usage(const char *name)
{
UT_OUT("usage: %s <pool_path> (e|d|q) <feature-name>", name);
UT_OUT("feature-name: SINGLEHDR, CKSUM_2K, SHUTDOWN_STATE");
}
/*
* str2pmempool_feature -- convert feature name to pmempool_feature enum
*/
static enum pmempool_feature
str2pmempool_feature(const char *app, const char *str)
{
uint32_t fval = util_str2pmempool_feature(str);
if (fval == UINT32_MAX) {
print_usage(app);
UT_FATAL("unknown feature: %s", str);
}
return (enum pmempool_feature)fval;
}
int
main(int argc, char *argv[])
{
START(argc, argv, "libpmempool_feature");
if (argc < 4) {
print_usage(argv[0]);
UT_FATAL("insufficient number of arguments: %d", argc - 1);
}
const char *path = argv[1];
char cmd = argv[2][0];
enum pmempool_feature feature = str2pmempool_feature(argv[0], argv[3]);
int ret;
switch (cmd) {
case 'e':
return pmempool_feature_enable(path, feature, EMPTY_FLAGS);
case 'd':
return pmempool_feature_disable(path, feature, EMPTY_FLAGS);
case 'q':
ret = pmempool_feature_query(path, feature, EMPTY_FLAGS);
if (ret < 0)
return 1;
UT_OUT("query %s result is %d", argv[3], ret);
return 0;
default:
print_usage(argv[0]);
UT_FATAL("unknown command: %c", cmd);
}
DONE(NULL);
}
| 1,622 | 20.077922 | 72 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_tx_flow/obj_tx_flow.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* obj_tx_flow.c -- unit test for transaction flow
*/
#include "unittest.h"
#include "obj.h"
#define LAYOUT_NAME "direct"
#define TEST_VALUE_A 5
#define TEST_VALUE_B 10
#define TEST_VALUE_C 15
#define OPS_NUM 9
TOID_DECLARE(struct test_obj, 1);
struct test_obj {
int a;
int b;
int c;
};
static void
do_tx_macro_commit(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
TX_BEGIN(pop) {
D_RW(*obj)->a = TEST_VALUE_A;
} TX_ONCOMMIT {
UT_ASSERT(D_RW(*obj)->a == TEST_VALUE_A);
D_RW(*obj)->b = TEST_VALUE_B;
} TX_ONABORT { /* not called */
D_RW(*obj)->a = TEST_VALUE_B;
} TX_FINALLY {
UT_ASSERT(D_RW(*obj)->b == TEST_VALUE_B);
D_RW(*obj)->c = TEST_VALUE_C;
} TX_END
}
static void
do_tx_macro_abort(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
D_RW(*obj)->a = TEST_VALUE_A;
D_RW(*obj)->b = TEST_VALUE_B;
TX_BEGIN(pop) {
TX_ADD(*obj);
D_RW(*obj)->a = TEST_VALUE_B;
pmemobj_tx_abort(EINVAL);
D_RW(*obj)->b = TEST_VALUE_A;
} TX_ONCOMMIT { /* not called */
D_RW(*obj)->a = TEST_VALUE_B;
} TX_ONABORT {
UT_ASSERT(D_RW(*obj)->a == TEST_VALUE_A);
UT_ASSERT(D_RW(*obj)->b == TEST_VALUE_B);
D_RW(*obj)->b = TEST_VALUE_B;
} TX_FINALLY {
UT_ASSERT(D_RW(*obj)->b == TEST_VALUE_B);
D_RW(*obj)->c = TEST_VALUE_C;
} TX_END
}
static void
do_tx_macro_commit_nested(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
TX_BEGIN(pop) {
TX_BEGIN(pop) {
D_RW(*obj)->a = TEST_VALUE_A;
} TX_ONCOMMIT {
UT_ASSERT(D_RW(*obj)->a == TEST_VALUE_A);
D_RW(*obj)->b = TEST_VALUE_B;
} TX_END
} TX_ONCOMMIT {
D_RW(*obj)->c = TEST_VALUE_C;
} TX_END
}
static void
do_tx_macro_abort_nested(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
volatile int a = 0;
volatile int b = 0;
volatile int c = 0;
D_RW(*obj)->a = TEST_VALUE_A;
D_RW(*obj)->b = TEST_VALUE_B;
TX_BEGIN(pop) {
TX_ADD(*obj);
D_RW(*obj)->a = TEST_VALUE_B;
a = TEST_VALUE_C;
TX_BEGIN(pop) {
D_RW(*obj)->b = TEST_VALUE_C;
a = TEST_VALUE_A;
pmemobj_tx_abort(EINVAL);
a = TEST_VALUE_B;
} TX_ONCOMMIT { /* not called */
a = TEST_VALUE_C;
} TX_ONABORT {
UT_ASSERT(a == TEST_VALUE_A);
b = TEST_VALUE_B;
} TX_FINALLY {
UT_ASSERT(b == TEST_VALUE_B);
c = TEST_VALUE_C;
} TX_END
a = TEST_VALUE_B;
} TX_ONCOMMIT { /* not called */
UT_ASSERT(a == TEST_VALUE_A);
c = TEST_VALUE_C;
} TX_ONABORT {
UT_ASSERT(a == TEST_VALUE_A);
UT_ASSERT(b == TEST_VALUE_B);
UT_ASSERT(c == TEST_VALUE_C);
b = TEST_VALUE_A;
} TX_FINALLY {
UT_ASSERT(b == TEST_VALUE_A);
D_RW(*obj)->c = TEST_VALUE_C;
a = TEST_VALUE_B;
} TX_END
UT_ASSERT(a == TEST_VALUE_B);
}
static void
do_tx_macro_abort_nested_begin(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
errno = 0;
TX_BEGIN(pop) {
D_RW(*obj)->a = TEST_VALUE_A;
D_RW(*obj)->b = TEST_VALUE_B;
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
TX_BEGIN((PMEMobjpool *)(uintptr_t)7) {
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
UT_ASSERT(errno == EINVAL);
} TX_ONABORT {
D_RW(*obj)->c = TEST_VALUE_C;
} TX_ONCOMMIT { /* not called */
D_RW(*obj)->a = TEST_VALUE_B;
} TX_END
}
static void
do_tx_commit(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
D_RW(*obj)->a = TEST_VALUE_A;
TX_ADD(*obj);
D_RW(*obj)->b = TEST_VALUE_B;
pmemobj_tx_commit();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONCOMMIT);
D_RW(*obj)->c = TEST_VALUE_C;
pmemobj_tx_end();
}
static void
do_tx_commit_nested(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
TX_ADD(*obj);
D_RW(*obj)->a = TEST_VALUE_A;
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
TX_ADD(*obj);
D_RW(*obj)->b = TEST_VALUE_B;
pmemobj_tx_commit();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONCOMMIT);
pmemobj_tx_end();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_WORK);
pmemobj_tx_commit();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONCOMMIT);
D_RW(*obj)->c = TEST_VALUE_C;
pmemobj_tx_end();
}
static void
do_tx_abort(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
D_RW(*obj)->a = TEST_VALUE_A;
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
D_RW(*obj)->b = TEST_VALUE_B;
TX_ADD(*obj);
D_RW(*obj)->a = 0;
pmemobj_tx_abort(EINVAL);
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONABORT);
D_RW(*obj)->c = TEST_VALUE_C;
pmemobj_tx_end();
}
static void
do_tx_abort_nested(PMEMobjpool *pop, TOID(struct test_obj) *obj)
{
D_RW(*obj)->a = TEST_VALUE_A;
D_RW(*obj)->b = TEST_VALUE_B;
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
TX_ADD(*obj);
D_RW(*obj)->a = 0;
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
TX_ADD(*obj);
D_RW(*obj)->b = 0;
pmemobj_tx_abort(EINVAL);
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONABORT);
pmemobj_tx_end();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONABORT);
D_RW(*obj)->c = TEST_VALUE_C;
pmemobj_tx_end();
}
typedef void (*fn_op)(PMEMobjpool *pop, TOID(struct test_obj) *obj);
static fn_op tx_op[OPS_NUM] = {do_tx_macro_commit, do_tx_macro_abort,
do_tx_macro_commit_nested, do_tx_macro_abort_nested,
do_tx_macro_abort_nested_begin, do_tx_commit,
do_tx_commit_nested, do_tx_abort, do_tx_abort_nested};
static void
do_tx_process(PMEMobjpool *pop)
{
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_WORK);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONCOMMIT);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_FINALLY);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_NONE);
pmemobj_tx_end();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_NONE);
}
static void
do_tx_process_nested(PMEMobjpool *pop)
{
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_WORK);
pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONCOMMIT);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_FINALLY);
pmemobj_tx_end();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_WORK);
pmemobj_tx_abort(EINVAL);
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_ONABORT);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_FINALLY);
pmemobj_tx_process();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_NONE);
pmemobj_tx_end();
UT_ASSERT(pmemobj_tx_stage() == TX_STAGE_NONE);
}
static void
do_fault_injection(PMEMobjpool *pop)
{
if (!pmemobj_fault_injection_enabled())
return;
pmemobj_inject_fault_at(PMEM_MALLOC, 1, "pmemobj_tx_begin");
int ret = pmemobj_tx_begin(pop, NULL, TX_PARAM_NONE);
UT_ASSERTne(ret, 0);
UT_ASSERTeq(errno, ENOMEM);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_tx_flow");
if (argc != 3)
UT_FATAL("usage: %s [file]", argv[0]);
PMEMobjpool *pop;
if ((pop = pmemobj_create(argv[2], LAYOUT_NAME, PMEMOBJ_MIN_POOL,
S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create");
TOID(struct test_obj) obj;
POBJ_ZNEW(pop, &obj, struct test_obj);
for (int i = 0; i < OPS_NUM; i++) {
D_RW(obj)->a = 0;
D_RW(obj)->b = 0;
D_RW(obj)->c = 0;
tx_op[i](pop, &obj);
UT_ASSERT(D_RO(obj)->a == TEST_VALUE_A);
UT_ASSERT(D_RO(obj)->b == TEST_VALUE_B);
UT_ASSERT(D_RO(obj)->c == TEST_VALUE_C);
}
switch (argv[1][0]) {
case 't':
do_tx_process(pop);
do_tx_process_nested(pop);
break;
case 'f':
do_fault_injection(pop);
break;
default:
UT_FATAL("usage: %s [t|f]", argv[0]);
}
pmemobj_close(pop);
DONE(NULL);
}
| 7,445 | 23.574257 | 76 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_persist/pmem2_persist.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* pmem2_map.c -- pmem2_get_[flush|drain|persist]_fn unittests
*/
#include "mmap.h"
#include "persist.h"
#include "pmem2_arch.h"
#include "out.h"
#include "unittest.h"
static int n_flushes = 0;
static int n_fences = 0;
static int n_msynces = 0;
/*
* mock_flush -- count flush calls in the test
*/
static void
mock_flush(const void *addr, size_t len)
{
++n_flushes;
}
/*
* mock_drain -- count drain calls in the test
*/
static void
mock_drain(void)
{
++n_fences;
}
/*
* pmem2_arch_init -- redefine libpmem2 function
*/
void
pmem2_arch_init(struct pmem2_arch_info *info)
{
info->flush = mock_flush;
info->fence = mock_drain;
}
/*
* pmem2_map_find -- redefine libpmem2 function
*/
struct pmem2_map *
pmem2_map_find(const void *addr, size_t len)
{
static struct pmem2_map cur;
cur.addr = (void *)ALIGN_DOWN((size_t)addr, Pagesize);
if ((size_t)cur.addr < (size_t)addr)
len += (size_t)addr - (size_t)cur.addr;
cur.reserved_length = ALIGN_UP(len, Pagesize);
return &cur;
}
/*
* pmem2_flush_file_buffers_os -- redefine libpmem2 function
*/
int
pmem2_flush_file_buffers_os(struct pmem2_map *map, const void *addr, size_t len,
int autorestart)
{
UT_ASSERTeq((uintptr_t)addr % Pagesize, 0);
++n_msynces;
return 0;
}
/*
* prepare_map -- fill pmem2_map in minimal scope
*/
static void
prepare_map(struct pmem2_map *map)
{
const size_t length = 20 * MEGABYTE + 5 * KILOBYTE;
map->content_length = length;
map->addr = MALLOC(length);
}
/*
* counters_check_n_reset -- check values of counts of calls of persist
* functions in the test and reset them
*/
static void
counters_check_n_reset(int msynces, int flushes, int fences)
{
UT_ASSERTeq(n_msynces, msynces);
UT_ASSERTeq(n_flushes, flushes);
UT_ASSERTeq(n_fences, fences);
n_msynces = 0;
n_flushes = 0;
n_fences = 0;
}
/*
* do_persist -- call persist function according to a granularity
*/
static void
do_persist(struct pmem2_map *map, enum pmem2_granularity granularity)
{
map->effective_granularity = granularity;
pmem2_set_flush_fns(map);
pmem2_persist_fn func = pmem2_get_persist_fn(map);
UT_ASSERTne(func, NULL);
func(map->addr, map->content_length);
}
/*
* do_flush -- call flush function according to a granularity
*/
static void
do_flush(struct pmem2_map *map, enum pmem2_granularity granularity)
{
map->effective_granularity = granularity;
pmem2_set_flush_fns(map);
pmem2_flush_fn func = pmem2_get_flush_fn(map);
UT_ASSERTne(func, NULL);
func(map->addr, map->content_length);
}
/*
* do_drain -- call drain function according to a granularity
*/
static void
do_drain(struct pmem2_map *map, enum pmem2_granularity granularity)
{
map->effective_granularity = granularity;
pmem2_set_flush_fns(map);
pmem2_drain_fn func = pmem2_get_drain_fn(map);
UT_ASSERTne(func, NULL);
func();
}
/*
* test_get_persist_funcs -- test getting pmem2 persist functions
*/
static int
test_get_persist_funcs(const struct test_case *tc, int argc, char *argv[])
{
struct pmem2_map map;
prepare_map(&map);
do_persist(&map, PMEM2_GRANULARITY_PAGE);
counters_check_n_reset(1, 0, 0);
do_persist(&map, PMEM2_GRANULARITY_CACHE_LINE);
counters_check_n_reset(0, 1, 1);
do_persist(&map, PMEM2_GRANULARITY_BYTE);
counters_check_n_reset(0, 0, 1);
FREE(map.addr);
return 0;
}
/*
* test_get_flush_funcs -- test getting pmem2 flush functions
*/
static int
test_get_flush_funcs(const struct test_case *tc, int argc, char *argv[])
{
struct pmem2_map map;
prepare_map(&map);
do_flush(&map, PMEM2_GRANULARITY_PAGE);
counters_check_n_reset(1, 0, 0);
do_flush(&map, PMEM2_GRANULARITY_CACHE_LINE);
counters_check_n_reset(0, 1, 0);
do_flush(&map, PMEM2_GRANULARITY_BYTE);
counters_check_n_reset(0, 0, 0);
FREE(map.addr);
return 0;
}
/*
* test_get_drain_funcs -- test getting pmem2 drain functions
*/
static int
test_get_drain_funcs(const struct test_case *tc, int argc, char *argv[])
{
struct pmem2_map map;
prepare_map(&map);
do_drain(&map, PMEM2_GRANULARITY_PAGE);
counters_check_n_reset(0, 0, 0);
do_drain(&map, PMEM2_GRANULARITY_CACHE_LINE);
counters_check_n_reset(0, 0, 1);
do_drain(&map, PMEM2_GRANULARITY_BYTE);
counters_check_n_reset(0, 0, 1);
FREE(map.addr);
return 0;
}
/*
* test_cases -- available test cases
*/
static struct test_case test_cases[] = {
TEST_CASE(test_get_persist_funcs),
TEST_CASE(test_get_flush_funcs),
TEST_CASE(test_get_drain_funcs),
};
#define NTESTS (sizeof(test_cases) / sizeof(test_cases[0]))
int
main(int argc, char *argv[])
{
START(argc, argv, "pmem2_persist");
pmem2_persist_init();
util_init();
TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS);
DONE(NULL);
}
| 4,727 | 19.37931 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_persist/TESTS.py
|
#!../env.py
#
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019, Intel Corporation
import testframework as t
from testframework import granularity as g
@g.no_testdir()
class PMEM2_PERSIST(t.Test):
test_type = t.Short
def run(self, ctx):
ctx.exec('pmem2_persist', self.test_case)
class TEST0(PMEM2_PERSIST):
"""test getting pmem2 persist functions"""
test_case = "test_get_persist_funcs"
class TEST1(PMEM2_PERSIST):
"""test getting pmem2 flush functions"""
test_case = "test_get_flush_funcs"
class TEST2(PMEM2_PERSIST):
"""test getting pmem2 drain functions"""
test_case = "test_get_drain_funcs"
| 652 | 20.064516 | 49 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/util_pool_hdr/util_pool_hdr.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* util_pool_hdr.c -- unit test for pool_hdr layout and default values
*
* This test should be modified after every layout change. It's here to prevent
* any accidental layout changes.
*/
#include "util.h"
#include "unittest.h"
#include "set.h"
#include "pool_hdr.h"
#define POOL_HDR_SIG_LEN_V1 (8)
#define POOL_HDR_UNUSED_LEN_V1 (1904)
#define POOL_HDR_UNUSED2_LEN_V1 (1976)
#define POOL_HDR_2K_CHECKPOINT (2048UL)
#define FEATURES_T_SIZE_V1 (12)
#define ARCH_FLAGS_SIZE_V1 (16)
#define ARCH_FLAGS_RESERVED_LEN_V1 (4)
#define SHUTDOWN_STATE_SIZE_V1 (64)
#define SHUTDOWN_STATE_RESERVED_LEN_V1 (39)
/*
* test_layout -- test pool_hdr layout
*/
static void
test_layout()
{
ASSERT_ALIGNED_BEGIN(struct pool_hdr);
ASSERT_ALIGNED_FIELD(struct pool_hdr, signature);
ASSERT_FIELD_SIZE(signature, POOL_HDR_SIG_LEN_V1);
ASSERT_ALIGNED_FIELD(struct pool_hdr, major);
ASSERT_ALIGNED_FIELD(struct pool_hdr, features);
ASSERT_ALIGNED_FIELD(struct pool_hdr, poolset_uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, prev_part_uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, next_part_uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, prev_repl_uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, next_repl_uuid);
ASSERT_ALIGNED_FIELD(struct pool_hdr, crtime);
ASSERT_ALIGNED_FIELD(struct pool_hdr, arch_flags);
ASSERT_ALIGNED_FIELD(struct pool_hdr, unused);
ASSERT_FIELD_SIZE(unused, POOL_HDR_UNUSED_LEN_V1);
ASSERT_OFFSET_CHECKPOINT(struct pool_hdr, POOL_HDR_2K_CHECKPOINT);
ASSERT_ALIGNED_FIELD(struct pool_hdr, unused2);
ASSERT_FIELD_SIZE(unused2, POOL_HDR_UNUSED2_LEN_V1);
ASSERT_ALIGNED_FIELD(struct pool_hdr, sds);
ASSERT_ALIGNED_FIELD(struct pool_hdr, checksum);
#if PMEM_PAGESIZE > 4096
ASSERT_ALIGNED_FIELD(struct pool_hdr, align_pad);
#endif
ASSERT_ALIGNED_CHECK(struct pool_hdr);
ASSERT_ALIGNED_BEGIN(features_t);
ASSERT_ALIGNED_FIELD(features_t, compat);
ASSERT_ALIGNED_FIELD(features_t, incompat);
ASSERT_ALIGNED_FIELD(features_t, ro_compat);
ASSERT_ALIGNED_CHECK(features_t);
UT_COMPILE_ERROR_ON(sizeof(features_t) != FEATURES_T_SIZE_V1);
ASSERT_ALIGNED_BEGIN(struct arch_flags);
ASSERT_ALIGNED_FIELD(struct arch_flags, alignment_desc);
ASSERT_ALIGNED_FIELD(struct arch_flags, machine_class);
ASSERT_ALIGNED_FIELD(struct arch_flags, data);
ASSERT_ALIGNED_FIELD(struct arch_flags, reserved);
ASSERT_FIELD_SIZE(reserved, ARCH_FLAGS_RESERVED_LEN_V1);
ASSERT_ALIGNED_FIELD(struct arch_flags, machine);
ASSERT_ALIGNED_CHECK(struct arch_flags);
UT_COMPILE_ERROR_ON(sizeof(struct arch_flags) != ARCH_FLAGS_SIZE_V1);
ASSERT_ALIGNED_BEGIN(struct shutdown_state);
ASSERT_ALIGNED_FIELD(struct shutdown_state, usc);
ASSERT_ALIGNED_FIELD(struct shutdown_state, uuid);
ASSERT_ALIGNED_FIELD(struct shutdown_state, dirty);
ASSERT_ALIGNED_FIELD(struct shutdown_state, reserved);
ASSERT_FIELD_SIZE(reserved, SHUTDOWN_STATE_RESERVED_LEN_V1);
ASSERT_ALIGNED_FIELD(struct shutdown_state, checksum);
ASSERT_ALIGNED_CHECK(struct shutdown_state);
UT_COMPILE_ERROR_ON(sizeof(struct shutdown_state) !=
SHUTDOWN_STATE_SIZE_V1);
}
/* incompat features - final values */
#define POOL_FEAT_SINGLEHDR_FINAL 0x0001U
#define POOL_FEAT_CKSUM_2K_FINAL 0x0002U
#define POOL_FEAT_SDS_FINAL 0x0004U
/* incompat features effective values */
#if defined(_WIN32) || NDCTL_ENABLED
#ifdef SDS_ENABLED
#define POOL_E_FEAT_SDS_FINAL POOL_FEAT_SDS_FINAL
#else
#define POOL_E_FEAT_SDS_FINAL 0x0000U /* empty */
#endif
#else
/*
* shutdown state support on Linux requires root access on kernel < 4.20 with
* ndctl < 63 so it is disabled by default
*/
#define POOL_E_FEAT_SDS_FINAL 0x0000U /* empty */
#endif
#define POOL_FEAT_INCOMPAT_DEFAULT_V1 \
(POOL_FEAT_CKSUM_2K_FINAL | POOL_E_FEAT_SDS_FINAL)
#ifdef _WIN32
#define SDS_AT_CREATE_EXPECTED 1
#else
#define SDS_AT_CREATE_EXPECTED 0
#endif
/*
* test_default_values -- test default values
*/
static void
test_default_values()
{
UT_COMPILE_ERROR_ON(POOL_FEAT_SINGLEHDR != POOL_FEAT_SINGLEHDR_FINAL);
UT_COMPILE_ERROR_ON(POOL_FEAT_CKSUM_2K != POOL_FEAT_CKSUM_2K_FINAL);
UT_COMPILE_ERROR_ON(POOL_FEAT_SDS != POOL_FEAT_SDS_FINAL);
UT_COMPILE_ERROR_ON(SDS_at_create != SDS_AT_CREATE_EXPECTED);
UT_COMPILE_ERROR_ON(POOL_FEAT_INCOMPAT_DEFAULT !=
POOL_FEAT_INCOMPAT_DEFAULT_V1);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "util_pool_hdr");
test_layout();
test_default_values();
DONE(NULL);
}
| 4,508 | 30.531469 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/util_map_proc/util_map_proc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* util_map_proc.c -- unit test for util_map() /proc parsing
*
* usage: util_map_proc maps_file len [len]...
*/
#define _GNU_SOURCE
#include <dlfcn.h>
#include "unittest.h"
#include "util.h"
#include "mmap.h"
#define GIGABYTE ((uintptr_t)1 << 30)
#define TERABYTE ((uintptr_t)1 << 40)
int
main(int argc, char *argv[])
{
START(argc, argv, "util_map_proc");
util_init();
util_mmap_init();
if (argc < 3)
UT_FATAL("usage: %s maps_file len [len]...", argv[0]);
Mmap_mapfile = argv[1];
UT_OUT("redirecting " OS_MAPFILE " to %s", Mmap_mapfile);
for (int arg = 2; arg < argc; arg++) {
size_t len = (size_t)strtoull(argv[arg], NULL, 0);
size_t align = 2 * MEGABYTE;
if (len >= 2 * GIGABYTE)
align = GIGABYTE;
void *h1 =
util_map_hint_unused((void *)TERABYTE, len, GIGABYTE);
void *h2 = util_map_hint(len, 0);
if (h1 != MAP_FAILED && h1 != NULL)
UT_ASSERTeq((uintptr_t)h1 & (GIGABYTE - 1), 0);
if (h2 != MAP_FAILED && h2 != NULL)
UT_ASSERTeq((uintptr_t)h2 & (align - 1), 0);
if (h1 == NULL) /* XXX portability */
UT_OUT("len %zu: (nil) %p", len, h2);
else if (h2 == NULL)
UT_OUT("len %zu: %p (nil)", len, h1);
else
UT_OUT("len %zu: %p %p", len, h1, h2);
}
util_mmap_fini();
DONE(NULL);
}
| 1,335 | 21.644068 | 60 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/win_lists/win_lists.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* Copyright (c) 2016, Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* win_lists.c -- test list routines used in windows implementation
*/
#include "unittest.h"
#include "queue.h"
typedef struct TEST_LIST_NODE {
PMDK_LIST_ENTRY(TEST_LIST_NODE) ListEntry;
int dummy;
} *PTEST_LIST_NODE;
PMDK_LIST_HEAD(TestList, TEST_LIST_NODE);
static void
dump_list(struct TestList *head)
{
PTEST_LIST_NODE pNode = NULL;
pNode = (PTEST_LIST_NODE)PMDK_LIST_FIRST(head);
while (pNode != NULL) {
UT_OUT("Node value: %d", pNode->dummy);
pNode = (PTEST_LIST_NODE)PMDK_LIST_NEXT(pNode, ListEntry);
}
}
static int
get_list_count(struct TestList *head)
{
PTEST_LIST_NODE pNode = NULL;
int listCount = 0;
pNode = (PTEST_LIST_NODE)PMDK_LIST_FIRST(head);
while (pNode != NULL) {
listCount++;
pNode = (PTEST_LIST_NODE)PMDK_LIST_NEXT(pNode, ListEntry);
}
return listCount;
}
/*
* test_list - Do some basic list manipulations and output to log for
* script comparison. Only testing the macros we use.
*/
static void
test_list(void)
{
PTEST_LIST_NODE pNode = NULL;
struct TestList head = PMDK_LIST_HEAD_INITIALIZER(head);
PMDK_LIST_INIT(&head);
UT_ASSERT_rt(PMDK_LIST_EMPTY(&head));
pNode = MALLOC(sizeof(struct TEST_LIST_NODE));
pNode->dummy = 0;
PMDK_LIST_INSERT_HEAD(&head, pNode, ListEntry);
UT_ASSERTeq_rt(1, get_list_count(&head));
dump_list(&head);
/* Remove one node */
PMDK_LIST_REMOVE(pNode, ListEntry);
UT_ASSERTeq_rt(0, get_list_count(&head));
dump_list(&head);
free(pNode);
/* Add a bunch of nodes */
for (int i = 1; i < 10; i++) {
pNode = MALLOC(sizeof(struct TEST_LIST_NODE));
pNode->dummy = i;
PMDK_LIST_INSERT_HEAD(&head, pNode, ListEntry);
}
UT_ASSERTeq_rt(9, get_list_count(&head));
dump_list(&head);
/* Remove all of them */
while (!PMDK_LIST_EMPTY(&head)) {
pNode = (PTEST_LIST_NODE)PMDK_LIST_FIRST(&head);
PMDK_LIST_REMOVE(pNode, ListEntry);
free(pNode);
}
UT_ASSERTeq_rt(0, get_list_count(&head));
dump_list(&head);
}
typedef struct TEST_SORTEDQ_NODE {
PMDK_SORTEDQ_ENTRY(TEST_SORTEDQ_NODE) queue_link;
int dummy;
} TEST_SORTEDQ_NODE, *PTEST_SORTEDQ_NODE;
PMDK_SORTEDQ_HEAD(TEST_SORTEDQ, TEST_SORTEDQ_NODE);
static int
sortedq_node_comparer(TEST_SORTEDQ_NODE *a, TEST_SORTEDQ_NODE *b)
{
return a->dummy - b->dummy;
}
struct TEST_DATA_SORTEDQ {
int count;
int data[10];
};
/*
* test_sortedq - Do some basic operations on SORTEDQ and make sure that the
* queue is sorted for different input sequences.
*/
void
test_sortedq(void)
{
PTEST_SORTEDQ_NODE node = NULL;
struct TEST_SORTEDQ head = PMDK_SORTEDQ_HEAD_INITIALIZER(head);
struct TEST_DATA_SORTEDQ test_data[] = {
{5, {5, 7, 9, 100, 101}},
{7, {1, 2, 3, 4, 5, 6, 7}},
{5, {100, 90, 80, 70, 40}},
{6, {10, 9, 8, 7, 6, 5}},
{5, {23, 13, 27, 4, 15}},
{5, {2, 2, 2, 2, 2}}
};
PMDK_SORTEDQ_INIT(&head);
UT_ASSERT_rt(PMDK_SORTEDQ_EMPTY(&head));
for (int i = 0; i < _countof(test_data); i++) {
for (int j = 0; j < test_data[i].count; j++) {
node = MALLOC(sizeof(TEST_SORTEDQ_NODE));
node->dummy = test_data[i].data[j];
PMDK_SORTEDQ_INSERT(&head, node, queue_link,
TEST_SORTEDQ_NODE, sortedq_node_comparer);
}
int prev = MININT;
int num_entries = 0;
PMDK_SORTEDQ_FOREACH(node, &head, queue_link) {
UT_ASSERT(prev <= node->dummy);
num_entries++;
}
UT_ASSERT(num_entries == test_data[i].count);
while (!PMDK_SORTEDQ_EMPTY(&head)) {
node = PMDK_SORTEDQ_FIRST(&head);
PMDK_SORTEDQ_REMOVE(&head, node, queue_link);
FREE(node);
}
}
}
int
main(int argc, char *argv[])
{
START(argc, argv, "win_lists - testing %s",
(argc > 1) ? argv[1] : "list");
if (argc == 1 || (stricmp(argv[1], "list") == 0))
test_list();
if (argc > 1 && (stricmp(argv[1], "sortedq") == 0))
test_sortedq();
DONE(NULL);
}
| 5,431 | 27 | 76 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_pool/obj_pool.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* obj_pool.c -- unit test for pmemobj_create() and pmemobj_open()
* Also tests pmemobj_(set/get)_user_data().
*
* usage: obj_pool op path layout [poolsize mode]
*
* op can be:
* c - create
* o - open
*
* "poolsize" and "mode" arguments are ignored for "open"
*/
#include "unittest.h"
#include "../libpmemobj/obj.h"
#define MB ((size_t)1 << 20)
#define USER_DATA_V (void *) 123456789ULL
static void
pool_create(const char *path, const char *layout, size_t poolsize,
unsigned mode)
{
PMEMobjpool *pop = pmemobj_create(path, layout, poolsize, mode);
if (pop == NULL)
UT_OUT("!%s: pmemobj_create: %s", path, pmemobj_errormsg());
else {
/* Test pmemobj_(get/set)_user data */
UT_ASSERTeq(NULL, pmemobj_get_user_data(pop));
pmemobj_set_user_data(pop, USER_DATA_V);
UT_ASSERTeq(USER_DATA_V, pmemobj_get_user_data(pop));
os_stat_t stbuf;
STAT(path, &stbuf);
UT_OUT("%s: file size %zu mode 0%o",
path, stbuf.st_size,
stbuf.st_mode & 0777);
pmemobj_close(pop);
int result = pmemobj_check(path, layout);
if (result < 0)
UT_OUT("!%s: pmemobj_check", path);
else if (result == 0)
UT_OUT("%s: pmemobj_check: not consistent", path);
}
}
static void
pool_open(const char *path, const char *layout)
{
PMEMobjpool *pop = pmemobj_open(path, layout);
if (pop == NULL)
UT_OUT("!%s: pmemobj_open: %s", path, pmemobj_errormsg());
else {
UT_OUT("%s: pmemobj_open: Success", path);
UT_ASSERTeq(NULL, pmemobj_get_user_data(pop));
pmemobj_close(pop);
}
}
static void
test_fault_injection(const char *path, const char *layout, size_t poolsize,
unsigned mode)
{
if (!pmemobj_fault_injection_enabled())
return;
pmemobj_inject_fault_at(PMEM_MALLOC, 1, "tx_params_new");
PMEMobjpool *pop = pmemobj_create(path, layout, poolsize, mode);
UT_ASSERTeq(pop, NULL);
UT_ASSERTeq(errno, ENOMEM);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_pool");
if (argc < 4)
UT_FATAL("usage: %s op path layout [poolsize mode]", argv[0]);
char *layout = NULL;
size_t poolsize;
unsigned mode;
if (strcmp(argv[3], "EMPTY") == 0)
layout = "";
else if (strcmp(argv[3], "NULL") != 0)
layout = argv[3];
switch (argv[1][0]) {
case 'c':
poolsize = strtoull(argv[4], NULL, 0) * MB; /* in megabytes */
mode = strtoul(argv[5], NULL, 8);
pool_create(argv[2], layout, poolsize, mode);
break;
case 'o':
pool_open(argv[2], layout);
break;
case 'f':
os_setenv("PMEMOBJ_CONF", "invalid-query", 1);
pool_open(argv[2], layout);
os_unsetenv("PMEMOBJ_CONF");
pool_open(argv[2], layout);
break;
case 't':
poolsize = strtoull(argv[4], NULL, 0) * MB; /* in megabytes */
mode = strtoul(argv[5], NULL, 8);
test_fault_injection(argv[2], layout, poolsize, mode);
break;
default:
UT_FATAL("unknown operation");
}
DONE(NULL);
}
| 2,905 | 21.527132 | 75 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_memset/pmem2_memset.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* pmem_memset.c -- unit test for doing a memset
*
* usage: pmem_memset file offset length
*/
#include "unittest.h"
#include "file.h"
#include "ut_pmem2.h"
#include "memset_common.h"
static void
do_memset_variants(int fd, char *dest, const char *file_name, size_t dest_off,
size_t bytes, persist_fn p, memset_fn fn)
{
for (int i = 0; i < ARRAY_SIZE(Flags); ++i) {
do_memset(fd, dest, file_name, dest_off, bytes,
fn, Flags[i], p);
if (Flags[i] & PMEMOBJ_F_MEM_NOFLUSH)
p(dest, bytes);
}
}
int
main(int argc, char *argv[])
{
int fd;
char *dest;
struct pmem2_config *cfg;
struct pmem2_source *src;
struct pmem2_map *map;
if (argc != 4)
UT_FATAL("usage: %s file offset length", argv[0]);
const char *thr = os_getenv("PMEM_MOVNT_THRESHOLD");
const char *avx = os_getenv("PMEM_AVX");
const char *avx512f = os_getenv("PMEM_AVX512F");
START(argc, argv, "pmem2_memset %s %s %s %savx %savx512f",
argv[2], argv[3],
thr ? thr : "default",
avx ? "" : "!",
avx512f ? "" : "!");
fd = OPEN(argv[1], O_RDWR);
PMEM2_CONFIG_NEW(&cfg);
PMEM2_SOURCE_FROM_FD(&src, fd);
PMEM2_CONFIG_SET_GRANULARITY(cfg, PMEM2_GRANULARITY_PAGE);
int ret = pmem2_map(cfg, src, &map);
UT_PMEM2_EXPECT_RETURN(ret, 0);
PMEM2_CONFIG_DELETE(&cfg);
dest = pmem2_map_get_address(map);
if (dest == NULL)
UT_FATAL("!could not map file: %s", argv[1]);
size_t dest_off = strtoul(argv[2], NULL, 0);
size_t bytes = strtoul(argv[3], NULL, 0);
pmem2_persist_fn persist = pmem2_get_persist_fn(map);
pmem2_memset_fn memset_fn = pmem2_get_memset_fn(map);
do_memset_variants(fd, dest, argv[1], dest_off, bytes,
persist, memset_fn);
ret = pmem2_unmap(&map);
UT_ASSERTeq(ret, 0);
CLOSE(fd);
DONE(NULL);
}
| 1,810 | 21.6375 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_memset/memset_common.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* memset_common.c -- common part for tests doing a persistent memset
*/
#include "unittest.h"
#include "memset_common.h"
/*
* do_memset - worker function for memset
*/
void
do_memset(int fd, char *dest, const char *file_name, size_t dest_off,
size_t bytes, memset_fn fn, unsigned flags,
persist_fn persist)
{
char *buf = MALLOC(bytes);
char *dest1;
char *ret;
memset(dest, 0, bytes);
persist(dest, bytes);
dest1 = MALLOC(bytes);
memset(dest1, 0, bytes);
/*
* This is used to verify that the value of what a non persistent
* memset matches the outcome of the persistent memset. The
* persistent memset will match the file but may not be the
* correct or expected value.
*/
memset(dest1 + dest_off, 0x5A, bytes / 4);
memset(dest1 + dest_off + (bytes / 4), 0x46, bytes / 4);
/* Test the corner cases */
ret = fn(dest + dest_off, 0x5A, 0, flags);
UT_ASSERTeq(ret, dest + dest_off);
UT_ASSERTeq(*(char *)(dest + dest_off), 0);
/*
* Do the actual memset with persistence.
*/
ret = fn(dest + dest_off, 0x5A, bytes / 4, flags);
UT_ASSERTeq(ret, dest + dest_off);
ret = fn(dest + dest_off + (bytes / 4), 0x46, bytes / 4, flags);
UT_ASSERTeq(ret, dest + dest_off + (bytes / 4));
if (memcmp(dest, dest1, bytes / 2))
UT_FATAL("%s: first %zu bytes do not match",
file_name, bytes / 2);
LSEEK(fd, 0, SEEK_SET);
if (READ(fd, buf, bytes / 2) == bytes / 2) {
if (memcmp(buf, dest, bytes / 2))
UT_FATAL("%s: first %zu bytes do not match",
file_name, bytes / 2);
}
FREE(dest1);
FREE(buf);
}
unsigned Flags[] = {
0,
PMEM_F_MEM_NODRAIN,
PMEM_F_MEM_NONTEMPORAL,
PMEM_F_MEM_TEMPORAL,
PMEM_F_MEM_NONTEMPORAL | PMEM_F_MEM_TEMPORAL,
PMEM_F_MEM_NONTEMPORAL | PMEM_F_MEM_NODRAIN,
PMEM_F_MEM_WC,
PMEM_F_MEM_WB,
PMEM_F_MEM_NOFLUSH,
/* all possible flags */
PMEM_F_MEM_NODRAIN | PMEM_F_MEM_NOFLUSH |
PMEM_F_MEM_NONTEMPORAL | PMEM_F_MEM_TEMPORAL |
PMEM_F_MEM_WC | PMEM_F_MEM_WB,
};
| 2,043 | 24.55 | 69 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_memset/TESTS.py
|
#!../env.py
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2020, Intel Corporation
#
from collections import namedtuple
import testframework as t
TC = namedtuple('TC', ['offset', 'length'])
class Pmem2Memset(t.Test):
test_type = t.Short
filesize = 4 * t.MiB
envs0 = ()
envs1 = ()
test_cases = (
TC(offset=0, length=8),
TC(offset=13, length=4096)
)
def run(self, ctx):
for env in self.envs0:
ctx.env[env] = '0'
for env in self.envs1:
ctx.env[env] = '1'
if ctx.wc_workaround() == 'on':
ctx.env['PMEM_WC_WORKAROUND'] = '1'
elif ctx.wc_workaround() == 'off':
ctx.env['PMEM_WC_WORKAROUND'] = '0'
for tc in self.test_cases:
filepath = ctx.create_holey_file(self.filesize, 'testfile',)
ctx.exec('pmem2_memset', filepath, tc.offset, tc.length)
@t.add_params('wc_workaround', ['on', 'off', 'default'])
class TEST0(Pmem2Memset):
pass
@t.require_architectures('x86_64')
@t.add_params('wc_workaround', ['on', 'off', 'default'])
class TEST1(Pmem2Memset):
envs0 = ("PMEM_AVX512F",)
@t.require_architectures('x86_64')
@t.add_params('wc_workaround', ['on', 'off', 'default'])
class TEST2(Pmem2Memset):
envs0 = ("PMEM_AVX512F", "PMEM_AVX",)
@t.add_params('wc_workaround', ['default'])
class TEST3(Pmem2Memset):
envs1 = ("PMEM_NO_MOVNT",)
@t.add_params('wc_workaround', ['default'])
class TEST4(Pmem2Memset):
envs1 = ("PMEM_NO_MOVNT", "PMEM_NO_GENERIC_MEMCPY")
| 1,543 | 22.753846 | 72 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_memset/memset_common.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* memset_common.h -- header file for common memset utilities
*/
#ifndef MEMSET_COMMON_H
#define MEMSET_COMMON_H 1
#include "unittest.h"
#include "file.h"
extern unsigned Flags[10];
typedef void *(*memset_fn)(void *pmemdest, int c, size_t len, unsigned flags);
typedef void (*persist_fn)(const void *ptr, size_t len);
void
do_memset(int fd, char *dest, const char *file_name, size_t dest_off,
size_t bytes, memset_fn fn, unsigned flags, persist_fn p);
#endif
| 552 | 22.041667 | 78 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/sync-remotes/copy-to-remote-nodes.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2018, Intel Corporation
#
# copy-to-remote-nodes.sh -- helper script used to sync remote nodes
#
set -e
if [ ! -f ../testconfig.sh ]; then
echo "SKIP: testconfig.sh does not exist"
exit 0
fi
# defined only to be able to source unittest.sh
UNITTEST_NAME=sync-remotes
UNITTEST_NUM=0
# Override default FS (any).
# This is not a real test, so it should not depend on whether
# PMEM_FS_DIR/NON_PMEM_FS_DIR are set.
FS=none
. ../unittest/unittest.sh
COPY_TYPE=$1
shift
case "$COPY_TYPE" in
common)
copy_common_to_remote_nodes $* > /dev/null
exit 0
;;
test)
copy_test_to_remote_nodes $* > /dev/null
exit 0
;;
esac
echo "Error: unknown copy type: $COPY_TYPE"
exit 1
| 788 | 17.785714 | 68 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_root/obj_root.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018, Intel Corporation */
/*
* obj_root.c -- unit tests for pmemobj_root
*/
#include "unittest.h"
#define FILE_SIZE ((size_t)0x440000000) /* 17 GB */
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_root");
if (argc < 2)
UT_FATAL("usage: obj_root <file> [l]");
const char *path = argv[1];
PMEMobjpool *pop = NULL;
os_stat_t st;
int long_test = 0;
if (argc >= 3 && argv[2][0] == 'l')
long_test = 1;
os_stat(path, &st);
UT_ASSERTeq(st.st_size, FILE_SIZE);
if ((pop = pmemobj_create(path, NULL, 0, S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create: %s", path);
errno = 0;
PMEMoid oid = pmemobj_root(pop, 0);
UT_ASSERT(OID_EQUALS(oid, OID_NULL));
UT_ASSERTeq(errno, EINVAL);
if (long_test) {
oid = pmemobj_root(pop, PMEMOBJ_MAX_ALLOC_SIZE);
UT_ASSERT(!OID_EQUALS(oid, OID_NULL));
}
oid = pmemobj_root(pop, 1);
UT_ASSERT(!OID_EQUALS(oid, OID_NULL));
oid = pmemobj_root(pop, 0);
UT_ASSERT(!OID_EQUALS(oid, OID_NULL));
errno = 0;
oid = pmemobj_root(pop, FILE_SIZE);
UT_ASSERT(OID_EQUALS(oid, OID_NULL));
UT_ASSERTeq(errno, ENOMEM);
errno = 0;
oid = pmemobj_root(pop, SIZE_MAX);
UT_ASSERT(OID_EQUALS(oid, OID_NULL));
UT_ASSERTeq(errno, ENOMEM);
pmemobj_close(pop);
DONE(NULL);
}
| 1,298 | 19.619048 | 70 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_pmalloc_basic/obj_pmalloc_basic.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2019, Intel Corporation */
/*
* obj_pmalloc_basic.c -- unit test for pmalloc interface
*/
#include <stdint.h>
#include "heap.h"
#include "obj.h"
#include "pmalloc.h"
#include "unittest.h"
#include "valgrind_internal.h"
#include "set.h"
#define MOCK_POOL_SIZE (PMEMOBJ_MIN_POOL * 3)
#define TEST_MEGA_ALLOC_SIZE (10 * 1024 * 1024)
#define TEST_HUGE_ALLOC_SIZE (4 * 255 * 1024)
#define TEST_SMALL_ALLOC_SIZE (1000)
#define TEST_MEDIUM_ALLOC_SIZE (1024 * 200)
#define TEST_TINY_ALLOC_SIZE (64)
#define TEST_RUNS 2
#define MAX_MALLOC_FREE_LOOP 1000
#define MALLOC_FREE_SIZE 8000
#define PAD_SIZE (PMEM_PAGESIZE - LANE_TOTAL_SIZE)
struct mock_pop {
PMEMobjpool p;
char lanes[LANE_TOTAL_SIZE];
char padding[PAD_SIZE]; /* to page boundary */
uint64_t ptr;
};
static struct mock_pop *addr;
static PMEMobjpool *mock_pop;
/*
* drain_empty -- (internal) empty function for drain on non-pmem memory
*/
static void
drain_empty(void)
{
/* do nothing */
}
/*
* obj_persist -- pmemobj version of pmem_persist w/o replication
*/
static int
obj_persist(void *ctx, const void *addr, size_t len, unsigned flags)
{
PMEMobjpool *pop = ctx;
pop->persist_local(addr, len);
return 0;
}
/*
* obj_flush -- pmemobj version of pmem_flush w/o replication
*/
static int
obj_flush(void *ctx, const void *addr, size_t len, unsigned flags)
{
PMEMobjpool *pop = ctx;
pop->flush_local(addr, len);
return 0;
}
/*
* obj_drain -- pmemobj version of pmem_drain w/o replication
*/
static void
obj_drain(void *ctx)
{
PMEMobjpool *pop = ctx;
pop->drain_local();
}
static void
obj_msync_nofail(const void *addr, size_t size)
{
if (pmem_msync(addr, size))
UT_FATAL("!pmem_msync");
}
/*
* obj_memcpy -- pmemobj version of memcpy w/o replication
*/
static void *
obj_memcpy(void *ctx, void *dest, const void *src, size_t len, unsigned flags)
{
pmem_memcpy(dest, src, len, flags);
return dest;
}
static void *
obj_memset(void *ctx, void *ptr, int c, size_t sz, unsigned flags)
{
pmem_memset(ptr, c, sz, flags);
return ptr;
}
static size_t
test_oom_allocs(size_t size)
{
uint64_t max_allocs = MOCK_POOL_SIZE / size;
uint64_t *allocs = CALLOC(max_allocs, sizeof(*allocs));
size_t count = 0;
for (;;) {
if (pmalloc(mock_pop, &addr->ptr, size, 0, 0)) {
break;
}
UT_ASSERT(addr->ptr != 0);
allocs[count++] = addr->ptr;
}
for (int i = 0; i < count; ++i) {
addr->ptr = allocs[i];
pfree(mock_pop, &addr->ptr);
UT_ASSERT(addr->ptr == 0);
}
UT_ASSERT(count != 0);
FREE(allocs);
return count;
}
static size_t
test_oom_resrv(size_t size)
{
uint64_t max_allocs = MOCK_POOL_SIZE / size;
uint64_t *allocs = CALLOC(max_allocs, sizeof(*allocs));
struct pobj_action *resvs = CALLOC(max_allocs, sizeof(*resvs));
size_t count = 0;
for (;;) {
if (palloc_reserve(&mock_pop->heap, size,
NULL, NULL, 0, 0, 0, 0,
&resvs[count]) != 0)
break;
allocs[count] = resvs[count].heap.offset;
UT_ASSERT(allocs[count] != 0);
count++;
}
for (size_t i = 0; i < count; ) {
size_t nresv = MIN(count - i, 10);
struct operation_context *ctx =
pmalloc_operation_hold(mock_pop);
palloc_publish(&mock_pop->heap, &resvs[i], nresv, ctx);
pmalloc_operation_release(mock_pop);
i += nresv;
}
for (int i = 0; i < count; ++i) {
addr->ptr = allocs[i];
pfree(mock_pop, &addr->ptr);
UT_ASSERT(addr->ptr == 0);
}
UT_ASSERT(count != 0);
FREE(allocs);
FREE(resvs);
return count;
}
static void
test_malloc_free_loop(size_t size)
{
int err;
for (int i = 0; i < MAX_MALLOC_FREE_LOOP; ++i) {
err = pmalloc(mock_pop, &addr->ptr, size, 0, 0);
UT_ASSERTeq(err, 0);
pfree(mock_pop, &addr->ptr);
}
}
static void
test_realloc(size_t org, size_t dest)
{
int err;
struct palloc_heap *heap = &mock_pop->heap;
err = pmalloc(mock_pop, &addr->ptr, org, 0, 0);
UT_ASSERTeq(err, 0);
UT_ASSERT(palloc_usable_size(heap, addr->ptr) >= org);
err = prealloc(mock_pop, &addr->ptr, dest, 0, 0);
UT_ASSERTeq(err, 0);
UT_ASSERT(palloc_usable_size(heap, addr->ptr) >= dest);
pfree(mock_pop, &addr->ptr);
}
#define PMALLOC_EXTRA 20
#define PALLOC_FLAG (1 << 15)
#define FIRST_SIZE 1 /* use the first allocation class */
#define FIRST_USIZE 112 /* the usable size is 128 - 16 */
static void
test_pmalloc_extras(PMEMobjpool *pop)
{
uint64_t val;
int ret = pmalloc(pop, &val, FIRST_SIZE, PMALLOC_EXTRA, PALLOC_FLAG);
UT_ASSERTeq(ret, 0);
UT_ASSERTeq(palloc_extra(&pop->heap, val), PMALLOC_EXTRA);
UT_ASSERT((palloc_flags(&pop->heap, val) & PALLOC_FLAG) == PALLOC_FLAG);
UT_ASSERT(palloc_usable_size(&pop->heap, val) == FIRST_USIZE);
pfree(pop, &val);
}
#define PMALLOC_ELEMENTS 20
static void
test_pmalloc_first_next(PMEMobjpool *pop)
{
uint64_t vals[PMALLOC_ELEMENTS];
for (unsigned i = 0; i < PMALLOC_ELEMENTS; ++i) {
int ret = pmalloc(pop, &vals[i], FIRST_SIZE, i, i);
UT_ASSERTeq(ret, 0);
}
uint64_t off = palloc_first(&pop->heap);
UT_ASSERTne(off, 0);
int nvalues = 0;
do {
UT_ASSERTeq(vals[nvalues], off);
UT_ASSERTeq(palloc_extra(&pop->heap, off), nvalues);
UT_ASSERTeq(palloc_flags(&pop->heap, off), nvalues);
UT_ASSERT(palloc_usable_size(&pop->heap, off) == FIRST_USIZE);
nvalues ++;
} while ((off = palloc_next(&pop->heap, off)) != 0);
UT_ASSERTeq(nvalues, PMALLOC_ELEMENTS);
for (int i = 0; i < PMALLOC_ELEMENTS; ++i)
pfree(pop, &vals[i]);
}
static void
test_mock_pool_allocs(void)
{
addr = MMAP_ANON_ALIGNED(MOCK_POOL_SIZE, Ut_mmap_align);
mock_pop = &addr->p;
mock_pop->addr = addr;
mock_pop->rdonly = 0;
mock_pop->is_pmem = 0;
mock_pop->heap_offset = offsetof(struct mock_pop, ptr);
UT_ASSERTeq(mock_pop->heap_offset % Ut_pagesize, 0);
mock_pop->nlanes = 1;
mock_pop->lanes_offset = sizeof(PMEMobjpool);
mock_pop->is_master_replica = 1;
mock_pop->persist_local = obj_msync_nofail;
mock_pop->flush_local = obj_msync_nofail;
mock_pop->drain_local = drain_empty;
mock_pop->p_ops.persist = obj_persist;
mock_pop->p_ops.flush = obj_flush;
mock_pop->p_ops.drain = obj_drain;
mock_pop->p_ops.memcpy = obj_memcpy;
mock_pop->p_ops.memset = obj_memset;
mock_pop->p_ops.base = mock_pop;
mock_pop->set = MALLOC(sizeof(*(mock_pop->set)));
mock_pop->set->options = 0;
mock_pop->set->directory_based = 0;
void *heap_start = (char *)mock_pop + mock_pop->heap_offset;
uint64_t heap_size = MOCK_POOL_SIZE - mock_pop->heap_offset;
struct stats *s = stats_new(mock_pop);
UT_ASSERTne(s, NULL);
heap_init(heap_start, heap_size, &mock_pop->heap_size,
&mock_pop->p_ops);
heap_boot(&mock_pop->heap, heap_start, heap_size, &mock_pop->heap_size,
mock_pop, &mock_pop->p_ops, s, mock_pop->set);
heap_buckets_init(&mock_pop->heap);
/* initialize runtime lanes structure */
mock_pop->lanes_desc.runtime_nlanes = (unsigned)mock_pop->nlanes;
lane_boot(mock_pop);
UT_ASSERTne(mock_pop->heap.rt, NULL);
test_pmalloc_extras(mock_pop);
test_pmalloc_first_next(mock_pop);
test_malloc_free_loop(MALLOC_FREE_SIZE);
size_t medium_resv = test_oom_resrv(TEST_MEDIUM_ALLOC_SIZE);
/*
* Allocating till OOM and freeing the objects in a loop for different
* buckets covers basically all code paths except error cases.
*/
size_t medium0 = test_oom_allocs(TEST_MEDIUM_ALLOC_SIZE);
size_t mega0 = test_oom_allocs(TEST_MEGA_ALLOC_SIZE);
size_t huge0 = test_oom_allocs(TEST_HUGE_ALLOC_SIZE);
size_t small0 = test_oom_allocs(TEST_SMALL_ALLOC_SIZE);
size_t tiny0 = test_oom_allocs(TEST_TINY_ALLOC_SIZE);
size_t huge1 = test_oom_allocs(TEST_HUGE_ALLOC_SIZE);
size_t small1 = test_oom_allocs(TEST_SMALL_ALLOC_SIZE);
size_t mega1 = test_oom_allocs(TEST_MEGA_ALLOC_SIZE);
size_t tiny1 = test_oom_allocs(TEST_TINY_ALLOC_SIZE);
size_t medium1 = test_oom_allocs(TEST_MEDIUM_ALLOC_SIZE);
UT_ASSERTeq(mega0, mega1);
UT_ASSERTeq(huge0, huge1);
UT_ASSERTeq(small0, small1);
UT_ASSERTeq(tiny0, tiny1);
UT_ASSERTeq(medium0, medium1);
UT_ASSERTeq(medium0, medium_resv);
/* realloc to the same size shouldn't affect anything */
for (size_t i = 0; i < tiny1; ++i)
test_realloc(TEST_TINY_ALLOC_SIZE, TEST_TINY_ALLOC_SIZE);
size_t tiny2 = test_oom_allocs(TEST_TINY_ALLOC_SIZE);
UT_ASSERTeq(tiny1, tiny2);
test_realloc(TEST_SMALL_ALLOC_SIZE, TEST_MEDIUM_ALLOC_SIZE);
test_realloc(TEST_HUGE_ALLOC_SIZE, TEST_MEGA_ALLOC_SIZE);
stats_delete(mock_pop, s);
lane_cleanup(mock_pop);
heap_cleanup(&mock_pop->heap);
FREE(mock_pop->set);
MUNMAP_ANON_ALIGNED(addr, MOCK_POOL_SIZE);
}
static void
test_spec_compliance(void)
{
uint64_t max_alloc = MAX_MEMORY_BLOCK_SIZE -
sizeof(struct allocation_header_legacy);
UT_ASSERTeq(max_alloc, PMEMOBJ_MAX_ALLOC_SIZE);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_pmalloc_basic");
for (int i = 0; i < TEST_RUNS; ++i)
test_mock_pool_allocs();
test_spec_compliance();
DONE(NULL);
}
#ifdef _MSC_VER
/*
* Since libpmemobj is linked statically, we need to invoke its ctor/dtor.
*/
MSVC_CONSTR(libpmemobj_init)
MSVC_DESTR(libpmemobj_fini)
#endif
| 8,962 | 23.15903 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmempool_check/config.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2017, Intel Corporation
#
#
# pmempool_check/config.sh -- test configuration
#
# Extend timeout for TEST5, as it may take a few minutes
# when run on a non-pmem file system.
CONF_TIMEOUT[5]='10m'
| 271 | 18.428571 | 56 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmempool_check/common.sh
|
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2018-2020, Intel Corporation
#
#
# pmempool_check/common.sh -- checking pools helpers
#
LOG=out${UNITTEST_NUM}.log
rm -f $LOG && touch $LOG
LAYOUT=OBJ_LAYOUT$SUFFIX
POOLSET=$DIR/poolset
# pmemspoil_corrupt_replica_sds -- corrupt shutdown state
#
# usage: pmemspoil_corrupt_replica_sds <replica>
function pmemspoil_corrupt_replica_sds() {
local replica=$1
expect_normal_exit $PMEMSPOIL --replica $replica $POOLSET \
pool_hdr.shutdown_state.usc=999 \
pool_hdr.shutdown_state.dirty=1 \
"pool_hdr.shutdown_state.f:checksum_gen"
}
# pmempool_check_sds_init -- shutdown state unittest init
#
# usage: pmempool_check_sds [enable-sds]
function pmempool_check_sds_init() {
# initialize poolset
create_poolset $POOLSET \
8M:$DIR/part00:x \
r 8M:$DIR/part10:x
# enable SHUTDOWN_STATE feature
if [ "x$1" == "xenable-sds" ]; then
local conf="sds.at_create=1"
fi
PMEMOBJ_CONF="${PMEMOBJ_CONF}$conf;"
expect_normal_exit $PMEMPOOL$EXESUFFIX create --layout=$LAYOUT obj $POOLSET
}
# pmempool_check_sds -- perform shutdown state unittest
#
# usage: pmempool_check_sds <scenario>
function pmempool_check_sds() {
# corrupt poolset replicas
pmemspoil_corrupt_replica_sds 0
pmemspoil_corrupt_replica_sds 1
# verify it is corrupted
expect_abnormal_exit $PMEMPOOL$EXESUFFIX check $POOLSET >> $LOG 2>/dev/null
exit_func=expect_normal_exit
# perform fixes
case "$1" in
fix_second_replica_only)
echo -e "n\ny\n" | expect_normal_exit $PMEMPOOL$EXESUFFIX check -vr $POOLSET >> $LOG 2>/dev/null
;;
fix_first_replica)
echo -e "y\n" | expect_normal_exit $PMEMPOOL$EXESUFFIX check -vr $POOLSET >> $LOG 2>/dev/null
;;
fix_no_replicas)
echo -e "n\nn\n" | expect_abnormal_exit $PMEMPOOL$EXESUFFIX check -vr $POOLSET >> $LOG 2>/dev/null
exit_func=expect_abnormal_exit
;;
*)
fatal "unittest_sds: undefined scenario '$1'"
;;
esac
#verify result
$exit_func $PMEMPOOL$EXESUFFIX check $POOLSET >> $LOG 2>/dev/null
}
| 2,010 | 25.460526 | 100 |
sh
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/blk_pool_win/blk_pool_win.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2019, Intel Corporation */
/*
* blk_pool_win.c -- unit test for pmemblk_create() and pmemblk_open()
*
* usage: blk_pool_win op path bsize [poolsize mode]
*
* op can be:
* c - create
* o - open
*
* "poolsize" and "mode" arguments are ignored for "open"
*/
#include "unittest.h"
#define MB ((size_t)1 << 20)
static void
pool_create(const wchar_t *path, size_t bsize, size_t poolsize, unsigned mode)
{
char *upath = ut_toUTF8(path);
UT_ASSERTne(upath, NULL);
PMEMblkpool *pbp = pmemblk_createW(path, bsize, poolsize, mode);
if (pbp == NULL)
UT_OUT("!%s: pmemblk_create", upath);
else {
os_stat_t stbuf;
STATW(path, &stbuf);
UT_OUT("%s: file size %zu usable blocks %zu mode 0%o",
upath, stbuf.st_size,
pmemblk_nblock(pbp),
stbuf.st_mode & 0777);
pmemblk_close(pbp);
int result = pmemblk_checkW(path, bsize);
if (result < 0)
UT_OUT("!%s: pmemblk_check", upath);
else if (result == 0)
UT_OUT("%s: pmemblk_check: not consistent", upath);
else
UT_ASSERTeq(pmemblk_checkW(path, bsize * 2), -1);
free(upath);
}
}
static void
pool_open(const wchar_t *path, size_t bsize)
{
char *upath = ut_toUTF8(path);
UT_ASSERTne(upath, NULL);
PMEMblkpool *pbp = pmemblk_openW(path, bsize);
if (pbp == NULL)
UT_OUT("!%s: pmemblk_open", upath);
else {
UT_OUT("%s: pmemblk_open: Success", upath);
pmemblk_close(pbp);
}
free(upath);
}
int
wmain(int argc, wchar_t *argv[])
{
STARTW(argc, argv, "blk_pool_win");
if (argc < 4)
UT_FATAL("usage: %s op path bsize [poolsize mode]",
ut_toUTF8(argv[0]));
size_t bsize = wcstoul(argv[3], NULL, 0);
size_t poolsize;
unsigned mode;
switch (argv[1][0]) {
case 'c':
poolsize = wcstoul(argv[4], NULL, 0) * MB; /* in megabytes */
mode = wcstoul(argv[5], NULL, 8);
pool_create(argv[2], bsize, poolsize, mode);
break;
case 'o':
pool_open(argv[2], bsize);
break;
default:
UT_FATAL("unknown operation");
}
DONEW(NULL);
}
| 2,006 | 19.272727 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/win_common/win_common.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* Copyright (c) 2016, Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* win_common.c -- test common POSIX or Linux API that were implemented
* for Windows by our library.
*/
#include "unittest.h"
/*
* test_setunsetenv - test the setenv and unsetenv APIs
*/
static void
test_setunsetenv(void)
{
os_unsetenv("TEST_SETUNSETENV_ONE");
/* set a new variable without overwriting - expect the new value */
UT_ASSERT(os_setenv("TEST_SETUNSETENV_ONE",
"test_setunsetenv_one", 0) == 0);
UT_ASSERT(strcmp(os_getenv("TEST_SETUNSETENV_ONE"),
"test_setunsetenv_one") == 0);
/* set an existing variable without overwriting - expect old value */
UT_ASSERT(os_setenv("TEST_SETUNSETENV_ONE",
"test_setunsetenv_two", 0) == 0);
UT_ASSERT(strcmp(os_getenv("TEST_SETUNSETENV_ONE"),
"test_setunsetenv_one") == 0);
/* set an existing variable with overwriting - expect the new value */
UT_ASSERT(os_setenv("TEST_SETUNSETENV_ONE",
"test_setunsetenv_two", 1) == 0);
UT_ASSERT(strcmp(os_getenv("TEST_SETUNSETENV_ONE"),
"test_setunsetenv_two") == 0);
/* unset our test value - expect it to be empty */
UT_ASSERT(os_unsetenv("TEST_SETUNSETENV_ONE") == 0);
UT_ASSERT(os_getenv("TEST_SETUNSETENV_ONE") == NULL);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "win_common - testing %s",
(argc > 1) ? argv[1] : "setunsetenv");
if (argc == 1 || (stricmp(argv[1], "setunsetenv") == 0))
test_setunsetenv();
DONE(NULL);
}
| 3,080 | 35.678571 | 74 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/win_common/TESTS.py
|
#!../env.py
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019, Intel Corporation
import testframework as t
@t.windows_only
class TEST0(t.Test):
test_type = t.Medium
def run(self, ctx):
ctx.exec('win_common', 'setunsetenv')
| 251 | 15.8 | 45 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_realloc/obj_realloc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2019, Intel Corporation */
/*
* obj_realloc.c -- unit test for pmemobj_realloc and pmemobj_zrealloc
*/
#include <sys/param.h>
#include <string.h>
#include "unittest.h"
#include "heap.h"
#include "alloc_class.h"
#include "obj.h"
#include "util.h"
#define MAX_ALLOC_MUL 8
#define MAX_ALLOC_CLASS 5
POBJ_LAYOUT_BEGIN(realloc);
POBJ_LAYOUT_ROOT(realloc, struct root);
POBJ_LAYOUT_TOID(realloc, struct object);
POBJ_LAYOUT_END(realloc);
struct object {
size_t value;
char data[];
};
struct root {
TOID(struct object) obj;
char data[CHUNKSIZE - sizeof(TOID(struct object))];
};
static struct alloc_class_collection *alloc_classes;
/*
* test_alloc -- test allocation using realloc
*/
static void
test_alloc(PMEMobjpool *pop, size_t size)
{
TOID(struct root) root = POBJ_ROOT(pop, struct root);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
int ret = pmemobj_realloc(pop, &D_RW(root)->obj.oid, size,
TOID_TYPE_NUM(struct object));
UT_ASSERTeq(ret, 0);
UT_ASSERT(!TOID_IS_NULL(D_RO(root)->obj));
UT_ASSERT(pmemobj_alloc_usable_size(D_RO(root)->obj.oid) >= size);
}
/*
* test_free -- test free using realloc
*/
static void
test_free(PMEMobjpool *pop)
{
TOID(struct root) root = POBJ_ROOT(pop, struct root);
UT_ASSERT(!TOID_IS_NULL(D_RO(root)->obj));
int ret = pmemobj_realloc(pop, &D_RW(root)->obj.oid, 0,
TOID_TYPE_NUM(struct object));
UT_ASSERTeq(ret, 0);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
}
/*
* test_huge_size -- test zrealloc with size greater than pool size
*/
static void
test_huge_size(PMEMobjpool *pop)
{
TOID(struct root) root = POBJ_ROOT(pop, struct root);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
int ret;
ret = pmemobj_zrealloc(pop, &D_RW(root)->obj.oid,
PMEMOBJ_MAX_ALLOC_SIZE, TOID_TYPE_NUM(struct object));
UT_ASSERTne(ret, 0);
UT_ASSERTeq(errno, ENOMEM);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
ret = pmemobj_zrealloc(pop, &D_RW(root)->obj.oid, UINTMAX_MAX,
TOID_TYPE_NUM(struct object));
UT_ASSERTne(ret, 0);
UT_ASSERTeq(errno, ENOMEM);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
ret = pmemobj_zrealloc(pop, &D_RW(root)->obj.oid, UINTMAX_MAX - 1,
TOID_TYPE_NUM(struct object));
UT_ASSERTne(ret, 0);
UT_ASSERTeq(errno, ENOMEM);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
}
/* test zrealloc passing PMEMoid that points to OID_NULL value */
static void
test_null_oid(PMEMobjpool *pop)
{
TOID(struct root) root = POBJ_ROOT(pop, struct root);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
int ret = pmemobj_zrealloc(pop, &D_RW(root)->obj.oid, 1024,
TOID_TYPE_NUM(struct object));
UT_ASSERTeq(ret, 0);
UT_ASSERT(!TOID_IS_NULL(D_RO(root)->obj));
pmemobj_free(&D_RW(root)->obj.oid);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
}
static int check_integrity = 1;
/*
* fill_buffer -- fill buffer with random data and return its checksum
*/
static uint16_t
fill_buffer(unsigned char *buf, size_t size)
{
for (size_t i = 0; i < size; ++i)
buf[i] = rand() % 255;
pmem_persist(buf, size);
return ut_checksum(buf, size);
}
/*
* test_realloc -- test single reallocation
*/
static void
test_realloc(PMEMobjpool *pop, size_t size_from, size_t size_to,
uint64_t type_from, uint64_t type_to, int zrealloc)
{
TOID(struct root) root = POBJ_ROOT(pop, struct root);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
int ret;
if (zrealloc)
ret = pmemobj_zalloc(pop, &D_RW(root)->obj.oid,
size_from, type_from);
else
ret = pmemobj_alloc(pop, &D_RW(root)->obj.oid,
size_from, type_from, NULL, NULL);
UT_ASSERTeq(ret, 0);
UT_ASSERT(!TOID_IS_NULL(D_RO(root)->obj));
size_t usable_size_from =
pmemobj_alloc_usable_size(D_RO(root)->obj.oid);
UT_ASSERT(usable_size_from >= size_from);
size_t check_size;
uint16_t checksum;
if (zrealloc) {
UT_ASSERT(util_is_zeroed(D_RO(D_RO(root)->obj),
size_from));
} else if (check_integrity) {
check_size = size_to >= usable_size_from ?
usable_size_from : size_to;
checksum = fill_buffer((unsigned char *)D_RW(D_RW(root)->obj),
check_size);
}
if (zrealloc) {
ret = pmemobj_zrealloc(pop, &D_RW(root)->obj.oid,
size_to, type_to);
} else {
ret = pmemobj_realloc(pop, &D_RW(root)->obj.oid,
size_to, type_to);
}
UT_ASSERTeq(ret, 0);
UT_ASSERT(!TOID_IS_NULL(D_RO(root)->obj));
size_t usable_size_to =
pmemobj_alloc_usable_size(D_RO(root)->obj.oid);
UT_ASSERT(usable_size_to >= size_to);
if (size_to < size_from) {
UT_ASSERT(usable_size_to <= usable_size_from);
}
if (zrealloc) {
UT_ASSERT(util_is_zeroed(D_RO(D_RO(root)->obj), size_to));
} else if (check_integrity) {
uint16_t checksum2 = ut_checksum(
(uint8_t *)D_RW(D_RW(root)->obj), check_size);
if (checksum2 != checksum)
UT_ASSERTinfo(0, "memory corruption");
}
pmemobj_free(&D_RW(root)->obj.oid);
UT_ASSERT(TOID_IS_NULL(D_RO(root)->obj));
}
/*
* test_realloc_sizes -- test reallocations from/to specified sizes
*/
static void
test_realloc_sizes(PMEMobjpool *pop, uint64_t type_from,
uint64_t type_to, int zrealloc, unsigned size_diff)
{
for (uint8_t i = 0; i < MAX_ALLOCATION_CLASSES; ++i) {
struct alloc_class *c = alloc_class_by_id(alloc_classes, i);
if (c == NULL)
continue;
size_t header_size = header_type_to_size[c->header_type];
size_t size_from = c->unit_size - header_size - size_diff;
for (unsigned j = 2; j <= MAX_ALLOC_MUL; j++) {
size_t inc_size_to = c->unit_size * j - header_size;
test_realloc(pop, size_from, inc_size_to,
type_from, type_to, zrealloc);
size_t dec_size_to = c->unit_size / j;
if (dec_size_to <= header_size)
dec_size_to = header_size;
else
dec_size_to -= header_size;
test_realloc(pop, size_from, dec_size_to,
type_from, type_to, zrealloc);
for (int k = 0; k < MAX_ALLOC_CLASS; k++) {
struct alloc_class *ck = alloc_class_by_id(
alloc_classes, k);
if (c == NULL)
continue;
size_t header_sizek =
header_type_to_size[c->header_type];
size_t prev_size = ck->unit_size - header_sizek;
test_realloc(pop, size_from, prev_size,
type_from, type_to, zrealloc);
}
}
}
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_realloc");
/* root doesn't count */
UT_COMPILE_ERROR_ON(POBJ_LAYOUT_TYPES_NUM(realloc) != 1);
if (argc < 2)
UT_FATAL("usage: %s file [check_integrity]", argv[0]);
PMEMobjpool *pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(realloc));
if (!pop)
UT_FATAL("!pmemobj_open");
if (argc >= 3)
check_integrity = atoi(argv[2]);
alloc_classes = alloc_class_collection_new();
/* test huge size alloc */
test_huge_size(pop);
/* test alloc and free */
test_alloc(pop, 16);
test_free(pop);
/* test zrealloc passing PMEMoid that points to OID_NULL value */
test_null_oid(pop);
/* test realloc without changing type number */
test_realloc_sizes(pop, 0, 0, 0, 0);
/* test realloc with changing type number */
test_realloc_sizes(pop, 0, 1, 0, 0);
/* test zrealloc without changing type number... */
test_realloc_sizes(pop, 0, 0, 1, 8);
test_realloc_sizes(pop, 0, 0, 1, 0);
/* test zrealloc with changing type number... */
test_realloc_sizes(pop, 0, 1, 1, 8);
test_realloc_sizes(pop, 0, 1, 1, 0);
/* test realloc with type number equal to range of long long int */
test_realloc_sizes(pop, 0, UINT64_MAX, 0, 0);
test_realloc_sizes(pop, 0, UINT64_MAX - 1, 0, 0);
/* test zrealloc with type number equal to range of long long int */
test_realloc_sizes(pop, 0, UINT64_MAX, 1, 0);
test_realloc_sizes(pop, 0, (UINT64_MAX - 1), 1, 0);
alloc_class_collection_delete(alloc_classes);
pmemobj_close(pop);
DONE(NULL);
}
#ifdef _MSC_VER
extern "C" {
/*
* Since libpmemobj is linked statically,
* we need to invoke its ctor/dtor.
*/
MSVC_CONSTR(libpmemobj_init)
MSVC_DESTR(libpmemobj_fini)
}
#endif
| 7,788 | 24.371336 | 70 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem2_include/pmem2_include.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* pmem2_include.c -- include test for libpmem2
*
* this is only a compilation test - do not run this program
*/
#include <libpmem2.h>
int
main(int argc, char *argv[])
{
return 0;
}
| 273 | 15.117647 | 60 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem_deep_persist/mocks_posix.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* mocks_posix.c -- redefinitions of open/write functions (Posix implementation)
*/
#include "util.h"
#include "os.h"
#include "unittest.h"
/*
* open -- open mock because of Dev DAX without deep_flush
* sysfs file, eg. DAX on emulated pmem
*/
FUNC_MOCK(os_open, int, const char *path, int flags, ...)
FUNC_MOCK_RUN_DEFAULT {
if (strstr(path, "/sys/bus/nd/devices/region") &&
strstr(path, "/deep_flush")) {
UT_OUT("mocked open, path %s", path);
if (os_access(path, R_OK))
return 999;
}
va_list ap;
va_start(ap, flags);
int mode = va_arg(ap, int);
va_end(ap);
return _FUNC_REAL(os_open)(path, flags, mode);
}
FUNC_MOCK_END
/*
* write -- write mock
*/
FUNC_MOCK(write, int, int fd, const void *buffer, size_t count)
FUNC_MOCK_RUN_DEFAULT {
if (fd == 999) {
UT_OUT("mocked write, path %d", fd);
return 1;
}
return _FUNC_REAL(write)(fd, buffer, count);
}
FUNC_MOCK_END
/*
* read -- read mock
*/
FUNC_MOCK(read, size_t, int fd, void *buffer, size_t nbyte)
FUNC_MOCK_RUN_DEFAULT {
if (fd == 999) {
char pattern[2] = {'1', '\n'};
memcpy(buffer, pattern, sizeof(pattern));
UT_OUT("mocked read, fd %d", fd);
return sizeof(pattern);
}
return _FUNC_REAL(read)(fd, buffer, nbyte);
}
FUNC_MOCK_END
| 1,326 | 20.754098 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/pmem_deep_persist/pmem_deep_persist.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2019, Intel Corporation */
/*
* pmem_deep_persist.c -- unit test for pmem_deep_persist()
*
* usage: pmem_deep_persist file type deep_persist_size offset
*
* type is one of:
* p - call pmem_map_file()
* m - call mmap()
* o - call pmemobj_create()
*/
#include <string.h>
#include "unittest.h"
#include "file.h"
#include "os.h"
#include "file.h"
#include "set.h"
#include "obj.h"
#include "valgrind_internal.h"
#include "pmemcommon.h"
#include "pmem.h"
#define LAYOUT_NAME "deep_persist"
int
main(int argc, char *argv[])
{
START(argc, argv, "pmem_deep_persist");
pmem_init();
if (argc != 5)
UT_FATAL("usage: %s file type deep_persist_size offset",
argv[0]);
char *addr;
size_t mapped_len;
size_t persist_size;
size_t offset;
const char *path;
int is_pmem;
int ret = -1;
path = argv[1];
ssize_t tmp = ATOLL(argv[3]);
if (tmp < 0)
persist_size = UINT64_MAX;
else
persist_size = (size_t)tmp;
offset = ATOULL(argv[4]);
switch (*argv[2]) {
case 'p':
if ((addr = pmem_map_file(path, 0, 0,
0, &mapped_len, &is_pmem)) == NULL) {
UT_FATAL("!pmem_map_file");
}
if (persist_size == UINT64_MAX)
persist_size = mapped_len;
ret = pmem_deep_persist(addr + offset, persist_size);
pmem_unmap(addr, mapped_len);
break;
case 'm':
{
int fd = OPEN(path, O_RDWR);
ssize_t size = util_fd_get_size(fd);
if (size < 0)
UT_FATAL("!util_fd_get_size: %s", path);
size_t file_size = (size_t)size;
/* XXX: add MAP_SYNC flag */
addr = MMAP(NULL, file_size, PROT_READ|PROT_WRITE,
MAP_SHARED, fd, 0);
UT_ASSERTne(addr, MAP_FAILED);
CLOSE(fd);
if (persist_size == UINT64_MAX)
persist_size = file_size;
ret = pmem_deep_persist(addr + offset, persist_size);
break;
}
case 'o':
{
PMEMobjpool *pop = NULL;
if ((pop = pmemobj_create(path, LAYOUT_NAME,
0, S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create: %s", path);
void *start = (void *)((uintptr_t)pop + offset);
int flush = 1;
VALGRIND_DO_MAKE_MEM_DEFINED(start, persist_size);
ret = util_replica_deep_common(start, persist_size,
pop->set, 0, flush);
pmemobj_close(pop);
}
}
UT_OUT("deep_persist %d", ret);
DONE(NULL);
}
#ifdef _MSC_VER
/*
* Since libpmemobj is linked statically, we need to invoke its ctor/dtor.
*/
MSVC_CONSTR(libpmemobj_init)
MSVC_DESTR(libpmemobj_fini)
#endif
| 2,440 | 19.863248 | 74 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_tx_free/obj_tx_free.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* obj_tx_free.c -- unit test for pmemobj_tx_free
*/
#include <sys/param.h>
#include <string.h>
#include "unittest.h"
#include "util.h"
#include "valgrind_internal.h"
#define LAYOUT_NAME "tx_free"
#define OBJ_SIZE (200 * 1024)
enum type_number {
TYPE_FREE_NO_TX,
TYPE_FREE_WRONG_UUID,
TYPE_FREE_COMMIT,
TYPE_FREE_ABORT,
TYPE_FREE_COMMIT_NESTED1,
TYPE_FREE_COMMIT_NESTED2,
TYPE_FREE_ABORT_NESTED1,
TYPE_FREE_ABORT_NESTED2,
TYPE_FREE_ABORT_AFTER_NESTED1,
TYPE_FREE_ABORT_AFTER_NESTED2,
TYPE_FREE_OOM,
TYPE_FREE_ALLOC,
TYPE_FREE_AFTER_ABORT,
TYPE_FREE_MANY_TIMES,
};
TOID_DECLARE(struct object, 0);
struct object {
size_t value;
char data[OBJ_SIZE - sizeof(size_t)];
};
/*
* do_tx_alloc -- do tx allocation with specified type number
*/
static PMEMoid
do_tx_alloc(PMEMobjpool *pop, unsigned type_num)
{
PMEMoid ret = OID_NULL;
TX_BEGIN(pop) {
ret = pmemobj_tx_alloc(sizeof(struct object), type_num);
} TX_END
return ret;
}
/*
* do_tx_free_wrong_uuid -- try to free object with invalid uuid
*/
static void
do_tx_free_wrong_uuid(PMEMobjpool *pop)
{
volatile int ret = 0;
PMEMoid oid = do_tx_alloc(pop, TYPE_FREE_WRONG_UUID);
oid.pool_uuid_lo = ~oid.pool_uuid_lo;
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid);
UT_ASSERTeq(ret, 0);
} TX_ONABORT {
ret = -1;
} TX_END
UT_ASSERTeq(ret, -1);
/* POBJ_XFREE_NO_ABORT flag is set */
TX_BEGIN(pop) {
ret = pmemobj_tx_xfree(oid, POBJ_XFREE_NO_ABORT);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_WRONG_UUID));
UT_ASSERT(!TOID_IS_NULL(obj));
}
/*
* do_tx_free_wrong_uuid_abort_on_failure -- try to free object with
* invalid uuid in a transaction where pmemobj_tx_set_failure_behavior
* was called.
*/
static void
do_tx_free_wrong_uuid_abort_on_failure(PMEMobjpool *pop)
{
volatile int ret = 0;
PMEMoid oid = do_tx_alloc(pop, TYPE_FREE_WRONG_UUID);
oid.pool_uuid_lo = ~oid.pool_uuid_lo;
/* pmemobj_tx_set_failure_behavior is called */
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_RETURN);
ret = pmemobj_tx_free(oid);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
/* pmemobj_tx_set_failure_behavior is called */
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_RETURN);
ret = pmemobj_tx_xfree(oid, 0);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
/* pmemobj_tx_set_failure_behavior is called in outer tx */
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
TX_BEGIN(pop) {
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_RETURN);
ret = pmemobj_tx_free(oid);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
ret = pmemobj_tx_free(oid);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
/* pmemobj_tx_set_failure_behavior is called in neighbour tx */
TX_BEGIN(pop) {
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
ret = pmemobj_tx_free(oid);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
TX_BEGIN(pop) {
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_ABORT);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
/* pmemobj_tx_set_failure_behavior is called in neighbour tx */
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_RETURN);
TX_BEGIN(pop) {
pmemobj_tx_set_failure_behavior(POBJ_TX_FAILURE_ABORT);
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_ABORT);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
TX_BEGIN(pop) {
UT_ASSERTeq(pmemobj_tx_get_failure_behavior(),
POBJ_TX_FAILURE_RETURN);
ret = pmemobj_tx_free(oid);
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
} TX_ONCOMMIT {
UT_ASSERTeq(ret, EINVAL);
} TX_ONABORT {
UT_ASSERT(0); /* should not get to this point */
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_WRONG_UUID));
UT_ASSERT(!TOID_IS_NULL(obj));
}
/*
* do_tx_free_null_oid -- call pmemobj_tx_free with OID_NULL
*/
static void
do_tx_free_null_oid(PMEMobjpool *pop)
{
volatile int ret = 0;
TX_BEGIN(pop) {
ret = pmemobj_tx_free(OID_NULL);
} TX_ONABORT {
ret = -1;
} TX_END
UT_ASSERTeq(ret, 0);
}
/*
* do_tx_free_commit -- do the basic transactional deallocation of object
*/
static void
do_tx_free_commit(PMEMobjpool *pop)
{
int ret;
PMEMoid oid = do_tx_alloc(pop, TYPE_FREE_COMMIT);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid);
UT_ASSERTeq(ret, 0);
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_COMMIT));
UT_ASSERT(TOID_IS_NULL(obj));
}
/*
* do_tx_free_abort -- abort deallocation of object
*/
static void
do_tx_free_abort(PMEMobjpool *pop)
{
int ret;
PMEMoid oid = do_tx_alloc(pop, TYPE_FREE_ABORT);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid);
UT_ASSERTeq(ret, 0);
pmemobj_tx_abort(-1);
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_ABORT));
UT_ASSERT(!TOID_IS_NULL(obj));
}
/*
* do_tx_free_commit_nested -- do allocation in nested transaction
*/
static void
do_tx_free_commit_nested(PMEMobjpool *pop)
{
int ret;
PMEMoid oid1 = do_tx_alloc(pop, TYPE_FREE_COMMIT_NESTED1);
PMEMoid oid2 = do_tx_alloc(pop, TYPE_FREE_COMMIT_NESTED2);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid1);
UT_ASSERTeq(ret, 0);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid2);
UT_ASSERTeq(ret, 0);
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_COMMIT_NESTED1));
UT_ASSERT(TOID_IS_NULL(obj));
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_COMMIT_NESTED2));
UT_ASSERT(TOID_IS_NULL(obj));
}
/*
* do_tx_free_abort_nested -- abort allocation in nested transaction
*/
static void
do_tx_free_abort_nested(PMEMobjpool *pop)
{
int ret;
PMEMoid oid1 = do_tx_alloc(pop, TYPE_FREE_ABORT_NESTED1);
PMEMoid oid2 = do_tx_alloc(pop, TYPE_FREE_ABORT_NESTED2);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid1);
UT_ASSERTeq(ret, 0);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid2);
UT_ASSERTeq(ret, 0);
pmemobj_tx_abort(-1);
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_ABORT_NESTED1));
UT_ASSERT(!TOID_IS_NULL(obj));
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_ABORT_NESTED2));
UT_ASSERT(!TOID_IS_NULL(obj));
}
/*
* do_tx_free_abort_after_nested -- abort transaction after nested
* pmemobj_tx_free
*/
static void
do_tx_free_abort_after_nested(PMEMobjpool *pop)
{
int ret;
PMEMoid oid1 = do_tx_alloc(pop, TYPE_FREE_ABORT_AFTER_NESTED1);
PMEMoid oid2 = do_tx_alloc(pop, TYPE_FREE_ABORT_AFTER_NESTED2);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid1);
UT_ASSERTeq(ret, 0);
TX_BEGIN(pop) {
ret = pmemobj_tx_free(oid2);
UT_ASSERTeq(ret, 0);
} TX_END
pmemobj_tx_abort(-1);
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
TOID(struct object) obj;
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop,
TYPE_FREE_ABORT_AFTER_NESTED1));
UT_ASSERT(!TOID_IS_NULL(obj));
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop,
TYPE_FREE_ABORT_AFTER_NESTED2));
UT_ASSERT(!TOID_IS_NULL(obj));
}
/*
* do_tx_free_alloc_abort -- free object allocated in the same transaction
* and abort transaction
*/
static void
do_tx_free_alloc_abort(PMEMobjpool *pop)
{
int ret;
TOID(struct object) obj;
TX_BEGIN(pop) {
TOID_ASSIGN(obj, pmemobj_tx_alloc(
sizeof(struct object), TYPE_FREE_ALLOC));
UT_ASSERT(!TOID_IS_NULL(obj));
ret = pmemobj_tx_free(obj.oid);
UT_ASSERTeq(ret, 0);
pmemobj_tx_abort(-1);
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_ALLOC));
UT_ASSERT(TOID_IS_NULL(obj));
}
/*
* do_tx_free_alloc_abort -- free object allocated in the same transaction
* and commit transaction
*/
static void
do_tx_free_alloc_commit(PMEMobjpool *pop)
{
int ret;
TOID(struct object) obj;
TX_BEGIN(pop) {
TOID_ASSIGN(obj, pmemobj_tx_alloc(
sizeof(struct object), TYPE_FREE_ALLOC));
UT_ASSERT(!TOID_IS_NULL(obj));
ret = pmemobj_tx_free(obj.oid);
UT_ASSERTeq(ret, 0);
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
TOID_ASSIGN(obj, POBJ_FIRST_TYPE_NUM(pop, TYPE_FREE_ALLOC));
UT_ASSERT(TOID_IS_NULL(obj));
}
/*
* do_tx_free_abort_free - allocate a new object, perform a transactional free
* in an aborted transaction and then to actually free the object.
*
* This can expose any issues with not properly handled free undo log.
*/
static void
do_tx_free_abort_free(PMEMobjpool *pop)
{
PMEMoid oid = do_tx_alloc(pop, TYPE_FREE_AFTER_ABORT);
TX_BEGIN(pop) {
pmemobj_tx_free(oid);
pmemobj_tx_abort(-1);
} TX_ONCOMMIT {
UT_ASSERT(0);
} TX_END
TX_BEGIN(pop) {
pmemobj_tx_free(oid);
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
}
/*
* do_tx_free_many_times -- free enough objects to trigger vector array alloc
*/
static void
do_tx_free_many_times(PMEMobjpool *pop)
{
#define TX_FREE_COUNT ((1 << 3) + 1)
PMEMoid oids[TX_FREE_COUNT];
for (int i = 0; i < TX_FREE_COUNT; ++i)
oids[i] = do_tx_alloc(pop, TYPE_FREE_MANY_TIMES);
TX_BEGIN(pop) {
for (int i = 0; i < TX_FREE_COUNT; ++i)
pmemobj_tx_free(oids[i]);
} TX_ONABORT {
UT_ASSERT(0);
} TX_END
#undef TX_FREE_COUNT
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_tx_free");
util_init();
if (argc != 2)
UT_FATAL("usage: %s [file]", argv[0]);
PMEMobjpool *pop;
if ((pop = pmemobj_create(argv[1], LAYOUT_NAME, PMEMOBJ_MIN_POOL,
S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create");
do_tx_free_wrong_uuid(pop);
VALGRIND_WRITE_STATS;
do_tx_free_wrong_uuid_abort_on_failure(pop);
VALGRIND_WRITE_STATS;
do_tx_free_null_oid(pop);
VALGRIND_WRITE_STATS;
do_tx_free_commit(pop);
VALGRIND_WRITE_STATS;
do_tx_free_abort(pop);
VALGRIND_WRITE_STATS;
do_tx_free_commit_nested(pop);
VALGRIND_WRITE_STATS;
do_tx_free_abort_nested(pop);
VALGRIND_WRITE_STATS;
do_tx_free_abort_after_nested(pop);
VALGRIND_WRITE_STATS;
do_tx_free_alloc_commit(pop);
VALGRIND_WRITE_STATS;
do_tx_free_alloc_abort(pop);
VALGRIND_WRITE_STATS;
do_tx_free_abort_free(pop);
VALGRIND_WRITE_STATS;
do_tx_free_many_times(pop);
VALGRIND_WRITE_STATS;
pmemobj_close(pop);
DONE(NULL);
}
| 11,423 | 21.356164 | 78 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/util_uuid_generate/util_uuid_generate.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* util_uuid_generate.c -- unit test for generating a uuid
*
* usage: util_uuid_generate [string] [valid|invalid]
*/
#include "unittest.h"
#include "uuid.h"
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
START(argc, argv, "util_uuid_generate");
uuid_t uuid;
uuid_t uuid1;
int ret;
char conv_uu[POOL_HDR_UUID_STR_LEN];
char uu[POOL_HDR_UUID_STR_LEN];
/*
* No string passed in. Generate uuid.
*/
if (argc == 1) {
/* generate a UUID string */
ret = ut_get_uuid_str(uu);
UT_ASSERTeq(ret, 0);
/*
* Convert the string to a uuid, convert generated
* uuid back to a string and compare strings.
*/
ret = util_uuid_from_string(uu, (struct uuid *)&uuid);
UT_ASSERTeq(ret, 0);
ret = util_uuid_to_string(uuid, conv_uu);
UT_ASSERTeq(ret, 0);
UT_ASSERT(strncmp(uu, conv_uu, POOL_HDR_UUID_STR_LEN) == 0);
/*
* Generate uuid from util_uuid_generate and translate to
* string then back to uuid to verify they match.
*/
memset(uuid, 0, sizeof(uuid_t));
memset(uu, 0, POOL_HDR_UUID_STR_LEN);
memset(conv_uu, 0, POOL_HDR_UUID_STR_LEN);
ret = util_uuid_generate(uuid);
UT_ASSERTeq(ret, 0);
ret = util_uuid_to_string(uuid, uu);
UT_ASSERTeq(ret, 0);
ret = util_uuid_from_string(uu, (struct uuid *)&uuid1);
UT_ASSERTeq(ret, 0);
UT_ASSERT(memcmp(&uuid, &uuid1, sizeof(uuid_t)) == 0);
} else {
/*
* Caller passed in string.
*/
if (strcmp(argv[2], "valid") == 0) {
ret = util_uuid_from_string(argv[1],
(struct uuid *)&uuid);
UT_ASSERTeq(ret, 0);
ret = util_uuid_to_string(uuid, conv_uu);
UT_ASSERTeq(ret, 0);
} else {
ret = util_uuid_from_string(argv[1],
(struct uuid *)&uuid);
UT_ASSERT(ret < 0);
UT_OUT("util_uuid_generate: invalid uuid string");
}
}
DONE(NULL);
}
| 1,885 | 21.722892 | 62 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_pool_lookup/obj_pool_lookup.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2018, Intel Corporation */
/*
* obj_pool_lookup.c -- unit test for pmemobj_pool and pmemobj_pool_of
*/
#include "unittest.h"
#define MAX_PATH_LEN 255
#define LAYOUT_NAME "pool_lookup"
#define ALLOC_SIZE 100
static void
define_path(char *str, size_t size, const char *dir, unsigned i)
{
int ret = snprintf(str, size, "%s"OS_DIR_SEP_STR"testfile%d",
dir, i);
if (ret < 0 || ret >= size)
UT_FATAL("snprintf: %d", ret);
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_pool_lookup");
if (argc != 3)
UT_FATAL("usage: %s [directory] [# of pools]", argv[0]);
unsigned npools = ATOU(argv[2]);
const char *dir = argv[1];
int r;
/* check before pool creation */
PMEMoid some_oid = {2, 3};
UT_ASSERTeq(pmemobj_pool_by_ptr(&some_oid), NULL);
UT_ASSERTeq(pmemobj_pool_by_oid(some_oid), NULL);
PMEMobjpool **pops = MALLOC(npools * sizeof(PMEMobjpool *));
void **guard_after = MALLOC(npools * sizeof(void *));
size_t length = strlen(dir) + MAX_PATH_LEN;
char *path = MALLOC(length);
for (unsigned i = 0; i < npools; ++i) {
define_path(path, length, dir, i);
pops[i] = pmemobj_create(path, LAYOUT_NAME, PMEMOBJ_MIN_POOL,
S_IWUSR | S_IRUSR);
/*
* Reserve a page after the pool for address checks, if it
* doesn't map precisely at that address - it's OK.
*/
guard_after[i] =
MMAP((char *)pops[i] + PMEMOBJ_MIN_POOL, Ut_pagesize,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
UT_ASSERTne(guard_after[i], NULL);
if (pops[i] == NULL)
UT_FATAL("!pmemobj_create");
}
PMEMoid *oids = MALLOC(npools * sizeof(PMEMoid));
for (unsigned i = 0; i < npools; ++i) {
r = pmemobj_alloc(pops[i], &oids[i], ALLOC_SIZE, 1, NULL, NULL);
UT_ASSERTeq(r, 0);
}
PMEMoid invalid = {123, 321};
UT_ASSERTeq(pmemobj_pool_by_oid(OID_NULL), NULL);
UT_ASSERTeq(pmemobj_pool_by_oid(invalid), NULL);
for (unsigned i = 0; i < npools; ++i) {
UT_ASSERTeq(pmemobj_pool_by_oid(oids[i]), pops[i]);
}
UT_ASSERTeq(pmemobj_pool_by_ptr(NULL), NULL);
UT_ASSERTeq(pmemobj_pool_by_ptr((void *)0xCBA), NULL);
void *valid_ptr = MALLOC(ALLOC_SIZE);
UT_ASSERTeq(pmemobj_pool_by_ptr(valid_ptr), NULL);
FREE(valid_ptr);
for (unsigned i = 0; i < npools; ++i) {
void *before_pool = (char *)pops[i] - 1;
void *after_pool = (char *)pops[i] + PMEMOBJ_MIN_POOL + 1;
void *start_pool = (char *)pops[i];
void *end_pool = (char *)pops[i] + PMEMOBJ_MIN_POOL - 1;
void *edge = (char *)pops[i] + PMEMOBJ_MIN_POOL;
void *middle = (char *)pops[i] + (PMEMOBJ_MIN_POOL / 2);
void *in_oid = (char *)pmemobj_direct(oids[i]) +
(ALLOC_SIZE / 2);
UT_ASSERTeq(pmemobj_pool_by_ptr(before_pool), NULL);
UT_ASSERTeq(pmemobj_pool_by_ptr(after_pool), NULL);
UT_ASSERTeq(pmemobj_pool_by_ptr(start_pool), pops[i]);
UT_ASSERTeq(pmemobj_pool_by_ptr(end_pool), pops[i]);
UT_ASSERTeq(pmemobj_pool_by_ptr(edge), NULL);
UT_ASSERTeq(pmemobj_pool_by_ptr(middle), pops[i]);
UT_ASSERTeq(pmemobj_pool_by_ptr(in_oid), pops[i]);
pmemobj_close(pops[i]);
UT_ASSERTeq(pmemobj_pool_by_ptr(middle), NULL);
UT_ASSERTeq(pmemobj_pool_by_ptr(in_oid), NULL);
MUNMAP(guard_after[i], Ut_pagesize);
}
for (unsigned i = 0; i < npools; ++i) {
UT_ASSERTeq(pmemobj_pool_by_oid(oids[i]), NULL);
define_path(path, length, dir, i);
pops[i] = pmemobj_open(path, LAYOUT_NAME);
UT_ASSERTne(pops[i], NULL);
UT_ASSERTeq(pmemobj_pool_by_oid(oids[i]), pops[i]);
pmemobj_close(pops[i]);
}
FREE(path);
FREE(pops);
FREE(guard_after);
FREE(oids);
DONE(NULL);
}
| 3,576 | 26.305344 | 70 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_constructor/obj_constructor.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2017, Intel Corporation */
/*
* obj_constructor.c -- tests for constructor
*/
#include <stddef.h>
#include "unittest.h"
/*
* Command line toggle indicating use of a bigger node structure for querying
* pool size expressed in a number of possible allocations. A small node
* structure results in a great number of allocations impossible to replicate
* in assumed timeout. It is required by unit tests using remote replication to
* pass on Travis.
*/
#define USE_BIG_ALLOC "--big-alloc"
/*
* Layout definition
*/
POBJ_LAYOUT_BEGIN(constr);
POBJ_LAYOUT_ROOT(constr, struct root);
POBJ_LAYOUT_TOID(constr, struct node);
POBJ_LAYOUT_TOID(constr, struct node_big);
POBJ_LAYOUT_END(constr);
struct root {
TOID(struct node) n;
POBJ_LIST_HEAD(head, struct node) list;
POBJ_LIST_HEAD(head_big, struct node_big) list_big;
};
struct node {
POBJ_LIST_ENTRY(struct node) next;
};
struct node_big {
POBJ_LIST_ENTRY(struct node_big) next;
int weight[2048];
};
static int
root_constr_cancel(PMEMobjpool *pop, void *ptr, void *arg)
{
return 1;
}
static int
node_constr_cancel(PMEMobjpool *pop, void *ptr, void *arg)
{
return 1;
}
struct foo {
int bar;
};
static struct foo *Canceled_ptr;
static int
vg_test_save_ptr(PMEMobjpool *pop, void *ptr, void *arg)
{
Canceled_ptr = (struct foo *)ptr;
return 1;
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_constructor");
/* root doesn't count */
UT_COMPILE_ERROR_ON(POBJ_LAYOUT_TYPES_NUM(constr) != 2);
int big = (argc == 3 && strcmp(argv[2], USE_BIG_ALLOC) == 0);
size_t node_size;
size_t next_off;
if (big) {
node_size = sizeof(struct node_big);
next_off = offsetof(struct node_big, next);
} else if (argc == 2) {
node_size = sizeof(struct node);
next_off = offsetof(struct node, next);
} else {
UT_FATAL("usage: %s file-name [ %s ]", argv[0], USE_BIG_ALLOC);
}
const char *path = argv[1];
PMEMobjpool *pop = NULL;
int ret;
TOID(struct root) root;
TOID(struct node) node;
TOID(struct node_big) node_big;
if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(constr),
0, S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create: %s", path);
errno = 0;
root.oid = pmemobj_root_construct(pop, sizeof(struct root),
root_constr_cancel, NULL);
UT_ASSERT(TOID_IS_NULL(root));
UT_ASSERTeq(errno, ECANCELED);
/*
* Allocate memory until OOM, so we can check later if the alloc
* cancellation didn't damage the heap in any way.
*/
int allocs = 0;
while (pmemobj_alloc(pop, NULL, node_size, 1, NULL, NULL) == 0)
allocs++;
UT_ASSERTne(allocs, 0);
PMEMoid oid;
PMEMoid next;
POBJ_FOREACH_SAFE(pop, oid, next)
pmemobj_free(&oid);
errno = 0;
ret = pmemobj_alloc(pop, NULL, node_size, 1, node_constr_cancel, NULL);
UT_ASSERTeq(ret, -1);
UT_ASSERTeq(errno, ECANCELED);
/* the same number of allocations should be possible. */
while (pmemobj_alloc(pop, NULL, node_size, 1, NULL, NULL) == 0)
allocs--;
UT_ASSERT(allocs <= 0);
POBJ_FOREACH_SAFE(pop, oid, next)
pmemobj_free(&oid);
root.oid = pmemobj_root_construct(pop, sizeof(struct root),
NULL, NULL);
UT_ASSERT(!TOID_IS_NULL(root));
errno = 0;
if (big) {
node_big.oid = pmemobj_list_insert_new(pop, next_off,
&D_RW(root)->list_big, OID_NULL, 0, node_size,
1, node_constr_cancel, NULL);
UT_ASSERT(TOID_IS_NULL(node_big));
} else {
node.oid = pmemobj_list_insert_new(pop, next_off,
&D_RW(root)->list, OID_NULL, 0, node_size,
1, node_constr_cancel, NULL);
UT_ASSERT(TOID_IS_NULL(node));
}
UT_ASSERTeq(errno, ECANCELED);
pmemobj_alloc(pop, &oid, sizeof(struct foo), 1,
vg_test_save_ptr, NULL);
UT_ASSERTne(Canceled_ptr, NULL);
/* this should generate a valgrind memcheck warning */
Canceled_ptr->bar = 5;
pmemobj_persist(pop, &Canceled_ptr->bar, sizeof(Canceled_ptr->bar));
/*
* Allocate and cancel a huge object. It should return back to the
* heap and it should be possible to allocate it again.
*/
Canceled_ptr = NULL;
ret = pmemobj_alloc(pop, &oid, sizeof(struct foo) + (1 << 22), 1,
vg_test_save_ptr, NULL);
UT_ASSERTne(Canceled_ptr, NULL);
void *first_ptr = Canceled_ptr;
Canceled_ptr = NULL;
ret = pmemobj_alloc(pop, &oid, sizeof(struct foo) + (1 << 22), 1,
vg_test_save_ptr, NULL);
UT_ASSERTeq(first_ptr, Canceled_ptr);
pmemobj_close(pop);
DONE(NULL);
}
| 4,369 | 22.621622 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/util_poolset_parse/util_poolset_parse.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* obj_pool_sets_parser.c -- unit test for parsing a set file
*
* usage: obj_pool_sets_parser set-file ...
*/
#include "set.h"
#include "unittest.h"
#include "pmemcommon.h"
#include "fault_injection.h"
#define LOG_PREFIX "parser"
#define LOG_LEVEL_VAR "PARSER_LOG_LEVEL"
#define LOG_FILE_VAR "PARSER_LOG_FILE"
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
int
main(int argc, char *argv[])
{
START(argc, argv, "util_poolset_parse");
common_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR,
MAJOR_VERSION, MINOR_VERSION);
if (argc < 3)
UT_FATAL("usage: %s set-file-name ...", argv[0]);
struct pool_set *set;
int fd;
switch (argv[1][0]) {
case 't':
for (int i = 2; i < argc; i++) {
const char *path = argv[i];
fd = OPEN(path, O_RDWR);
int ret = util_poolset_parse(&set, path, fd);
if (ret == 0)
util_poolset_free(set);
CLOSE(fd);
}
break;
case 'f':
if (!core_fault_injection_enabled())
break;
const char *path = argv[2];
fd = OPEN(path, O_RDWR);
core_inject_fault_at(PMEM_MALLOC, 1,
"util_poolset_directories_load");
int ret = util_poolset_parse(&set, path, fd);
UT_ASSERTne(ret, 0);
UT_ASSERTeq(errno, ENOMEM);
CLOSE(fd);
}
common_fini();
DONE(NULL);
}
| 1,321 | 18.15942 | 61 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/log_recovery/log_recovery.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* log_recovery.c -- unit test for pmemlog recovery
*
* usage: log_recovery file operation:...
*
* operation has to be 'a' or 'v'
*
*/
#include <sys/param.h>
#include "unittest.h"
#include "log.h"
/*
* do_append -- call pmemlog_append() & print result
*/
static void
do_append(PMEMlogpool *plp)
{
const char *str[6] = {
"1st append string\n",
"2nd append string\n",
"3rd append string\n",
"4th append string\n",
"5th append string\n",
"6th append string\n"
};
for (int i = 0; i < 6; ++i) {
int rv = pmemlog_append(plp, str[i], strlen(str[i]));
switch (rv) {
case 0:
UT_OUT("append str[%i] %s", i, str[i]);
break;
case -1:
UT_OUT("!append str[%i] %s", i, str[i]);
break;
default:
UT_OUT("!append: wrong return value");
break;
}
}
}
/*
* do_appendv -- call pmemlog_appendv() & print result
*/
static void
do_appendv(PMEMlogpool *plp)
{
struct iovec iov[9] = {
{
.iov_base = "1st appendv string\n",
.iov_len = 19
},
{
.iov_base = "2nd appendv string\n",
.iov_len = 19
},
{
.iov_base = "3rd appendv string\n",
.iov_len = 19
},
{
.iov_base = "4th appendv string\n",
.iov_len = 19
},
{
.iov_base = "5th appendv string\n",
.iov_len = 19
},
{
.iov_base = "6th appendv string\n",
.iov_len = 19
},
{
.iov_base = "7th appendv string\n",
.iov_len = 19
},
{
.iov_base = "8th appendv string\n",
.iov_len = 19
},
{
.iov_base = "9th appendv string\n",
.iov_len = 19
}
};
int rv = pmemlog_appendv(plp, iov, 9);
switch (rv) {
case 0:
UT_OUT("appendv");
break;
case -1:
UT_OUT("!appendv");
break;
default:
UT_OUT("!appendv: wrong return value");
break;
}
}
/*
* do_tell -- call pmemlog_tell() & print result
*/
static void
do_tell(PMEMlogpool *plp)
{
os_off_t tell = pmemlog_tell(plp);
UT_OUT("tell %zu", tell);
}
/*
* printit -- print out the 'buf' of length 'len'.
*
* It is a walker function for pmemlog_walk
*/
static int
printit(const void *buf, size_t len, void *arg)
{
char *str = MALLOC(len + 1);
strncpy(str, buf, len);
str[len] = '\0';
UT_OUT("%s", str);
FREE(str);
return 0;
}
/*
* do_walk -- call pmemlog_walk() & print result
*/
static void
do_walk(PMEMlogpool *plp)
{
pmemlog_walk(plp, 0, printit, NULL);
UT_OUT("walk all at once");
}
static ut_jmp_buf_t Jmp;
/*
* signal_handler -- called on SIGSEGV
*/
static void
signal_handler(int sig)
{
UT_OUT("signal: %s", os_strsignal(sig));
ut_siglongjmp(Jmp);
}
int
main(int argc, char *argv[])
{
PMEMlogpool *plp;
int result;
START(argc, argv, "log_recovery");
if (argc != 3)
UT_FATAL("usage: %s file-name op:a|v", argv[0]);
if (strchr("av", argv[2][0]) == NULL || argv[2][1] != '\0')
UT_FATAL("op must be a or v");
const char *path = argv[1];
int fd = OPEN(path, O_RDWR);
/* pre-allocate 2MB of persistent memory */
POSIX_FALLOCATE(fd, (os_off_t)0, (size_t)(2 * 1024 * 1024));
CLOSE(fd);
if ((plp = pmemlog_create(path, 0, S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemlog_create: %s", path);
/* append some data */
if (argv[2][0] == 'a')
do_append(plp);
else
do_appendv(plp);
/* print out current write point */
do_tell(plp);
size_t len = roundup(sizeof(*plp), LOG_FORMAT_DATA_ALIGN);
UT_OUT("write-protecting the metadata, length %zu", len);
MPROTECT(plp, len, PROT_READ);
/* arrange to catch SEGV */
struct sigaction v;
sigemptyset(&v.sa_mask);
v.sa_flags = 0;
v.sa_handler = signal_handler;
SIGACTION(SIGSEGV, &v, NULL);
if (!ut_sigsetjmp(Jmp)) {
/* try to append more data */
if (argv[2][0] == 'a')
do_append(plp);
else
do_appendv(plp);
}
MPROTECT(plp, len, PROT_READ | PROT_WRITE);
pmemlog_close(plp);
/* check consistency */
result = pmemlog_check(path);
if (result < 0)
UT_OUT("!%s: pmemlog_check", path);
else if (result == 0)
UT_OUT("%s: pmemlog_check: not consistent", path);
else
UT_OUT("%s: consistent", path);
/* map again to print out whole log */
if ((plp = pmemlog_open(path)) == NULL)
UT_FATAL("!pmemlog_open: %s", path);
/* print out current write point */
do_tell(plp);
/* print out whole log */
do_walk(plp);
pmemlog_close(plp);
DONE(NULL);
}
| 4,290 | 17.029412 | 64 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/obj_heap_state/obj_heap_state.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2017, Intel Corporation */
/*
* obj_heap_state.c -- volatile heap state verification test
*/
#include <stddef.h>
#include "unittest.h"
#define LAYOUT_NAME "heap_state"
#define ROOT_SIZE 256
#define ALLOCS 100
#define ALLOC_SIZE 50
static char buf[ALLOC_SIZE];
static int
test_constructor(PMEMobjpool *pop, void *addr, void *args)
{
/* do not use pmem_memcpy_persist() here */
pmemobj_memcpy_persist(pop, addr, buf, ALLOC_SIZE);
return 0;
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_heap_state");
if (argc != 2)
UT_FATAL("usage: %s file-name", argv[0]);
const char *path = argv[1];
for (int i = 0; i < ALLOC_SIZE; i++)
buf[i] = rand() % 256;
PMEMobjpool *pop = NULL;
if ((pop = pmemobj_create(path, LAYOUT_NAME,
0, S_IWUSR | S_IRUSR)) == NULL)
UT_FATAL("!pmemobj_create: %s", path);
pmemobj_root(pop, ROOT_SIZE); /* just to trigger allocation */
pmemobj_close(pop);
pop = pmemobj_open(path, LAYOUT_NAME);
UT_ASSERTne(pop, NULL);
for (int i = 0; i < ALLOCS; ++i) {
PMEMoid oid;
pmemobj_alloc(pop, &oid, ALLOC_SIZE, 0,
test_constructor, NULL);
UT_OUT("%d %lu", i, oid.off);
}
pmemobj_close(pop);
DONE(NULL);
}
| 1,239 | 18.076923 | 63 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/out_err/out_err.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* traces.c -- unit test for traces
*/
#define LOG_PREFIX "trace"
#define LOG_LEVEL_VAR "TRACE_LOG_LEVEL"
#define LOG_FILE_VAR "TRACE_LOG_FILE"
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
#include <sys/types.h>
#include <stdarg.h>
#include "unittest.h"
#include "pmemcommon.h"
int
main(int argc, char *argv[])
{
char buff[UT_MAX_ERR_MSG];
START(argc, argv, "out_err");
/* Execute test */
common_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR,
MAJOR_VERSION, MINOR_VERSION);
errno = 0;
ERR("ERR #%d", 1);
UT_OUT("%s", out_get_errormsg());
errno = 0;
ERR("!ERR #%d", 2);
UT_OUT("%s", out_get_errormsg());
errno = EINVAL;
ERR("!ERR #%d", 3);
UT_OUT("%s", out_get_errormsg());
errno = EBADF;
ut_strerror(errno, buff, UT_MAX_ERR_MSG);
out_err(__FILE__, 100, __func__,
"ERR1: %s:%d", buff, 1234);
UT_OUT("%s", out_get_errormsg());
errno = EBADF;
ut_strerror(errno, buff, UT_MAX_ERR_MSG);
out_err(NULL, 0, NULL,
"ERR2: %s:%d", buff, 1234);
UT_OUT("%s", out_get_errormsg());
/* Cleanup */
common_fini();
DONE(NULL);
}
| 1,146 | 18.440678 | 53 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/unittest.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* unittest.h -- the mundane stuff shared by all unit tests
*
* we want unit tests to be very thorough and check absolutely everything
* in order to nail down the test case as precisely as possible and flag
* anything at all unexpected. as a result, most unit tests are 90% code
* checking stuff that isn't really interesting to what is being tested.
* to help address this, the macros defined here include all the boilerplate
* error checking which prints information and exits on unexpected errors.
*
* the result changes this code:
*
* if ((buf = malloc(size)) == NULL) {
* fprintf(stderr, "cannot allocate %d bytes for buf\n", size);
* exit(1);
* }
*
* into this code:
*
* buf = MALLOC(size);
*
* and the error message includes the calling context information (file:line).
* in general, using the all-caps version of a call means you're using the
* unittest.h version which does the most common checking for you. so
* calling VMEM_CREATE() instead of vmem_create() returns the same
* thing, but can never return an error since the unit test library checks for
* it. * for routines like vmem_delete() there is no corresponding
* VMEM_DELETE() because there's no error to check for.
*
* all unit tests should use the same initialization:
*
* START(argc, argv, "brief test description", ...);
*
* all unit tests should use these exit calls:
*
* DONE("message", ...);
* UT_FATAL("message", ...);
*
* uniform stderr and stdout messages:
*
* UT_OUT("message", ...);
* UT_ERR("message", ...);
*
* in all cases above, the message is printf-like, taking variable args.
* the message can be NULL. it can start with "!" in which case the "!" is
* skipped and the message gets the errno string appended to it, like this:
*
* if (somesyscall(..) < 0)
* UT_FATAL("!my message");
*/
#ifndef _UNITTEST_H
#define _UNITTEST_H 1
#include <libpmem.h>
#include <libpmem2.h>
#include <libpmemblk.h>
#include <libpmemlog.h>
#include <libpmemobj.h>
#include <libpmempool.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <setjmp.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/file.h>
#ifndef __FreeBSD__
#include <sys/mount.h>
#endif
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <dirent.h>
/* XXX: move OS abstraction layer out of common */
#include "os.h"
#include "os_thread.h"
#include "util.h"
int ut_get_uuid_str(char *);
#define UT_MAX_ERR_MSG 128
#define UT_POOL_HDR_UUID_STR_LEN 37 /* uuid string length */
#define UT_POOL_HDR_UUID_GEN_FILE "/proc/sys/kernel/random/uuid"
/* XXX - fix this temp hack dup'ing util_strerror when we get mock for win */
void ut_strerror(int errnum, char *buff, size_t bufflen);
/* XXX - eliminate duplicated definitions in unittest.h and util.h */
#ifdef _WIN32
static inline int ut_util_statW(const wchar_t *path,
os_stat_t *st_bufp) {
int retVal = _wstat64(path, st_bufp);
/* clear unused bits to avoid confusion */
st_bufp->st_mode &= 0600;
return retVal;
}
#endif
/*
* unit test support...
*/
void ut_start(const char *file, int line, const char *func,
int argc, char * const argv[], const char *fmt, ...)
__attribute__((format(printf, 6, 7)));
void ut_startW(const char *file, int line, const char *func,
int argc, wchar_t * const argv[], const char *fmt, ...)
__attribute__((format(printf, 6, 7)));
void NORETURN ut_done(const char *file, int line, const char *func,
const char *fmt, ...)
__attribute__((format(printf, 4, 5)));
void NORETURN ut_fatal(const char *file, int line, const char *func,
const char *fmt, ...)
__attribute__((format(printf, 4, 5)));
void NORETURN ut_end(const char *file, int line, const char *func,
int ret);
void ut_out(const char *file, int line, const char *func,
const char *fmt, ...)
__attribute__((format(printf, 4, 5)));
void ut_err(const char *file, int line, const char *func,
const char *fmt, ...)
__attribute__((format(printf, 4, 5)));
/* indicate the start of the test */
#ifndef _WIN32
#define START(argc, argv, ...)\
ut_start(__FILE__, __LINE__, __func__, argc, argv, __VA_ARGS__)
#else
#define START(argc, argv, ...)\
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);\
for (int i = 0; i < argc; i++) {\
argv[i] = ut_toUTF8(wargv[i]);\
if (argv[i] == NULL) {\
for (i--; i >= 0; i--)\
free(argv[i]);\
UT_FATAL("Error during arguments conversion\n");\
}\
}\
ut_start(__FILE__, __LINE__, __func__, argc, argv, __VA_ARGS__)
#endif
/* indicate the start of the test */
#define STARTW(argc, argv, ...)\
ut_startW(__FILE__, __LINE__, __func__, argc, argv, __VA_ARGS__)
/* normal exit from test */
#ifndef _WIN32
#define DONE(...)\
ut_done(__FILE__, __LINE__, __func__, __VA_ARGS__)
#else
#define DONE(...)\
for (int i = argc; i > 0; i--)\
free(argv[i - 1]);\
ut_done(__FILE__, __LINE__, __func__, __VA_ARGS__)
#endif
#define DONEW(...)\
ut_done(__FILE__, __LINE__, __func__, __VA_ARGS__)
#define END(ret, ...)\
ut_end(__FILE__, __LINE__, __func__, ret)
/* fatal error detected */
#define UT_FATAL(...)\
ut_fatal(__FILE__, __LINE__, __func__, __VA_ARGS__)
/* normal output */
#define UT_OUT(...)\
ut_out(__FILE__, __LINE__, __func__, __VA_ARGS__)
/* error output */
#define UT_ERR(...)\
ut_err(__FILE__, __LINE__, __func__, __VA_ARGS__)
/*
* assertions...
*/
/* assert a condition is true at runtime */
#define UT_ASSERT_rt(cnd)\
((void)((cnd) || (ut_fatal(__FILE__, __LINE__, __func__,\
"assertion failure: %s", #cnd), 0)))
/* assertion with extra info printed if assertion fails at runtime */
#define UT_ASSERTinfo_rt(cnd, info) \
((void)((cnd) || (ut_fatal(__FILE__, __LINE__, __func__,\
"assertion failure: %s (%s)", #cnd, info), 0)))
/* assert two integer values are equal at runtime */
#define UT_ASSERTeq_rt(lhs, rhs)\
((void)(((lhs) == (rhs)) || (ut_fatal(__FILE__, __LINE__, __func__,\
"assertion failure: %s (0x%llx) == %s (0x%llx)", #lhs,\
(unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)), 0)))
/* assert two integer values are not equal at runtime */
#define UT_ASSERTne_rt(lhs, rhs)\
((void)(((lhs) != (rhs)) || (ut_fatal(__FILE__, __LINE__, __func__,\
"assertion failure: %s (0x%llx) != %s (0x%llx)", #lhs,\
(unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)), 0)))
#if defined(__CHECKER__)
#define UT_COMPILE_ERROR_ON(cond)
#define UT_ASSERT_COMPILE_ERROR_ON(cond)
#elif defined(_MSC_VER)
#define UT_COMPILE_ERROR_ON(cond) C_ASSERT(!(cond))
/* XXX - can't be done with C_ASSERT() unless we have __builtin_constant_p() */
#define UT_ASSERT_COMPILE_ERROR_ON(cond) (void)(cond)
#else
#define UT_COMPILE_ERROR_ON(cond) ((void)sizeof(char[(cond) ? -1 : 1]))
#ifndef __cplusplus
#define UT_ASSERT_COMPILE_ERROR_ON(cond) UT_COMPILE_ERROR_ON(cond)
#else /* __cplusplus */
/*
* XXX - workaround for https://github.com/pmem/issues/issues/189
*/
#define UT_ASSERT_COMPILE_ERROR_ON(cond) UT_ASSERT_rt(!(cond))
#endif /* __cplusplus */
#endif /* _MSC_VER */
/* assert a condition is true */
#define UT_ASSERT(cnd)\
do {\
/*\
* Detect useless asserts on always true expression. Please use\
* UT_COMPILE_ERROR_ON(!cnd) or UT_ASSERT_rt(cnd) in such\
* cases.\
*/\
if (__builtin_constant_p(cnd))\
UT_ASSERT_COMPILE_ERROR_ON(cnd);\
UT_ASSERT_rt(cnd);\
} while (0)
/* assertion with extra info printed if assertion fails */
#define UT_ASSERTinfo(cnd, info) \
do {\
/* See comment in UT_ASSERT. */\
if (__builtin_constant_p(cnd))\
UT_ASSERT_COMPILE_ERROR_ON(cnd);\
UT_ASSERTinfo_rt(cnd, info);\
} while (0)
/* assert two integer values are equal */
#define UT_ASSERTeq(lhs, rhs)\
do {\
/* See comment in UT_ASSERT. */\
if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\
UT_ASSERT_COMPILE_ERROR_ON((lhs) == (rhs));\
UT_ASSERTeq_rt(lhs, rhs);\
} while (0)
/* assert two integer values are not equal */
#define UT_ASSERTne(lhs, rhs)\
do {\
/* See comment in UT_ASSERT. */\
if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\
UT_ASSERT_COMPILE_ERROR_ON((lhs) != (rhs));\
UT_ASSERTne_rt(lhs, rhs);\
} while (0)
/* assert pointer is fits range of [start, start + size) */
#define UT_ASSERTrange(ptr, start, size)\
((void)(((uintptr_t)(ptr) >= (uintptr_t)(start) &&\
(uintptr_t)(ptr) < (uintptr_t)(start) + (uintptr_t)(size)) ||\
(ut_fatal(__FILE__, __LINE__, __func__,\
"assert failure: %s (%p) is outside range [%s (%p), %s (%p))", #ptr,\
(void *)(ptr), #start, (void *)(start), #start"+"#size,\
(void *)((uintptr_t)(start) + (uintptr_t)(size))), 0)))
/*
* memory allocation...
*/
void *ut_malloc(const char *file, int line, const char *func, size_t size);
void *ut_calloc(const char *file, int line, const char *func,
size_t nmemb, size_t size);
void ut_free(const char *file, int line, const char *func, void *ptr);
void ut_aligned_free(const char *file, int line, const char *func, void *ptr);
void *ut_realloc(const char *file, int line, const char *func,
void *ptr, size_t size);
char *ut_strdup(const char *file, int line, const char *func,
const char *str);
void *ut_pagealignmalloc(const char *file, int line, const char *func,
size_t size);
void *ut_memalign(const char *file, int line, const char *func,
size_t alignment, size_t size);
void *ut_mmap_anon_aligned(const char *file, int line, const char *func,
size_t alignment, size_t size);
int ut_munmap_anon_aligned(const char *file, int line, const char *func,
void *start, size_t size);
/* a malloc() that can't return NULL */
#define MALLOC(size)\
ut_malloc(__FILE__, __LINE__, __func__, size)
/* a calloc() that can't return NULL */
#define CALLOC(nmemb, size)\
ut_calloc(__FILE__, __LINE__, __func__, nmemb, size)
/* a malloc() of zeroed memory */
#define ZALLOC(size)\
ut_calloc(__FILE__, __LINE__, __func__, 1, size)
#define FREE(ptr)\
ut_free(__FILE__, __LINE__, __func__, ptr)
#define ALIGNED_FREE(ptr)\
ut_aligned_free(__FILE__, __LINE__, __func__, ptr)
/* a realloc() that can't return NULL */
#define REALLOC(ptr, size)\
ut_realloc(__FILE__, __LINE__, __func__, ptr, size)
/* a strdup() that can't return NULL */
#define STRDUP(str)\
ut_strdup(__FILE__, __LINE__, __func__, str)
/* a malloc() that only returns page aligned memory */
#define PAGEALIGNMALLOC(size)\
ut_pagealignmalloc(__FILE__, __LINE__, __func__, size)
/* a malloc() that returns memory with given alignment */
#define MEMALIGN(alignment, size)\
ut_memalign(__FILE__, __LINE__, __func__, alignment, size)
/*
* A mmap() that returns anonymous memory with given alignment and guard
* pages.
*/
#define MMAP_ANON_ALIGNED(size, alignment)\
ut_mmap_anon_aligned(__FILE__, __LINE__, __func__, alignment, size)
#define MUNMAP_ANON_ALIGNED(start, size)\
ut_munmap_anon_aligned(__FILE__, __LINE__, __func__, start, size)
/*
* file operations
*/
int ut_open(const char *file, int line, const char *func, const char *path,
int flags, ...);
int ut_wopen(const char *file, int line, const char *func, const wchar_t *path,
int flags, ...);
int ut_close(const char *file, int line, const char *func, int fd);
FILE *ut_fopen(const char *file, int line, const char *func, const char *path,
const char *mode);
int ut_fclose(const char *file, int line, const char *func, FILE *stream);
int ut_unlink(const char *file, int line, const char *func, const char *path);
size_t ut_write(const char *file, int line, const char *func, int fd,
const void *buf, size_t len);
size_t ut_read(const char *file, int line, const char *func, int fd,
void *buf, size_t len);
os_off_t ut_lseek(const char *file, int line, const char *func, int fd,
os_off_t offset, int whence);
int ut_posix_fallocate(const char *file, int line, const char *func, int fd,
os_off_t offset, os_off_t len);
int ut_stat(const char *file, int line, const char *func, const char *path,
os_stat_t *st_bufp);
int ut_statW(const char *file, int line, const char *func, const wchar_t *path,
os_stat_t *st_bufp);
int ut_fstat(const char *file, int line, const char *func, int fd,
os_stat_t *st_bufp);
void *ut_mmap(const char *file, int line, const char *func, void *addr,
size_t length, int prot, int flags, int fd, os_off_t offset);
int ut_munmap(const char *file, int line, const char *func, void *addr,
size_t length);
int ut_mprotect(const char *file, int line, const char *func, void *addr,
size_t len, int prot);
int ut_ftruncate(const char *file, int line, const char *func,
int fd, os_off_t length);
long long ut_strtoll(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
long ut_strtol(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
int ut_strtoi(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
unsigned long long ut_strtoull(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
unsigned long ut_strtoul(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
unsigned ut_strtou(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base);
int ut_snprintf(const char *file, int line, const char *func,
char *str, size_t size, const char *format, ...);
/* an open() that can't return < 0 */
#define OPEN(path, ...)\
ut_open(__FILE__, __LINE__, __func__, path, __VA_ARGS__)
/* a _wopen() that can't return < 0 */
#define WOPEN(path, ...)\
ut_wopen(__FILE__, __LINE__, __func__, path, __VA_ARGS__)
/* a close() that can't return -1 */
#define CLOSE(fd)\
ut_close(__FILE__, __LINE__, __func__, fd)
/* an fopen() that can't return != 0 */
#define FOPEN(path, mode)\
ut_fopen(__FILE__, __LINE__, __func__, path, mode)
/* a fclose() that can't return != 0 */
#define FCLOSE(stream)\
ut_fclose(__FILE__, __LINE__, __func__, stream)
/* an unlink() that can't return -1 */
#define UNLINK(path)\
ut_unlink(__FILE__, __LINE__, __func__, path)
/* a write() that can't return -1 */
#define WRITE(fd, buf, len)\
ut_write(__FILE__, __LINE__, __func__, fd, buf, len)
/* a read() that can't return -1 */
#define READ(fd, buf, len)\
ut_read(__FILE__, __LINE__, __func__, fd, buf, len)
/* a lseek() that can't return -1 */
#define LSEEK(fd, offset, whence)\
ut_lseek(__FILE__, __LINE__, __func__, fd, offset, whence)
#define POSIX_FALLOCATE(fd, off, len)\
ut_posix_fallocate(__FILE__, __LINE__, __func__, fd, off, len)
#define FSTAT(fd, st_bufp)\
ut_fstat(__FILE__, __LINE__, __func__, fd, st_bufp)
/* a mmap() that can't return MAP_FAILED */
#define MMAP(addr, len, prot, flags, fd, offset)\
ut_mmap(__FILE__, __LINE__, __func__, addr, len, prot, flags, fd, offset);
/* a munmap() that can't return -1 */
#define MUNMAP(addr, length)\
ut_munmap(__FILE__, __LINE__, __func__, addr, length);
/* a mprotect() that can't return -1 */
#define MPROTECT(addr, len, prot)\
ut_mprotect(__FILE__, __LINE__, __func__, addr, len, prot);
#define STAT(path, st_bufp)\
ut_stat(__FILE__, __LINE__, __func__, path, st_bufp)
#define STATW(path, st_bufp)\
ut_statW(__FILE__, __LINE__, __func__, path, st_bufp)
#define FTRUNCATE(fd, length)\
ut_ftruncate(__FILE__, __LINE__, __func__, fd, length)
#define ATOU(nptr) STRTOU(nptr, NULL, 10)
#define ATOUL(nptr) STRTOUL(nptr, NULL, 10)
#define ATOULL(nptr) STRTOULL(nptr, NULL, 10)
#define ATOI(nptr) STRTOI(nptr, NULL, 10)
#define ATOL(nptr) STRTOL(nptr, NULL, 10)
#define ATOLL(nptr) STRTOLL(nptr, NULL, 10)
#define STRTOULL(nptr, endptr, base)\
ut_strtoull(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define STRTOUL(nptr, endptr, base)\
ut_strtoul(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define STRTOL(nptr, endptr, base)\
ut_strtol(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define STRTOLL(nptr, endptr, base)\
ut_strtoll(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define STRTOU(nptr, endptr, base)\
ut_strtou(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define STRTOI(nptr, endptr, base)\
ut_strtoi(__FILE__, __LINE__, __func__, nptr, endptr, base)
#define SNPRINTF(str, size, format, ...) \
ut_snprintf(__FILE__, __LINE__, __func__, \
str, size, format, __VA_ARGS__)
#ifndef _WIN32
#define ut_jmp_buf_t sigjmp_buf
#define ut_siglongjmp(b) siglongjmp(b, 1)
#define ut_sigsetjmp(b) sigsetjmp(b, 1)
#else
#define ut_jmp_buf_t jmp_buf
#define ut_siglongjmp(b) longjmp(b, 1)
#define ut_sigsetjmp(b) setjmp(b)
#endif
void ut_suppress_errmsg(void);
void ut_unsuppress_errmsg(void);
void ut_suppress_crt_assert(void);
void ut_unsuppress_crt_assert(void);
/*
* signals...
*/
int ut_sigaction(const char *file, int line, const char *func,
int signum, struct sigaction *act, struct sigaction *oldact);
/* a sigaction() that can't return an error */
#define SIGACTION(signum, act, oldact)\
ut_sigaction(__FILE__, __LINE__, __func__, signum, act, oldact)
/*
* pthreads...
*/
int ut_thread_create(const char *file, int line, const char *func,
os_thread_t *__restrict thread,
const os_thread_attr_t *__restrict attr,
void *(*start_routine)(void *), void *__restrict arg);
int ut_thread_join(const char *file, int line, const char *func,
os_thread_t *thread, void **value_ptr);
/* a os_thread_create() that can't return an error */
#define THREAD_CREATE(thread, attr, start_routine, arg)\
ut_thread_create(__FILE__, __LINE__, __func__,\
thread, attr, start_routine, arg)
/* a os_thread_join() that can't return an error */
#define THREAD_JOIN(thread, value_ptr)\
ut_thread_join(__FILE__, __LINE__, __func__, thread, value_ptr)
/*
* processes...
*/
#ifdef _WIN32
intptr_t ut_spawnv(int argc, const char **argv, ...);
#endif
/*
* mocks...
*
* NOTE: On Linux, function mocking is implemented using wrapper functions.
* See "--wrap" option of the GNU linker.
* There is no such feature in VC++, so on Windows we do the mocking at
* compile time, by redefining symbol names:
* - all the references to <symbol> are replaced with <__wrap_symbol>
* in all the compilation units, except the one where the <symbol> is
* defined and the test source file
* - the original definition of <symbol> is replaced with <__real_symbol>
* - a wrapper function <__wrap_symbol> must be defined in the test program
* (it may still call the original function via <__real_symbol>)
* Such solution seems to be sufficient for the purpose of our tests, even
* though it has some limitations. I.e. it does no work well with malloc/free,
* so to wrap the system memory allocator functions, we use the built-in
* feature of all the PMDK libraries, allowing to override default memory
* allocator with the custom one.
*/
#ifndef _WIN32
#define _FUNC_REAL_DECL(name, ret_type, ...)\
ret_type __real_##name(__VA_ARGS__) __attribute__((unused));
#else
#define _FUNC_REAL_DECL(name, ret_type, ...)\
ret_type name(__VA_ARGS__);
#endif
#ifndef _WIN32
#define _FUNC_REAL(name)\
__real_##name
#else
#define _FUNC_REAL(name)\
name
#endif
#define RCOUNTER(name)\
_rcounter##name
#define FUNC_MOCK_RCOUNTER_SET(name, val)\
RCOUNTER(name) = val;
#define FUNC_MOCK(name, ret_type, ...)\
_FUNC_REAL_DECL(name, ret_type, ##__VA_ARGS__)\
static unsigned RCOUNTER(name);\
ret_type __wrap_##name(__VA_ARGS__);\
ret_type __wrap_##name(__VA_ARGS__) {\
switch (util_fetch_and_add32(&RCOUNTER(name), 1)) {
#define FUNC_MOCK_DLLIMPORT(name, ret_type, ...)\
__declspec(dllimport) _FUNC_REAL_DECL(name, ret_type, ##__VA_ARGS__)\
static unsigned RCOUNTER(name);\
ret_type __wrap_##name(__VA_ARGS__);\
ret_type __wrap_##name(__VA_ARGS__) {\
switch (util_fetch_and_add32(&RCOUNTER(name), 1)) {
#define FUNC_MOCK_END\
}}
#define FUNC_MOCK_RUN(run)\
case run:
#define FUNC_MOCK_RUN_DEFAULT\
default:
#define FUNC_MOCK_RUN_RET(run, ret)\
case run: return (ret);
#define FUNC_MOCK_RUN_RET_DEFAULT_REAL(name, ...)\
default: return _FUNC_REAL(name)(__VA_ARGS__);
#define FUNC_MOCK_RUN_RET_DEFAULT(ret)\
default: return (ret);
#define FUNC_MOCK_RET_ALWAYS(name, ret_type, ret, ...)\
FUNC_MOCK(name, ret_type, __VA_ARGS__)\
FUNC_MOCK_RUN_RET_DEFAULT(ret);\
FUNC_MOCK_END
#define FUNC_MOCK_RET_ALWAYS_VOID(name, ...)\
FUNC_MOCK(name, void, __VA_ARGS__)\
default: return;\
FUNC_MOCK_END
extern unsigned long Ut_pagesize;
extern unsigned long long Ut_mmap_align;
extern os_mutex_t Sigactions_lock;
void ut_dump_backtrace(void);
void ut_sighandler(int);
void ut_register_sighandlers(void);
uint16_t ut_checksum(uint8_t *addr, size_t len);
char *ut_toUTF8(const wchar_t *wstr);
wchar_t *ut_toUTF16(const char *wstr);
struct test_case {
const char *name;
int (*func)(const struct test_case *tc, int argc, char *argv[]);
};
/*
* get_tc -- return test case of specified name
*/
static inline const struct test_case *
get_tc(const char *name, const struct test_case *test_cases, size_t ntests)
{
for (size_t i = 0; i < ntests; i++) {
if (strcmp(name, test_cases[i].name) == 0)
return &test_cases[i];
}
return NULL;
}
static inline void
TEST_CASE_PROCESS(int argc, char *argv[],
const struct test_case *test_cases, size_t ntests)
{
if (argc < 2)
UT_FATAL("usage: %s <test case> [<args>]", argv[0]);
for (int i = 1; i < argc; i++) {
char *str_test = argv[i];
const int args_off = i + 1;
const struct test_case *tc = get_tc(str_test,
test_cases, ntests);
if (!tc)
UT_FATAL("unknown test case -- '%s'", str_test);
int ret = tc->func(tc, argc - args_off, &argv[args_off]);
if (ret < 0)
UT_FATAL("test return value cannot be negative");
i += ret;
}
}
#define TEST_CASE_DECLARE(_name)\
int \
_name(const struct test_case *tc, int argc, char *argv[])
#define TEST_CASE(_name)\
{\
.name = #_name,\
.func = (_name),\
}
#define STR(x) #x
#define ASSERT_ALIGNED_BEGIN(type) do {\
size_t off = 0;\
const char *last = "(none)";\
type t;
#define ASSERT_ALIGNED_FIELD(type, field) do {\
if (offsetof(type, field) != off)\
UT_FATAL("%s: padding, missing field or fields not in order between "\
"'%s' and '%s' -- offset %lu, real offset %lu",\
STR(type), last, STR(field), off, offsetof(type, field));\
off += sizeof(t.field);\
last = STR(field);\
} while (0)
#define ASSERT_FIELD_SIZE(field, size) do {\
UT_COMPILE_ERROR_ON(size != sizeof(t.field));\
} while (0)
#define ASSERT_OFFSET_CHECKPOINT(type, checkpoint) do {\
if (off != checkpoint)\
UT_FATAL("%s: violated offset checkpoint -- "\
"checkpoint %lu, real offset %lu",\
STR(type), checkpoint, off);\
} while (0)
#define ASSERT_ALIGNED_CHECK(type)\
if (off != sizeof(type))\
UT_FATAL("%s: missing field or padding after '%s': "\
"sizeof(%s) = %lu, fields size = %lu",\
STR(type), last, STR(type), sizeof(type), off);\
} while (0)
/*
* AddressSanitizer
*/
#ifdef __clang__
#if __has_feature(address_sanitizer)
#define UT_DEFINE_ASAN_POISON
#endif
#else
#ifdef __SANITIZE_ADDRESS__
#define UT_DEFINE_ASAN_POISON
#endif
#endif
#ifdef UT_DEFINE_ASAN_POISON
void __asan_poison_memory_region(void const volatile *addr, size_t size);
void __asan_unpoison_memory_region(void const volatile *addr, size_t size);
#define ASAN_POISON_MEMORY_REGION(addr, size) \
__asan_poison_memory_region((addr), (size))
#define ASAN_UNPOISON_MEMORY_REGION(addr, size) \
__asan_unpoison_memory_region((addr), (size))
#else
#define ASAN_POISON_MEMORY_REGION(addr, size) \
((void)(addr), (void)(size))
#define ASAN_UNPOISON_MEMORY_REGION(addr, size) \
((void)(addr), (void)(size))
#endif
#ifdef __cplusplus
}
#endif
#endif /* unittest.h */
| 23,907 | 29.769627 | 79 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_fh.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* ut_fh.c -- implementation of OS-independent file handle / file descriptor
* interface
*/
/* for O_TMPFILE */
#define _GNU_SOURCE
#include <fcntl.h>
#include "ut_fh.h"
#include "unittest.h"
struct FHandle {
int fd;
#ifdef _WIN32
HANDLE h;
#endif
enum file_handle_type type;
};
#ifdef _WIN32
#define HIDWORD(x) ((DWORD)((x) >> 32))
#define LODWORD(x) ((DWORD)((x) & 0xFFFFFFFF))
#endif
static void
check_invalid_flags(const char *file, int line, const char *func, int flags)
{
if ((flags & FH_EXCL) && !(flags & FH_CREAT)) {
ut_fatal(file, line, func,
"FH_EXCL without FH_CREAT is meaningless");
}
if ((flags & FH_TRUNC) && (flags & FH_CREAT)) {
/* because Windows doesn't support both */
ut_fatal(file, line, func,
"FH_TRUNC with FH_CREAT is forbidden");
}
}
static int
ut_fh_open_fd(const char *file, int line, const char *func,
const char *path, int flags, mode_t mode)
{
int sflags = 0;
check_invalid_flags(file, line, func, flags);
if ((flags & (FH_CREAT | FH_EXCL)) == (FH_CREAT | FH_EXCL)) {
flags &= ~(FH_CREAT | FH_EXCL);
sflags |= O_CREAT | O_EXCL;
} else if (flags & FH_CREAT) {
flags &= ~FH_CREAT;
sflags |= O_CREAT;
/* Windows version doesn't support both O_TRUNC and O_CREAT */
} else if (flags & FH_TRUNC) {
flags &= ~FH_TRUNC;
sflags |= O_TRUNC;
}
int acc = flags & FH_ACCMODE;
/* Linux version does not have FH_EXEC equivalent */
if ((acc & FH_WRITE) && (acc & FH_READ))
sflags |= O_RDWR;
else if (acc & FH_WRITE)
sflags |= O_WRONLY;
else if (acc & FH_READ)
sflags |= O_RDONLY;
else
ut_fatal(file, line, func, "unknown access mode %d", acc);
flags &= ~FH_ACCMODE;
if (flags & FH_DIRECTORY) {
#ifdef _WIN32
ut_fatal(file, line, func,
"FH_DIRECTORY is not supported on Windows using FD interface");
#else
flags &= ~FH_DIRECTORY;
sflags |= O_DIRECTORY;
#endif
}
if (flags & FH_TMPFILE) {
#ifdef O_TMPFILE
flags &= ~FH_TMPFILE;
sflags |= O_TMPFILE;
#else
ut_fatal(file, line, func,
"FH_TMPFILE is not supported on this system for file descriptors");
#endif
}
if (flags)
ut_fatal(file, line, func, "unsupported flag(s) 0%o", flags);
return ut_open(file, line, func, path, sflags, mode);
}
#ifdef _WIN32
static HANDLE
ut_fh_open_handle(const char *file, int line, const char *func,
const char *path, int flags, mode_t mode)
{
DWORD dwDesiredAccess;
/* do not allow delete, read or write from another process */
DWORD dwShareMode = 0;
LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
HANDLE hTemplateFile = NULL;
/* XXX sometimes doesn't work, ERROR_ACCESS_DENIED on AppVeyor */
#if 0
/*
* FILE_FLAG_DELETE_ON_CLOSE needs a real file (FH_CREAT)
* If it already exists refuse to use it (FH_EXCL), because this means
* something weird is going on (either there's another process with
* the same file opened or FILE_FLAG_DELETE_ON_CLOSE didn't actually
* delete the file on close)
*/
if (flags & FH_TMPFILE)
flags |= FH_CREAT | FH_EXCL;
#else
if (flags & FH_TMPFILE)
ut_fatal(file, line, func,
"FH_TMPFILE is not supported for file handles");
#endif
check_invalid_flags(file, line, func, flags);
/* only write permission can be taken out on Windows */
if (!(mode & _S_IWRITE))
dwFlagsAndAttributes |= FILE_ATTRIBUTE_READONLY;
if ((flags & (FH_CREAT | FH_EXCL)) == (FH_CREAT | FH_EXCL)) {
flags &= ~(FH_CREAT | FH_EXCL);
dwCreationDisposition = CREATE_NEW;
} else if (flags & FH_CREAT) {
flags &= ~FH_CREAT;
dwCreationDisposition = OPEN_ALWAYS;
} else if (flags & FH_TRUNC) {
flags &= ~FH_TRUNC;
dwCreationDisposition = TRUNCATE_EXISTING;
} else {
dwCreationDisposition = OPEN_EXISTING;
}
int acc = flags & FH_ACCMODE;
dwDesiredAccess = 0;
if (acc & FH_READ) {
dwDesiredAccess |= GENERIC_READ;
acc &= ~FH_READ;
}
if (acc & FH_WRITE) {
dwDesiredAccess |= GENERIC_WRITE;
acc &= ~FH_WRITE;
}
if (acc & FH_EXEC) {
dwDesiredAccess |= GENERIC_EXECUTE;
acc &= ~FH_EXEC;
}
if (acc)
ut_fatal(file, line, func, "unknown access mode %d", acc);
flags &= ~FH_ACCMODE;
if (flags & FH_DIRECTORY) {
flags &= ~FH_DIRECTORY;
/* GJ MS */
dwFlagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS;
}
char *full_path = NULL;
if (flags & FH_TMPFILE) {
flags &= ~FH_TMPFILE;
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE;
/*
* FILE_FLAG_DELETE_ON_CLOSE needs a real file,
* not a directory
*/
full_path = MALLOC(strlen(path) + 1 +
strlen("UT_FH_TMPFILE") + 1);
sprintf(full_path, "%s\\UT_FH_TMPFILE", path);
path = full_path;
}
if (flags)
ut_fatal(file, line, func, "unsupported flag(s) 0%o", flags);
wchar_t *wpath = util_toUTF16(path);
if (wpath == NULL)
ut_fatal(file, line, func, "conversion to utf16 failed");
HANDLE h = CreateFileW(wpath, dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
util_free_UTF16(wpath);
if (h == INVALID_HANDLE_VALUE) {
ut_fatal(file, line, func, "opening file %s failed: %d", path,
GetLastError());
}
if (full_path)
free(full_path);
return h;
}
#endif
struct FHandle *
ut_fh_open(const char *file, int line, const char *func,
enum file_handle_type type, const char *path, int flags, ...)
{
struct FHandle *f = MALLOC(sizeof(*f));
mode_t mode = 0;
va_list ap;
va_start(ap, flags);
if ((flags & FH_CREAT) || (flags & FH_TMPFILE))
mode = va_arg(ap, mode_t);
va_end(ap);
f->type = type;
if (type == FH_FD) {
f->fd = ut_fh_open_fd(file, line, func, path, flags, mode);
} else if (type == FH_HANDLE) {
#ifdef _WIN32
f->h = ut_fh_open_handle(file, line, func, path, flags,
mode);
#else
ut_fatal(file, line, func,
"FH_HANDLE not supported on !Windows");
#endif
} else {
ut_fatal(file, line, func, "unknown type value %d", type);
}
return f;
}
void
ut_fh_truncate(const char *file, int line, const char *func,
struct FHandle *f, os_off_t length)
{
if (f->type == FH_FD) {
ut_ftruncate(file, line, func, f->fd, length);
} else if (f->type == FH_HANDLE) {
#ifdef _WIN32
LONG low = LODWORD(length);
LONG high = HIDWORD(length);
if (SetFilePointer(f->h, low, &high, FILE_BEGIN) ==
INVALID_SET_FILE_POINTER &&
GetLastError() != ERROR_SUCCESS) {
ut_fatal(file, line, func, "SetFilePointer failed: %d",
GetLastError());
}
if (SetEndOfFile(f->h) == 0) {
ut_fatal(file, line, func, "SetEndOfFile failed: %d",
GetLastError());
}
#else
ut_fatal(file, line, func,
"FH_HANDLE not supported on !Windows");
#endif
} else {
ut_fatal(file, line, func, "unknown type value %d", f->type);
}
}
void
ut_fh_close(const char *file, int line, const char *func, struct FHandle *f)
{
if (f->type == FH_FD) {
CLOSE(f->fd);
} else if (f->type == FH_HANDLE) {
#ifdef _WIN32
CloseHandle(f->h);
#else
ut_fatal(file, line, func,
"FH_HANDLE not supported on !Windows");
#endif
} else {
ut_fatal(file, line, func, "unknown type value %d", f->type);
}
memset(f, 0, sizeof(*f));
FREE(f);
}
int
ut_fh_get_fd(const char *file, int line, const char *func, struct FHandle *f)
{
if (f->type == FH_FD)
return f->fd;
ut_fatal(file, line, func,
"requested file descriptor on FHandle that doesn't contain it");
}
#ifdef _WIN32
HANDLE
ut_fh_get_handle(const char *file, int line, const char *func,
struct FHandle *f)
{
if (f->type == FH_HANDLE)
return f->h;
ut_fatal(file, line, func,
"requested file handle on FHandle that doesn't contain it");
}
#endif
enum file_handle_type
ut_fh_get_handle_type(struct FHandle *fh)
{
return fh->type;
}
| 7,734 | 22.158683 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* ut_pmem2.h -- utility helper functions for libpmem tests
*/
#ifndef UT_PMEM2_H
#define UT_PMEM2_H 1
#include "ut_pmem2_config.h"
#include "ut_pmem2_map.h"
#include "ut_pmem2_source.h"
#include "ut_pmem2_utils.h"
#endif /* UT_PMEM2_H */
| 333 | 18.647059 | 59 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* ut.c -- unit test support routines
*
* some of these functions look at errno, but none of them
* change errno -- it is preserved across these calls.
*
* ut_done() and ut_fatal() never return.
*/
#include "unittest.h"
#ifndef _WIN32
#ifdef __FreeBSD__
#include <uuid/uuid.h>
int
ut_get_uuid_str(char *uu)
{
uuid_t uuid;
uuid_generate(uuid);
uuid_unparse(uuid, uu);
return 0;
}
#else
int
ut_get_uuid_str(char *uu)
{
int fd = OPEN(UT_POOL_HDR_UUID_GEN_FILE, O_RDONLY);
size_t num = READ(fd, uu, UT_POOL_HDR_UUID_STR_LEN);
UT_ASSERTeq(num, UT_POOL_HDR_UUID_STR_LEN);
uu[UT_POOL_HDR_UUID_STR_LEN - 1] = '\0';
CLOSE(fd);
return 0;
}
#endif
/* RHEL5 seems to be missing decls, even though libc supports them */
extern DIR *fdopendir(int fd);
extern ssize_t readlinkat(int, const char *restrict, char *__restrict, size_t);
void
ut_strerror(int errnum, char *buff, size_t bufflen)
{
strerror_r(errnum, buff, bufflen);
}
void ut_suppress_errmsg(void) {}
void ut_unsuppress_errmsg(void) {}
void ut_suppress_crt_assert(void) {}
void ut_unsuppress_crt_assert(void) {}
#else
#include <crtdbg.h>
#pragma comment(lib, "rpcrt4.lib")
static DWORD ErrMode;
static BOOL Err_suppressed = FALSE;
static UINT AbortBehave;
void
ut_suppress_errmsg(void)
{
ErrMode = GetErrorMode();
SetErrorMode(ErrMode | SEM_NOGPFAULTERRORBOX |
SEM_FAILCRITICALERRORS);
AbortBehave = _set_abort_behavior(0, _WRITE_ABORT_MSG |
_CALL_REPORTFAULT);
Err_suppressed = TRUE;
}
void
ut_unsuppress_errmsg(void)
{
if (Err_suppressed) {
SetErrorMode(ErrMode);
_set_abort_behavior(AbortBehave, _WRITE_ABORT_MSG |
_CALL_REPORTFAULT);
Err_suppressed = FALSE;
}
}
static _invalid_parameter_handler OldHandler;
static BOOL Crt_suppressed = FALSE;
static int Old_crt_assert_mode;
/*
* empty_parameter_handler -- empty, non aborting invalid parameter handler
*/
static void
empty_parameter_handler(const wchar_t *expression, const wchar_t *function,
const wchar_t *file, unsigned line, uintptr_t pReserved)
{
}
/*
* ut_suppress_crt_assert -- suppress crt raport message box
*/
void
ut_suppress_crt_assert(void)
{
OldHandler = _set_invalid_parameter_handler(empty_parameter_handler);
Old_crt_assert_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
Crt_suppressed = TRUE;
}
/*
* ut_suppress_crt_assert -- unsuppress crt raport message box
*/
void
ut_unsuppress_crt_assert(void)
{
if (Crt_suppressed) {
_set_invalid_parameter_handler(OldHandler);
_CrtSetReportMode(_CRT_ASSERT, Old_crt_assert_mode);
Crt_suppressed = FALSE;
}
}
int
ut_get_uuid_str(char *uuid_str)
{
UUID uuid;
char *buff;
if (UuidCreate(&uuid) == 0)
if (UuidToStringA(&uuid, &buff) == RPC_S_OK) {
strcpy_s(uuid_str, UT_POOL_HDR_UUID_STR_LEN, buff);
return 0;
}
return -1;
}
/* XXX - fix this temp hack dup'ing util_strerror when we get mock for win */
#define ENOTSUP_STR "Operation not supported"
#define UNMAPPED_STR "Unmapped error"
void
ut_strerror(int errnum, char *buff, size_t bufflen)
{
switch (errnum) {
case ENOTSUP:
strcpy_s(buff, bufflen, ENOTSUP_STR);
break;
default:
if (strerror_s(buff, bufflen, errnum))
strcpy_s(buff, bufflen, UNMAPPED_STR);
}
}
/*
* ut_spawnv -- creates and executes new synchronous process,
* ... are additional parameters to new process,
* the last argument must be a NULL
*
* XXX: argc/argv are ignored actually, as we need to use the unmodified
* UTF16-encoded command line args.
*/
intptr_t
ut_spawnv(int argc, const char **argv, ...)
{
int va_count = 0;
int wargc;
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &wargc);
va_list ap;
va_start(ap, argv);
while (va_arg(ap, char *)) {
va_count++;
}
va_end(ap);
/* 1 for terminating NULL */
wchar_t **wargv2 = calloc(wargc + va_count + 1, sizeof(wchar_t *));
if (wargv2 == NULL) {
UT_ERR("Cannot calloc memory for new array");
return -1;
}
memcpy(wargv2, wargv, wargc * sizeof(wchar_t *));
va_start(ap, argv);
for (int i = 0; i < va_count; i++) {
char *a = va_arg(ap, char *);
wargv2[wargc + i] = ut_toUTF16(a);
}
va_end(ap);
intptr_t ret = _wspawnv(_P_WAIT, wargv2[0], wargv2);
for (int i = 0; i < va_count; i++) {
free(wargv2[wargc + i]);
}
free(wargv2);
return ret;
}
#endif
#define MAXLOGFILENAME 100 /* maximum expected .log file name length */
#define MAXPRINT 8192 /* maximum expected single print length */
/*
* output gets replicated to these files
*/
static FILE *Outfp;
static FILE *Errfp;
static FILE *Tracefp;
static int LogLevel; /* set by UNITTEST_LOG_LEVEL env variable */
static int Force_quiet; /* set by UNITTEST_FORCE_QUIET env variable */
static char *Testname; /* set by UNITTEST_NAME env variable */
/* set by UNITTEST_CHECK_OPEN_FILES_IGNORE_BADBLOCKS env variable */
static int Ignore_bb;
unsigned long Ut_pagesize;
unsigned long long Ut_mmap_align;
os_mutex_t Sigactions_lock;
static char Buff_out[MAXPRINT];
static char Buff_err[MAXPRINT];
static char Buff_trace[MAXPRINT];
static char Buff_stdout[MAXPRINT];
/*
* flags that control output
*/
#define OF_NONL 1 /* do not append newline */
#define OF_ERR 2 /* output is error output */
#define OF_TRACE 4 /* output to trace file only */
#define OF_NAME 16 /* include Testname in the output */
/*
* vout -- common output code, all output happens here
*/
static void
vout(int flags, const char *prepend, const char *fmt, va_list ap)
{
char buf[MAXPRINT];
unsigned cc = 0;
int sn;
const char *sep = "";
char errstr[UT_MAX_ERR_MSG] = "";
const char *nl = "\n";
if (Force_quiet)
return;
if (flags & OF_NONL)
nl = "";
if (flags & OF_NAME && Testname) {
sn = util_snprintf(&buf[cc], MAXPRINT - cc, "%s: ", Testname);
if (sn < 0)
abort();
cc += (unsigned)sn;
}
if (prepend) {
const char *colon = "";
if (fmt)
colon = ": ";
sn = util_snprintf(&buf[cc], MAXPRINT - cc, "%s%s", prepend,
colon);
if (sn < 0)
abort();
cc += (unsigned)sn;
}
if (fmt) {
if (*fmt == '!') {
fmt++;
sep = ": ";
ut_strerror(errno, errstr, UT_MAX_ERR_MSG);
}
sn = vsnprintf(&buf[cc], MAXPRINT - cc, fmt, ap);
if (sn < 0)
abort();
cc += (unsigned)sn;
}
int ret = util_snprintf(&buf[cc], MAXPRINT - cc,
"%s%s%s", sep, errstr, nl);
if (ret < 0)
UT_FATAL("snprintf: %d", errno);
/* buf has the fully-baked output, send it everywhere it goes... */
fputs(buf, Tracefp);
if (flags & OF_ERR) {
fputs(buf, Errfp);
if (LogLevel >= 2)
fputs(buf, stderr);
} else if ((flags & OF_TRACE) == 0) {
fputs(buf, Outfp);
if (LogLevel >= 2)
fputs(buf, stdout);
}
}
/*
* out -- printf-like output controlled by flags
*/
static void
out(int flags, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vout(flags, NULL, fmt, ap);
va_end(ap);
}
/*
* prefix -- emit the trace line prefix
*/
static void
prefix(const char *file, int line, const char *func, int flags)
{
out(OF_NONL|OF_TRACE|flags, "{%s:%d %s} ", file, line, func);
}
/*
* lookup table for open files
*/
static struct fd_lut {
struct fd_lut *left;
struct fd_lut *right;
int fdnum;
char *fdfile;
} *Fd_lut;
static int Fd_errcount;
/*
* open_file_add -- add an open file to the lut
*/
static struct fd_lut *
open_file_add(struct fd_lut *root, int fdnum, const char *fdfile)
{
if (root == NULL) {
root = ZALLOC(sizeof(*root));
root->fdnum = fdnum;
root->fdfile = STRDUP(fdfile);
} else if (root->fdnum == fdnum)
UT_FATAL("duplicate fdnum: %d", fdnum);
else if (root->fdnum < fdnum)
root->left = open_file_add(root->left, fdnum, fdfile);
else
root->right = open_file_add(root->right, fdnum, fdfile);
return root;
}
/*
* open_file_remove -- find exact match & remove it from lut
*
* prints error if exact match not found, increments Fd_errcount
*/
static void
open_file_remove(struct fd_lut *root, int fdnum, const char *fdfile)
{
if (root == NULL) {
if (!Ignore_bb || strstr(fdfile, "badblocks") == NULL) {
UT_ERR("unexpected open file: fd %d => \"%s\"",
fdnum, fdfile);
Fd_errcount++;
}
} else if (root->fdnum == fdnum) {
if (root->fdfile == NULL) {
UT_ERR("open file dup: fd %d => \"%s\"", fdnum, fdfile);
Fd_errcount++;
} else if (strcmp(root->fdfile, fdfile) == 0) {
/* found exact match */
FREE(root->fdfile);
root->fdfile = NULL;
} else {
UT_ERR("open file changed: fd %d was \"%s\" now \"%s\"",
fdnum, root->fdfile, fdfile);
#ifdef __FreeBSD__
/*
* XXX Pathname list not definitive on FreeBSD,
* so treat as warning
*/
FREE(root->fdfile);
root->fdfile = NULL;
#else
Fd_errcount++;
#endif
}
} else if (root->fdnum < fdnum)
open_file_remove(root->left, fdnum, fdfile);
else
open_file_remove(root->right, fdnum, fdfile);
}
/*
* open_file_walk -- walk lut for any left-overs
*
* prints error if any found, increments Fd_errcount
*/
static void
open_file_walk(struct fd_lut *root)
{
if (root) {
open_file_walk(root->left);
if (root->fdfile) {
UT_ERR("open file missing: fd %d => \"%s\"",
root->fdnum, root->fdfile);
Fd_errcount++;
}
open_file_walk(root->right);
}
}
/*
* open_file_free -- free the lut
*/
static void
open_file_free(struct fd_lut *root)
{
if (root) {
open_file_free(root->left);
open_file_free(root->right);
if (root->fdfile)
FREE(root->fdfile);
FREE(root);
}
}
/*
* close_output_files -- close opened output files
*/
static void
close_output_files(void)
{
if (Outfp != NULL)
fclose(Outfp);
if (Errfp != NULL)
fclose(Errfp);
if (Tracefp != NULL)
fclose(Tracefp);
}
#ifndef _WIN32
#ifdef __FreeBSD__
/* XXX Note: Pathname retrieval is not really supported in FreeBSD */
#include <libutil.h>
#include <sys/user.h>
/*
* record_open_files -- make a list of open files (used at START() time)
*/
static void
record_open_files(void)
{
int numfds, i;
struct kinfo_file *fip, *f;
if ((fip = kinfo_getfile(getpid(), &numfds)) == NULL) {
UT_FATAL("!kinfo_getfile");
}
for (i = 0, f = fip; i < numfds; i++, f++) {
if (f->kf_fd >= 0) {
Fd_lut = open_file_add(Fd_lut, f->kf_fd, f->kf_path);
}
}
free(fip);
}
/*
* check_open_files -- verify open files match recorded open files
*/
static void
check_open_files(void)
{
int numfds, i;
struct kinfo_file *fip, *f;
if ((fip = kinfo_getfile(getpid(), &numfds)) == NULL) {
UT_FATAL("!kinfo_getfile");
}
for (i = 0, f = fip; i < numfds; i++, f++) {
if (f->kf_fd >= 0) {
open_file_remove(Fd_lut, f->kf_fd, f->kf_path);
}
}
open_file_walk(Fd_lut);
if (Fd_errcount)
UT_FATAL("open file list changed between START() and DONE()");
open_file_free(Fd_lut);
free(fip);
}
#else /* !__FreeBSD__ */
/*
* record_open_files -- make a list of open files (used at START() time)
*/
static void
record_open_files(void)
{
int dirfd;
DIR *dirp = NULL;
struct dirent *dp;
if ((dirfd = os_open("/proc/self/fd", O_RDONLY)) < 0 ||
(dirp = fdopendir(dirfd)) == NULL)
UT_FATAL("!/proc/self/fd");
while ((dp = readdir(dirp)) != NULL) {
int fdnum;
char fdfile[PATH_MAX];
ssize_t cc;
if (*dp->d_name == '.')
continue;
if ((cc = readlinkat(dirfd, dp->d_name, fdfile, PATH_MAX)) < 0)
UT_FATAL("!readlinkat: /proc/self/fd/%s", dp->d_name);
fdfile[cc] = '\0';
fdnum = atoi(dp->d_name);
if (dirfd == fdnum)
continue;
Fd_lut = open_file_add(Fd_lut, fdnum, fdfile);
}
closedir(dirp);
}
/*
* check_open_files -- verify open files match recorded open files
*/
static void
check_open_files(void)
{
int dirfd;
DIR *dirp = NULL;
struct dirent *dp;
if ((dirfd = os_open("/proc/self/fd", O_RDONLY)) < 0 ||
(dirp = fdopendir(dirfd)) == NULL)
UT_FATAL("!/proc/self/fd");
while ((dp = readdir(dirp)) != NULL) {
int fdnum;
char fdfile[PATH_MAX];
ssize_t cc;
if (*dp->d_name == '.')
continue;
if ((cc = readlinkat(dirfd, dp->d_name, fdfile, PATH_MAX)) < 0)
UT_FATAL("!readlinkat: /proc/self/fd/%s", dp->d_name);
fdfile[cc] = '\0';
fdnum = atoi(dp->d_name);
if (dirfd == fdnum)
continue;
open_file_remove(Fd_lut, fdnum, fdfile);
}
closedir(dirp);
open_file_walk(Fd_lut);
if (Fd_errcount)
UT_FATAL("open file list changed between START() and DONE()");
open_file_free(Fd_lut);
}
#endif /* __FreeBSD__ */
#else /* _WIN32 */
#include <winternl.h>
#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
#define ObjectTypeInformation 2
#define SystemExtendedHandleInformation 64
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX {
PVOID Object;
HANDLE UniqueProcessId;
HANDLE HandleValue;
ULONG GrantedAccess;
USHORT CreatorBackTraceIndex;
USHORT ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;
typedef struct _SYSTEM_HANDLE_INFORMATION_EX {
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX;
typedef enum _POOL_TYPE {
NonPagedPool,
PagedPool,
NonPagedPoolMustSucceed,
DontUseThisType,
NonPagedPoolCacheAligned,
PagedPoolCacheAligned,
NonPagedPoolCacheAlignedMustS
} POOL_TYPE, *PPOOL_TYPE;
typedef struct _OBJECT_TYPE_INFORMATION {
UNICODE_STRING Name;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG TotalPagedPoolUsage;
ULONG TotalNonPagedPoolUsage;
ULONG TotalNamePoolUsage;
ULONG TotalHandleTableUsage;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
ULONG HighWaterPagedPoolUsage;
ULONG HighWaterNonPagedPoolUsage;
ULONG HighWaterNamePoolUsage;
ULONG HighWaterHandleTableUsage;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccess;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
USHORT MaintainTypeList;
POOL_TYPE PoolType;
ULONG PagedPoolUsage;
ULONG NonPagedPoolUsage;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
/*
* enum_handles -- (internal) record or check a list of open handles
*/
static void
enum_handles(int op)
{
ULONG hi_size = 0x200000; /* default size */
ULONG req_size = 0;
PSYSTEM_HANDLE_INFORMATION_EX hndl_info =
(PSYSTEM_HANDLE_INFORMATION_EX)MALLOC(hi_size);
/* if it fails with the default info size, realloc and try again */
NTSTATUS status;
while ((status = NtQuerySystemInformation(
SystemExtendedHandleInformation,
hndl_info, hi_size, &req_size)
== STATUS_INFO_LENGTH_MISMATCH)) {
hi_size = req_size + 4096;
hndl_info = (PSYSTEM_HANDLE_INFORMATION_EX)REALLOC(hndl_info,
hi_size);
}
UT_ASSERT(status >= 0);
DWORD pid = GetProcessId(GetCurrentProcess());
DWORD ti_size = 4096; /* initial size */
POBJECT_TYPE_INFORMATION type_info =
(POBJECT_TYPE_INFORMATION)MALLOC(ti_size);
DWORD ni_size = 4096; /* initial size */
PVOID name_info = MALLOC(ni_size);
for (ULONG i = 0; i < hndl_info->NumberOfHandles; i++) {
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX handle
= hndl_info->Handles[i];
char name[MAX_PATH];
/* ignore handles not owned by current process */
if ((ULONGLONG)handle.UniqueProcessId != pid)
continue;
/* query the object type */
status = NtQueryObject(handle.HandleValue,
ObjectTypeInformation, type_info, ti_size, NULL);
if (status < 0)
continue; /* if handle can't be queried, ignore it */
/*
* Register/verify only handles of selected types.
* Do not rely on type numbers - check type name instead.
*/
if (wcscmp(type_info->Name.Buffer, L"Directory") &&
wcscmp(type_info->Name.Buffer, L"Mutant") &&
wcscmp(type_info->Name.Buffer, L"Semaphore") &&
wcscmp(type_info->Name.Buffer, L"File")) {
/* does not match any of the above types */
continue;
}
/*
* Skip handles with access 0x0012019f. NtQueryObject() may
* hang on querying the handles pointing to named pipes.
*/
if (handle.GrantedAccess == 0x0012019f)
continue;
int ret = snprintf(name, MAX_PATH, "%.*S",
type_info->Name.Length / 2, type_info->Name.Buffer);
if (ret < 0 || ret >= MAX_PATH)
UT_FATAL("snprintf: %d", ret);
int fd = (int)(ULONGLONG)handle.HandleValue;
if (op == 0)
Fd_lut = open_file_add(Fd_lut, fd, name);
else
open_file_remove(Fd_lut, fd, name);
}
FREE(type_info);
FREE(name_info);
FREE(hndl_info);
}
/*
* record_open_files -- record a number of open handles (used at START() time)
*
* On Windows, it records not only file handles, but some other handle types
* as well.
* XXX: We can't register all the handles, as spawning new process in the test
* may result in opening new handles of some types (i.e. registry keys).
*/
static void
record_open_files()
{
/*
* XXX: Dummy call to CoCreateGuid() to ignore files/handles open
* by this function. They won't be closed until process termination.
*/
GUID uuid;
HRESULT res = CoCreateGuid(&uuid);
enum_handles(0);
}
/*
* check_open_files -- verify open handles match recorded open handles
*/
static void
check_open_files()
{
enum_handles(1);
open_file_walk(Fd_lut);
if (Fd_errcount)
UT_FATAL("open file list changed between START() and DONE()");
open_file_free(Fd_lut);
}
#endif /* _WIN32 */
/*
* ut_start_common -- (internal) initialize unit test framework,
* indicate test started
*/
static void
ut_start_common(const char *file, int line, const char *func,
const char *fmt, va_list ap)
{
int saveerrno = errno;
char logname[MAXLOGFILENAME];
char *logsuffix;
long long sc = sysconf(_SC_PAGESIZE);
if (sc < 0)
abort();
Ut_pagesize = (unsigned long)sc;
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
Ut_mmap_align = si.dwAllocationGranularity;
if (os_getenv("PMDK_NO_ABORT_MSG") != NULL) {
/* disable windows error message boxes */
ut_suppress_errmsg();
}
os_mutex_init(&Sigactions_lock);
#else
Ut_mmap_align = Ut_pagesize;
char *ignore_bb =
os_getenv("UNITTEST_CHECK_OPEN_FILES_IGNORE_BADBLOCKS");
if (ignore_bb && *ignore_bb)
Ignore_bb = 1;
#endif
if (os_getenv("UNITTEST_NO_SIGHANDLERS") == NULL)
ut_register_sighandlers();
if (os_getenv("UNITTEST_LOG_LEVEL") != NULL)
LogLevel = atoi(os_getenv("UNITTEST_LOG_LEVEL"));
else
LogLevel = 2;
if (os_getenv("UNITTEST_FORCE_QUIET") != NULL)
Force_quiet++;
Testname = os_getenv("UNITTEST_NAME");
if ((logsuffix = os_getenv("UNITTEST_NUM")) == NULL)
logsuffix = "";
const char *fmode = "w";
if (os_getenv("UNITTEST_LOG_APPEND") != NULL)
fmode = "a";
int ret = util_snprintf(logname, MAXLOGFILENAME, "out%s.log",
logsuffix);
if (ret < 0)
UT_FATAL("snprintf: %d", errno);
if ((Outfp = os_fopen(logname, fmode)) == NULL) {
perror(logname);
exit(1);
}
ret = util_snprintf(logname, MAXLOGFILENAME, "err%s.log", logsuffix);
if (ret < 0)
UT_FATAL("snprintf: %d", errno);
if ((Errfp = os_fopen(logname, fmode)) == NULL) {
perror(logname);
exit(1);
}
ret = util_snprintf(logname, MAXLOGFILENAME, "trace%s.log", logsuffix);
if (ret < 0)
UT_FATAL("snprintf: %d", errno);
if ((Tracefp = os_fopen(logname, fmode)) == NULL) {
perror(logname);
exit(1);
}
setvbuf(Outfp, Buff_out, _IOLBF, MAXPRINT);
setvbuf(Errfp, Buff_err, _IOLBF, MAXPRINT);
setvbuf(Tracefp, Buff_trace, _IOLBF, MAXPRINT);
setvbuf(stdout, Buff_stdout, _IOLBF, MAXPRINT);
prefix(file, line, func, 0);
vout(OF_NAME, "START", fmt, ap);
#ifdef _WIN32
/*
* XXX To generate error string Windows will silently load
* KernelBase.dll.mui. To prevent counting it as an opened file, it is
* loaded here by force.
*/
char buff[1000];
util_strwinerror(1, buff, 1000);
#elif __FreeBSD__
/* XXX Record the fd that will be leaked by uuid_generate */
uuid_t u;
uuid_generate(u);
#endif
record_open_files();
errno = saveerrno;
}
/*
* ut_start -- initialize unit test framework, indicate test started
*/
void
ut_start(const char *file, int line, const char *func,
int argc, char * const argv[], const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
ut_start_common(file, line, func, fmt, ap);
out(OF_NONL, 0, " args:");
for (int i = 0; i < argc; i++)
out(OF_NONL, " %s", argv[i]);
out(0, NULL);
va_end(ap);
}
#ifdef _WIN32
/*
* ut_startW -- initialize unit test framework, indicate test started
*/
void
ut_startW(const char *file, int line, const char *func,
int argc, wchar_t * const argv[], const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
ut_start_common(file, line, func, fmt, ap);
out(OF_NONL, 0, " args:");
for (int i = 0; i < argc; i++) {
char *str = ut_toUTF8(argv[i]);
UT_ASSERTne(str, NULL);
out(OF_NONL, " %s", str);
free(str);
}
out(0, NULL);
va_end(ap);
}
#endif
/*
* ut_end -- indicate test is done, exit program with specified value
*/
void
ut_end(const char *file, int line, const char *func, int ret)
{
#ifdef _WIN32
os_mutex_destroy(&Sigactions_lock);
#endif
if (!os_getenv("UNITTEST_DO_NOT_CHECK_OPEN_FILES"))
check_open_files();
prefix(file, line, func, 0);
out(OF_NAME, "END %d", ret);
close_output_files();
exit(ret);
}
/*
* ut_done -- indicate test is done, exit program
*/
void
ut_done(const char *file, int line, const char *func,
const char *fmt, ...)
{
#ifdef _WIN32
os_mutex_destroy(&Sigactions_lock);
#endif
if (!os_getenv("UNITTEST_DO_NOT_CHECK_OPEN_FILES"))
check_open_files();
va_list ap;
va_start(ap, fmt);
prefix(file, line, func, 0);
vout(OF_NAME, "DONE", fmt, ap);
va_end(ap);
close_output_files();
exit(0);
}
/*
* ut_fatal -- indicate fatal error, exit program
*/
void
ut_fatal(const char *file, int line, const char *func,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
prefix(file, line, func, OF_ERR);
vout(OF_ERR|OF_NAME, "Error", fmt, ap);
va_end(ap);
abort();
}
/*
* ut_out -- output to stdout
*/
void
ut_out(const char *file, int line, const char *func,
const char *fmt, ...)
{
va_list ap;
int saveerrno = errno;
va_start(ap, fmt);
prefix(file, line, func, 0);
vout(0, NULL, fmt, ap);
va_end(ap);
errno = saveerrno;
}
/*
* ut_err -- output to stderr
*/
void
ut_err(const char *file, int line, const char *func,
const char *fmt, ...)
{
va_list ap;
int saveerrno = errno;
va_start(ap, fmt);
prefix(file, line, func, OF_ERR);
vout(OF_ERR|OF_NAME, NULL, fmt, ap);
va_end(ap);
errno = saveerrno;
}
/*
* ut_checksum -- compute checksum using Fletcher16 algorithm
*/
uint16_t
ut_checksum(uint8_t *addr, size_t len)
{
uint16_t sum1 = 0;
uint16_t sum2 = 0;
for (size_t i = 0; i < len; ++i) {
sum1 = (uint16_t)(sum1 + addr[i]) % 255;
sum2 = (uint16_t)(sum2 + sum1) % 255;
}
return (uint16_t)((sum2 << 8) | sum1);
}
#ifdef _WIN32
/*
* ut_toUTF8 -- convert WCS to UTF-8 string
*/
char *
ut_toUTF8(const wchar_t *wstr)
{
int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1,
NULL, 0, NULL, NULL);
if (size == 0) {
UT_FATAL("!ut_toUTF8");
}
char *str = malloc(size * sizeof(char));
if (str == NULL) {
UT_FATAL("!ut_toUTF8");
}
if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1, str,
size, NULL, NULL) == 0) {
UT_FATAL("!ut_toUTF8");
}
return str;
}
/*
* ut_toUTF16 -- convert UTF-8 to WCS string
*/
wchar_t *
ut_toUTF16(const char *wstr)
{
int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, wstr, -1,
NULL, 0);
if (size == 0) {
UT_FATAL("!ut_toUTF16");
}
wchar_t *str = malloc(size * sizeof(wchar_t));
if (str == NULL) {
UT_FATAL("!ut_toUTF16");
}
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, wstr, -1, str,
size) == 0) {
UT_FATAL("!ut_toUTF16");
}
return str;
}
#endif
/*
* ut_strtoi -- a strtoi call that cannot return error
*/
int
ut_strtoi(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
long ret = ut_strtol(file, line, func, nptr, endptr, base);
if (ret > INT_MAX || ret < INT_MIN)
ut_fatal(file, line, func,
"!strtoi: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
return (int)ret;
}
/*
* ut_strtou -- a strtou call that cannot return error
*/
unsigned
ut_strtou(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
unsigned long ret = ut_strtoul(file, line, func, nptr, endptr, base);
if (ret > UINT_MAX)
ut_fatal(file, line, func,
"!strtou: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
return (unsigned)ret;
}
/*
* ut_strtol -- a strtol call that cannot return error
*/
long
ut_strtol(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
long long ret = ut_strtoll(file, line, func, nptr, endptr, base);
if (ret > LONG_MAX || ret < LONG_MIN)
ut_fatal(file, line, func,
"!strtol: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
return (long)ret;
}
/*
* ut_strtoul -- a strtou call that cannot return error
*/
unsigned long
ut_strtoul(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
unsigned long long ret =
ut_strtoull(file, line, func, nptr, endptr, base);
if (ret > ULONG_MAX)
ut_fatal(file, line, func,
"!strtoul: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
return (unsigned long)ret;
}
/*
* ut_strtoull -- a strtoul call that cannot return error
*/
unsigned long long
ut_strtoull(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
unsigned long long retval;
errno = 0;
if (*nptr == '\0') {
errno = EINVAL;
goto fatal;
}
if (endptr != NULL) {
retval = strtoull(nptr, endptr, base);
} else {
char *end;
retval = strtoull(nptr, &end, base);
if (*end != '\0')
goto fatal;
}
if (errno != 0)
goto fatal;
return retval;
fatal:
ut_fatal(file, line, func,
"!strtoull: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
}
/*
* ut_strtoll -- a strtol call that cannot return error
*/
long long
ut_strtoll(const char *file, int line, const char *func,
const char *nptr, char **endptr, int base)
{
long long retval;
errno = 0;
if (*nptr == '\0') {
errno = EINVAL;
goto fatal;
}
if (endptr != NULL) {
retval = strtoll(nptr, endptr, base);
} else {
char *end;
retval = strtoll(nptr, &end, base);
if (*end != '\0')
goto fatal;
}
if (errno != 0)
goto fatal;
return retval;
fatal:
ut_fatal(file, line, func,
"!strtoll: nptr=%s, endptr=%s, base=%d",
nptr, endptr ? *endptr : "NULL", base);
}
int
ut_snprintf(const char *file, int line, const char *func,
char *str, size_t size, const char *format, ...)
{
va_list ap;
va_start(ap, format);
int ret = vsnprintf(str, size, format, ap);
va_end(ap);
if (ret < 0) {
if (!errno)
errno = EIO;
ut_fatal(file, line, func, "!snprintf");
} else if ((size_t)ret >= size) {
errno = ENOBUFS;
ut_fatal(file, line, func, "!snprintf");
}
return ret;
}
| 26,777 | 20.877451 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_config.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* ut_pmem2_config.h -- utility helper functions for libpmem2 config tests
*/
#ifndef UT_PMEM2_CONFIG_H
#define UT_PMEM2_CONFIG_H 1
#include "ut_fh.h"
/* a pmem2_config_new() that can't return NULL */
#define PMEM2_CONFIG_NEW(cfg) \
ut_pmem2_config_new(__FILE__, __LINE__, __func__, cfg)
/* a pmem2_config_set_required_store_granularity() doesn't return an error */
#define PMEM2_CONFIG_SET_GRANULARITY(cfg, g) \
ut_pmem2_config_set_required_store_granularity \
(__FILE__, __LINE__, __func__, cfg, g)
/* a pmem2_config_delete() that can't return NULL */
#define PMEM2_CONFIG_DELETE(cfg) \
ut_pmem2_config_delete(__FILE__, __LINE__, __func__, cfg)
void ut_pmem2_config_new(const char *file, int line, const char *func,
struct pmem2_config **cfg);
void ut_pmem2_config_set_required_store_granularity(const char *file,
int line, const char *func, struct pmem2_config *cfg,
enum pmem2_granularity g);
void ut_pmem2_config_delete(const char *file, int line, const char *func,
struct pmem2_config **cfg);
#endif /* UT_PMEM2_CONFIG_H */
| 1,152 | 30.162162 | 77 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_alloc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* ut_alloc.c -- unit test memory allocation routines
*/
#include "unittest.h"
/*
* ut_malloc -- a malloc that cannot return NULL
*/
void *
ut_malloc(const char *file, int line, const char *func, size_t size)
{
void *retval = malloc(size);
if (retval == NULL)
ut_fatal(file, line, func, "cannot malloc %zu bytes", size);
return retval;
}
/*
* ut_calloc -- a calloc that cannot return NULL
*/
void *
ut_calloc(const char *file, int line, const char *func,
size_t nmemb, size_t size)
{
void *retval = calloc(nmemb, size);
if (retval == NULL)
ut_fatal(file, line, func, "cannot calloc %zu bytes", size);
return retval;
}
/*
* ut_free -- wrapper for free
*
* technically we don't need to wrap free since there's no return to
* check. using this wrapper to add memory allocation tracking later.
*/
void
ut_free(const char *file, int line, const char *func, void *ptr)
{
free(ptr);
}
/*
* ut_aligned_free -- wrapper for aligned memory free
*/
void
ut_aligned_free(const char *file, int line, const char *func, void *ptr)
{
#ifndef _WIN32
free(ptr);
#else
_aligned_free(ptr);
#endif
}
/*
* ut_realloc -- a realloc that cannot return NULL
*/
void *
ut_realloc(const char *file, int line, const char *func,
void *ptr, size_t size)
{
void *retval = realloc(ptr, size);
if (retval == NULL)
ut_fatal(file, line, func, "cannot realloc %zu bytes", size);
return retval;
}
/*
* ut_strdup -- a strdup that cannot return NULL
*/
char *
ut_strdup(const char *file, int line, const char *func,
const char *str)
{
char *retval = strdup(str);
if (retval == NULL)
ut_fatal(file, line, func, "cannot strdup %zu bytes",
strlen(str));
return retval;
}
/*
* ut_memalign -- like malloc but page-aligned memory
*/
void *
ut_memalign(const char *file, int line, const char *func, size_t alignment,
size_t size)
{
void *retval;
#ifndef _WIN32
if ((errno = posix_memalign(&retval, alignment, size)) != 0)
ut_fatal(file, line, func,
"!memalign %zu bytes (%zu alignment)", size, alignment);
#else
retval = _aligned_malloc(size, alignment);
if (!retval) {
ut_fatal(file, line, func,
"!memalign %zu bytes (%zu alignment)", size, alignment);
}
#endif
return retval;
}
/*
* ut_pagealignmalloc -- like malloc but page-aligned memory
*/
void *
ut_pagealignmalloc(const char *file, int line, const char *func,
size_t size)
{
return ut_memalign(file, line, func, (size_t)Ut_pagesize, size);
}
/*
* ut_mmap_anon_aligned -- mmaps anonymous memory with specified (power of two,
* multiple of page size) alignment and adds guard
* pages around it
*/
void *
ut_mmap_anon_aligned(const char *file, int line, const char *func,
size_t alignment, size_t size)
{
char *d, *d_aligned;
uintptr_t di, di_aligned;
size_t sz;
if (alignment == 0)
alignment = Ut_mmap_align;
/* alignment must be a multiple of page size */
if (alignment & (Ut_mmap_align - 1))
return NULL;
/* power of two */
if (alignment & (alignment - 1))
return NULL;
d = ut_mmap(file, line, func, NULL, size + 2 * alignment,
PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
di = (uintptr_t)d;
di_aligned = (di + alignment - 1) & ~(alignment - 1);
if (di == di_aligned)
di_aligned += alignment;
d_aligned = (void *)di_aligned;
sz = di_aligned - di;
if (sz - Ut_mmap_align)
ut_munmap(file, line, func, d, sz - Ut_mmap_align);
/* guard page before */
ut_mprotect(file, line, func,
d_aligned - Ut_mmap_align, Ut_mmap_align, PROT_NONE);
/* guard page after */
ut_mprotect(file, line, func,
d_aligned + size, Ut_mmap_align, PROT_NONE);
sz = di + size + 2 * alignment - (di_aligned + size) - Ut_mmap_align;
if (sz)
ut_munmap(file, line, func,
d_aligned + size + Ut_mmap_align, sz);
return d_aligned;
}
/*
* ut_munmap_anon_aligned -- unmaps anonymous memory allocated by
* ut_mmap_anon_aligned
*/
int
ut_munmap_anon_aligned(const char *file, int line, const char *func,
void *start, size_t size)
{
return ut_munmap(file, line, func, (char *)start - Ut_mmap_align,
size + 2 * Ut_mmap_align);
}
| 4,238 | 20.963731 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/context.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
#
"""Set of classes that represent the context of single test execution"""
import os
import shlex
import sys
import itertools
import shutil
import subprocess as sp
import collections
import contextlib
from inspect import ismethod
import configurator
import futils
from poolset import _Poolset
from tools import Tools
from utils import KiB, MiB, HEADER_SIZE
try:
import testconfig
except ImportError:
sys.exit('Please add valid testconfig.py file - see testconfig.py.example')
config = testconfig.config
try:
import envconfig
envconfig = envconfig.config
except ImportError:
# if file doesn't exist create dummy object
envconfig = {'GLOBAL_LIB_PATH': '', 'PMEM2_AVX512F_ENABLED': ''}
def expand(*classes):
"""Return flatten list of container classes with removed duplications"""
return list(set(itertools.chain(*classes)))
class ContextBase:
"""Context basic interface and low-level utilities"""
def __init__(self, build, *args, **kwargs):
self._elems = []
self._env = {}
self.cmd_prefix = ''
self.build = build
# for positional arguments, each arg is added to the anonymous
# context elements list
for arg in args:
self.add_ctx_elem(arg)
# for keyword arguments, each kwarg value is additionally set as a
# context attribute with its key assigned as an attribute name.
for k, v in kwargs.items():
self.add_ctx_elem(v)
setattr(self, str(k), v)
def __getattr__(self, name):
"""
If context class itself does not have an acquired attribute
check if one of its elements has it and return it.
"""
elems_with_attr = [e for e in self._elems if hasattr(e, name)]
# no context elements with requested attribute found
if not elems_with_attr:
raise AttributeError('Neither context nor any of its elements '
'have the attribute "{}"'.format(name))
# all found elements have the same attribute value
elif all(e == e for e in elems_with_attr):
return getattr(elems_with_attr[0], name)
# more than one element found and they have different attribute values
else:
raise AttributeError('Ambiguity while acquiring attribute "{}": '
'implemented by multiple context elements '
'with different values'
.format(name))
def __str__(self):
"""
The Context string representation is a concatenation
(separated by '/') of all its elements string representations.
"""
s = '{}/'.format(str(self.build))
for e in self._elems:
if e:
s = s + str(e) + '/'
s = s[:-1]
return s
def add_ctx_elem(self, elem):
"""
Add element to the context. Update context environment variables
with element's environment variables (if present)
"""
self._elems.append(elem)
if hasattr(elem, 'name'):
setattr(self, elem.name, elem)
else:
setattr(self, str(elem), elem)
if hasattr(elem, 'env'):
self.add_env(elem.env)
if hasattr(elem, 'cmd'):
if self.cmd_prefix:
raise ValueError('More than one context element '
'defines command line prefix')
else:
self.cmd_prefix = elem.cmd
def add_env(self, env):
"""Add environment variables to those stored by context"""
futils.add_env_common(self._env, env)
def setup(self, *args, **kwargs):
"""
run setup() method for each context element.
Ignore error if not implemented
"""
kwargs['tools'] = self.tools
for e in self._elems:
with contextlib.suppress(AttributeError):
e.setup(*args, **kwargs)
def check(self, *args, **kwargs):
"""
run check() method for each context element.
Ignore error if not implemented
"""
kwargs['tools'] = self.tools
for e in self._elems:
with contextlib.suppress(AttributeError):
e.check(*args, **kwargs)
def clean(self, *args, **kwargs):
"""
run clean() method for each context element.
Ignore error if not implemented
"""
kwargs['tools'] = self.tools
for e in self._elems:
with contextlib.suppress(AttributeError):
e.clean(*args, **kwargs)
@property
def env(self):
return self._env
@property
def tools(self):
return Tools(self.env, self.build)
def dump_n_lines(self, file, n=-1):
"""
Prints last n lines of given log file. Number of lines printed can be
modified locally by "n" argument or globally by "dump_lines" in
testconfig.py file. If none of them are provided, default value is 30.
"""
if n < 0:
n = config.get('dump_lines', 30)
file_size = self.get_size(file.name)
# if file is small enough, read it whole and find last n lines
if file_size < 100 * MiB:
lines = list(file)
length = len(lines)
if n > length:
n = length
lines = lines[-n:]
lines.insert(0, 'Last {} lines of {} below '
'(whole file has {} lines):{}'
.format(n, file.name, length, os.linesep))
for line in lines:
print(line, end='')
else:
# if file is really big, read the last 10KiB and forget about lines
with open(file.name, 'br') as byte_file:
byte_file.seek(file_size - 10 * KiB)
print(byte_file.read().decode('iso_8859_1'))
def is_devdax(self, path):
"""Checks if given path points to device dax"""
proc = self.tools.pmemdetect('-d', path)
if proc.returncode == self.tools.PMEMDETECT_ERROR:
futils.fail(proc.stdout)
if proc.returncode == self.tools.PMEMDETECT_TRUE:
return True
if proc.returncode == self.tools.PMEMDETECT_FALSE:
return False
futils.fail('Unknown value {} returned by pmemdetect'
.format(proc.returncode))
def supports_map_sync(self, path):
"""Checks if MAP_SYNC is supported on a filesystem from given path"""
proc = self.tools.pmemdetect('-s', path)
if proc.returncode == self.tools.PMEMDETECT_ERROR:
futils.fail(proc.stdout)
if proc.returncode == self.tools.PMEMDETECT_TRUE:
return True
if proc.returncode == self.tools.PMEMDETECT_FALSE:
return False
futils.fail('Unknown value {} returned by pmemdetect'
.format(proc.returncode))
def get_size(self, path):
"""
Returns size of the file or dax device.
Value "2**64 - 1" is checked because pmemdetect
prints it in case of error.
"""
proc = self.tools.pmemdetect('-z', path)
if int(proc.stdout) != 2**64 - 1:
return int(proc.stdout)
futils.fail('Could not get size of the file, '
'it is inaccessible or does not exist')
def get_free_space(self, dir="."):
"""Returns free space for current file system"""
_, _, free = shutil.disk_usage(dir)
return free
class Context(ContextBase):
"""Manage test execution based on values from context classes"""
def __init__(self, *args, **kwargs):
self.conf = configurator.Configurator().config
self.msg = futils.Message(self.conf.unittest_log_level)
ContextBase.__init__(self, *args, **kwargs)
def new_poolset(self, path):
return _Poolset(path, self)
def exec(self, cmd, *args, expected_exitcode=0, stderr_file=None,
stdout_file=None):
"""Execute binary in current test context"""
tmp = self._env.copy()
futils.add_env_common(tmp, os.environ.copy())
# change cmd into list for supbrocess type compliance
cmd = [cmd, ]
if sys.platform == 'win32':
cmd[0] = os.path.join(self.build.exedir, cmd[0]) + '.exe'
else:
cmd[0] = os.path.join(self.cwd, cmd[0]) + \
self.build.exesuffix
if self.valgrind:
cmd = self.valgrind.cmd + cmd
# cast all provided args to strings (required by subprocess run())
# so that exec() can accept args of any printable type
cmd.extend([str(a) for a in args])
if self.conf.tracer:
cmd = shlex.split(self.conf.tracer) + cmd
# process stdout and stderr are not redirected - this lets running
# tracer command in an interactive session
proc = sp.run(cmd, env=tmp, cwd=self.cwd)
else:
if stderr_file:
f = open(os.path.join(self.cwd, stderr_file), 'w')
# let's create a dictionary of arguments to the run func
run_kwargs = {
'env': tmp,
'cwd': self.cwd,
'timeout': self.conf.timeout,
'stdout': sp.PIPE,
'universal_newlines': True,
'stderr': sp.STDOUT if stderr_file is None else f}
proc = sp.run(cmd, **run_kwargs)
if stderr_file:
f.close()
if expected_exitcode is not None and \
proc.returncode != expected_exitcode:
futils.fail(proc.stdout, exit_code=proc.returncode)
if stdout_file is not None:
with open(os.path.join(self.cwd, stdout_file), 'w') as f:
f.write(proc.stdout)
self.msg.print_verbose(proc.stdout)
def create_holey_file(self, size, path, mode=None):
"""Create a new file with the selected size and name"""
filepath = os.path.join(self.testdir, path)
with open(filepath, 'w') as f:
if size > 0:
f.seek(size - 1)
f.write('\0')
if mode is not None:
os.chmod(filepath, mode)
return filepath
def create_non_zero_file(self, size, path, mode=None):
"""Create a new non-zeroed file with the selected size and name"""
filepath = os.path.join(self.testdir, path)
with open(filepath, 'w') as f:
f.write('\132' * size)
if mode is not None:
os.chmod(filepath, mode)
return filepath
def create_zeroed_hdr_file(self, size, path, mode=None):
"""
Create a new non-zeroed file with a zeroed header and the selected
size and name
"""
filepath = os.path.join(self.testdir, path)
with open(filepath, 'w') as f:
f.write('\0' * HEADER_SIZE)
f.write('\132' * (size - HEADER_SIZE))
if mode is not None:
os.chmod(filepath, mode)
return filepath
def require_free_space(self, space):
if self.get_free_space(self.testdir) < space:
futils.skip('Not enough free space ({} MiB required)'
.format(space / MiB))
def mkdirs(self, path, mode=None):
"""
Creates directory along with all parent directories required. In the
case given path already exists do nothing.
"""
dirpath = os.path.join(self.testdir, path)
if mode is None:
os.makedirs(dirpath, exist_ok=True)
else:
os.makedirs(dirpath, mode, exist_ok=True)
class CtxType(type):
"""Metaclass for context classes that can stand for multiple classes"""
def __init__(cls, name, bases, dct):
type.__init__(cls, name, bases, dct)
# it is supposed that context class has a user defined base class
if cls.__base__.__name__ == 'object':
return
# context class preferred to be used when 'Any' test option is provided
if not hasattr(cls, 'preferred'):
cls.is_preferred = False
# if explicit, run only if the test case explicitly specifies this
# context in its own configuration
if not hasattr(cls, 'explicit'):
cls.explicit = False
if hasattr(cls, 'includes'):
cls.includes = expand(*cls.includes)
else:
# class that does not include other classes, includes itself
cls.includes = [cls]
# set instance (not class) method
setattr(cls, '__repr__', lambda cls: cls.__class__.__name__.lower())
def __repr__(cls):
return cls.__name__.lower()
def __str__(cls):
return cls.__name__.lower()
def __iter__(cls):
for c in cls.includes:
yield c
def factory(cls, conf, *classes):
return [c(conf) for c in expand(*classes)]
def filter_contexts(config_ctx, test_ctx):
"""
Return contexts that should be used in execution based on
contexts provided by config and test case
"""
if not test_ctx:
return [c for c in config_ctx if not c.explicit]
return [c for c in config_ctx if c in test_ctx]
def str_to_ctx_common(val, ctx_base_type):
def class_from_string(name, base):
if name == 'all':
return base.__subclasses__()
try:
return next(b for b in base.__subclasses__()
if str(b) == name.lower())
except StopIteration:
print('Invalid context value: "{}".'.format(name))
raise
if isinstance(val, list):
classes = [class_from_string(cl, ctx_base_type) for cl in val]
return expand(*classes)
else:
return expand(class_from_string(val, ctx_base_type))
def _req_prefix(attr):
"""
Add prefix to requirement attribute name. Used to mitigate the risk
of name clashes.
"""
return '_require{}'.format(attr)
def add_requirement(tc, attr, value, **kwargs):
"""Add requirement to the test"""
setattr(tc, _req_prefix(attr), value)
setattr(tc, _req_prefix('{}_kwargs'.format(attr)), kwargs)
def get_requirement(tc, attr, default):
"""
Get test requirement set to attribute 'attr', return default
if not found
"""
ret_val = default
ret_kwargs = {}
try:
ret_val = getattr(tc, _req_prefix(attr))
ret_kwargs = getattr(tc, _req_prefix('{}_kwargs'.format(attr)))
except AttributeError:
pass
return ret_val, ret_kwargs
class TestParam:
"""
TestParam manages single test parameter provided to test with add_params()
decorator.
Test parameters are added to context class as its elements - therefore the
'value' object may implement setup(), check() and clean() which will be
delegated to by TestParam class if context setup(), check() and
clean() methods are called.
"""
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return '{}: {}'.format(self.name, self.value)
def __call__(self):
return self.value
def setup(self, **kwargs):
if hasattr(self.value, 'setup') and ismethod(self.value.setup):
self.value.setup(**kwargs)
def check(self, **kwargs):
if hasattr(self.value, 'check') and ismethod(self.value.check):
self.value.check(**kwargs)
def clean(self, **kwargs):
if hasattr(self.value, 'clean') and ismethod(self.value.clean):
self.value.clean(**kwargs)
PARAMS_ATTR = '_params_'
def add_params(name, values):
"""
Add parameters to test case.
Parameters will be accessible from test through context 'name' attribute.
The value of single parameter can be accessed by calling this attribute,
e.g. for:
add_params('param', params_list)
single parameter provided within 'params_list' is accessible through:
ctx.param()
"""
params = [TestParam(name, v) for v in values]
def wrapped(tc):
if hasattr(tc, PARAMS_ATTR):
getattr(tc, PARAMS_ATTR).update({name: params})
else:
setattr(tc, PARAMS_ATTR, {name: params})
return tc
return wrapped
def get_params(tc):
"""Get parameters added to test case"""
try:
return getattr(tc, PARAMS_ATTR)
except AttributeError:
return {}
class Any:
"""
The test context attribute signifying that specific context value is not
relevant for the test outcome and it should be run only once in some
viable context
"""
@classmethod
def get(cls, conf_ctx):
"""Get specific context value to be run"""
for c in conf_ctx:
if c.is_preferred:
# pick preferred if found
return c
# if no preferred is found, pick the first non-explicit one
ret = [c for c in conf_ctx if not c.explicit]
if ret:
return ret[0]
else:
config = configurator.Configurator().config
msg = futils.Message(config.unittest_log_level)
msg.print_verbose('No valid "Any" context found')
return None
class _NoContext(collections.UserList):
"""
May be safely returned by context element class 'filter' method if
its items are not required during test execution
(e. g. no dax devices required by test)
"""
def __init__(self):
self.data = []
self.data.append(False)
def __bool__(self):
return False
NO_CONTEXT = _NoContext()
| 17,801 | 31.25 | 79 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/test_types.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019, Intel Corporation
#
"""Test type context classes"""
import context as ctx
class _TestType(metaclass=ctx.CtxType):
"""Base class for a test duration"""
class Short(_TestType):
pass
class Medium(_TestType):
pass
class Long(_TestType):
pass
class Check(_TestType):
includes = [Short, Medium]
| 378 | 13.037037 | 40 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ctx_filter.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
"""
Functionalities for acquiring (through 'filtering' execution configuration and
test specification) set of context parameters with which the test will be run
"""
import sys
import itertools
import builds
import futils
import granularity
import devdax
import context as ctx
import valgrind as vg
import requirements as req
if sys.platform != 'win32':
CTX_TYPES = (vg.Valgrind, granularity.Granularity, devdax.DevDaxes)
else:
CTX_TYPES = (granularity.Granularity, )
class CtxFilter:
"""
Generates contexts based on provided
configuration and test requirements
"""
def __init__(self, config, tc):
self.tc = tc
self.config = config
self.msg = futils.Message(config.unittest_log_level)
def _get_builds(self):
return builds.Build.filter(self.config, self.msg, self.tc)
def get_contexts(self):
"""
Generate a list of context based on configuration and
test requirements
"""
reqs = req.Requirements()
if not reqs.check_if_all_requirements_are_met(self.tc):
return []
conf_params = self._get_configured_params()
common_params = self._get_common_params()
ctx_arg_keys = list(conf_params.keys()) + list(common_params.keys())
builds = self._get_builds()
ctx_params = itertools.product(builds, *conf_params.values(),
*common_params.values())
ctxs = []
for cp in ctx_params:
build = cp[0]
kwargs = dict(zip(ctx_arg_keys, cp[1:]))
c = ctx.Context(build, **kwargs)
c.cwd = self.tc.cwd
ctxs.append(c)
return ctxs
def _get_configured_params(self):
"""
Get special test parameters, like file system or valgrind tool
which final content depends on test requirements, user configuration
and/or provided test plan.
"""
params = {}
for param in CTX_TYPES:
params[param.__name__.lower()] = \
param.filter(self.config, self.msg, self.tc)
return params
def _get_common_params(self):
return ctx.get_params(self.tc)
| 2,286 | 27.234568 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_utils.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* ut_pmem2_utils.c -- utility helper functions for libpmem2 tests
*/
#include "unittest.h"
#include "ut_pmem2_utils.h"
/*
* ut_pmem2_expect_return -- veryfies error code and prints appropriate
* error message in case of error
*/
void ut_pmem2_expect_return(const char *file, int line, const char *func,
int value, int expected)
{
if (value != expected) {
ut_fatal(file, line, func,
"unexpected return code (got %d, expected: %d): %s",
value, expected,
(value == 0 ? "success" : pmem2_errormsg()));
}
}
| 608 | 23.36 | 73 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_utils.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, Intel Corporation */
/*
* ut_pmem2_utils.h -- utility helper functions for libpmem2 tests
*/
#ifndef UT_PMEM2_UTILS_H
#define UT_PMEM2_UTILS_H 1
/* veryfies error code and prints appropriate error message in case of error */
#define UT_PMEM2_EXPECT_RETURN(value, expected) \
ut_pmem2_expect_return(__FILE__, __LINE__, __func__, \
value, expected)
void ut_pmem2_expect_return(const char *file, int line, const char *func,
int value, int expected);
#endif /* UT_PMEM2_UTILS_H */
| 552 | 26.65 | 79 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_fh.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* ut_fh.h -- OS-independent file handle / file descriptor interface
*/
#ifndef UT_FH_H
#define UT_FH_H
#include "os.h"
struct FHandle;
enum file_handle_type { FH_FD, FH_HANDLE };
#define FH_ACCMODE (7)
#define FH_READ (1 << 0)
#define FH_WRITE (1 << 1)
#define FH_RDWR (FH_READ | FH_WRITE)
#define FH_EXEC (1 << 2)
#define FH_CREAT (1 << 3)
#define FH_EXCL (1 << 4)
#define FH_TRUNC (1 << 5)
/* needs directory, on Windows it creates publicly visible file */
#define FH_TMPFILE (1 << 6)
#define FH_DIRECTORY (1 << 7)
#define UT_FH_OPEN(type, path, flags, ...) \
ut_fh_open(__FILE__, __LINE__, __func__, type, path, \
flags, ##__VA_ARGS__)
#define UT_FH_TRUNCATE(fhandle, size) \
ut_fh_truncate(__FILE__, __LINE__, __func__, fhandle, size)
#define UT_FH_GET_FD(fhandle) \
ut_fh_get_fd(__FILE__, __LINE__, __func__, fhandle)
#ifdef _WIN32
#define UT_FH_GET_HANDLE(fhandle) \
ut_fh_get_handle(__FILE__, __LINE__, __func__, fhandle)
#endif
#define UT_FH_CLOSE(fhandle) \
ut_fh_close(__FILE__, __LINE__, __func__, fhandle)
struct FHandle *ut_fh_open(const char *file, int line, const char *func,
enum file_handle_type type, const char *path, int flags, ...);
void ut_fh_truncate(const char *file, int line, const char *func,
struct FHandle *f, os_off_t length);
void ut_fh_close(const char *file, int line, const char *func,
struct FHandle *f);
enum file_handle_type ut_fh_get_handle_type(struct FHandle *fh);
int ut_fh_get_fd(const char *file, int line, const char *func,
struct FHandle *f);
#ifdef _WIN32
HANDLE ut_fh_get_handle(const char *file, int line, const char *func,
struct FHandle *f);
#endif
#endif
| 1,761 | 24.536232 | 72 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_file.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* ut_file.c -- unit test file operations
*/
#include "unittest.h"
/*
* ut_open -- an open that cannot return < 0
*/
int
ut_open(const char *file, int line, const char *func, const char *path,
int flags, ...)
{
va_list ap;
int mode;
va_start(ap, flags);
mode = va_arg(ap, int);
int retval = os_open(path, flags, mode);
va_end(ap);
if (retval < 0)
ut_fatal(file, line, func, "!open: %s", path);
return retval;
}
#ifdef _WIN32
/*
* ut_wopen -- a _wopen that cannot return < 0
*/
int
ut_wopen(const char *file, int line, const char *func, const wchar_t *path,
int flags, ...)
{
va_list ap;
int mode;
va_start(ap, flags);
mode = va_arg(ap, int);
int retval = _wopen(path, flags, mode);
va_end(ap);
if (retval < 0)
ut_fatal(file, line, func, "!wopen: %s", ut_toUTF8(path));
return retval;
}
#endif
/*
* ut_close -- a close that cannot return -1
*/
int
ut_close(const char *file, int line, const char *func, int fd)
{
int retval = os_close(fd);
if (retval != 0)
ut_fatal(file, line, func, "!close: %d", fd);
return retval;
}
/*
* ut_fopen --an fopen that cannot return != 0
*/
FILE *
ut_fopen(const char *file, int line, const char *func, const char *path,
const char *mode)
{
FILE *retval = os_fopen(path, mode);
if (retval == NULL)
ut_fatal(file, line, func, "!fopen: %s", path);
return retval;
}
/*
* ut_fclose -- a fclose that cannot return != 0
*/
int
ut_fclose(const char *file, int line, const char *func, FILE *stream)
{
int retval = os_fclose(stream);
if (retval != 0) {
ut_fatal(file, line, func, "!fclose: 0x%llx",
(unsigned long long)stream);
}
return retval;
}
/*
* ut_unlink -- an unlink that cannot return -1
*/
int
ut_unlink(const char *file, int line, const char *func, const char *path)
{
int retval = os_unlink(path);
if (retval != 0)
ut_fatal(file, line, func, "!unlink: %s", path);
return retval;
}
/*
* ut_posix_fallocate -- a posix_fallocate that cannot return -1
*/
int
ut_posix_fallocate(const char *file, int line, const char *func, int fd,
os_off_t offset, os_off_t len)
{
int retval = os_posix_fallocate(fd, offset, len);
if (retval != 0) {
errno = retval;
ut_fatal(file, line, func,
"!fallocate: fd %d offset 0x%llx len %llu",
fd, (unsigned long long)offset, (unsigned long long)len);
}
return retval;
}
/*
* ut_write -- a write that can't return -1
*/
size_t
ut_write(const char *file, int line, const char *func, int fd,
const void *buf, size_t count)
{
#ifndef _WIN32
ssize_t retval = write(fd, buf, count);
#else
/*
* XXX - do multiple write() calls in a loop?
* Or just use native Windows API?
*/
if (count > UINT_MAX)
ut_fatal(file, line, func, "read: count > UINT_MAX (%zu > %u)",
count, UINT_MAX);
ssize_t retval = _write(fd, buf, (unsigned)count);
#endif
if (retval < 0)
ut_fatal(file, line, func, "!write: %d", fd);
return (size_t)retval;
}
/*
* ut_read -- a read that can't return -1
*/
size_t
ut_read(const char *file, int line, const char *func, int fd,
void *buf, size_t count)
{
#ifndef _WIN32
ssize_t retval = read(fd, buf, count);
#else
/*
* XXX - do multiple read() calls in a loop?
* Or just use native Windows API?
*/
if (count > UINT_MAX)
ut_fatal(file, line, func, "read: count > UINT_MAX (%zu > %u)",
count, UINT_MAX);
ssize_t retval = read(fd, buf, (unsigned)count);
#endif
if (retval < 0)
ut_fatal(file, line, func, "!read: %d", fd);
return (size_t)retval;
}
/*
* ut_lseek -- an lseek that can't return -1
*/
os_off_t
ut_lseek(const char *file, int line, const char *func, int fd,
os_off_t offset, int whence)
{
os_off_t retval = os_lseek(fd, offset, whence);
if (retval == -1)
ut_fatal(file, line, func, "!lseek: %d", fd);
return retval;
}
/*
* ut_fstat -- a fstat that cannot return -1
*/
int
ut_fstat(const char *file, int line, const char *func, int fd,
os_stat_t *st_bufp)
{
int retval = os_fstat(fd, st_bufp);
if (retval < 0)
ut_fatal(file, line, func, "!fstat: %d", fd);
#ifdef _WIN32
/* clear unused bits to avoid confusion */
st_bufp->st_mode &= 0600;
#endif
return retval;
}
/*
* ut_stat -- a stat that cannot return -1
*/
int
ut_stat(const char *file, int line, const char *func, const char *path,
os_stat_t *st_bufp)
{
int retval = os_stat(path, st_bufp);
if (retval < 0)
ut_fatal(file, line, func, "!stat: %s", path);
#ifdef _WIN32
/* clear unused bits to avoid confusion */
st_bufp->st_mode &= 0600;
#endif
return retval;
}
#ifdef _WIN32
/*
* ut_statW -- a stat that cannot return -1
*/
int
ut_statW(const char *file, int line, const char *func, const wchar_t *path,
os_stat_t *st_bufp)
{
int retval = ut_util_statW(path, st_bufp);
if (retval < 0)
ut_fatal(file, line, func, "!stat: %S", path);
#ifdef _WIN32
/* clear unused bits to avoid confusion */
st_bufp->st_mode &= 0600;
#endif
return retval;
}
#endif
/*
* ut_mmap -- a mmap call that cannot return MAP_FAILED
*/
void *
ut_mmap(const char *file, int line, const char *func, void *addr,
size_t length, int prot, int flags, int fd, os_off_t offset)
{
void *ret_addr = mmap(addr, length, prot, flags, fd, offset);
if (ret_addr == MAP_FAILED) {
const char *error = "";
#ifdef _WIN32
/*
* XXX: on Windows mmap is implemented and exported by libpmem
*/
error = pmem_errormsg();
#endif
ut_fatal(file, line, func,
"!mmap: addr=0x%llx length=0x%zx prot=%d flags=%d fd=%d offset=0x%llx %s",
(unsigned long long)addr, length, prot,
flags, fd, (unsigned long long)offset, error);
}
return ret_addr;
}
/*
* ut_munmap -- a munmap call that cannot return -1
*/
int
ut_munmap(const char *file, int line, const char *func, void *addr,
size_t length)
{
int retval = munmap(addr, length);
if (retval < 0)
ut_fatal(file, line, func, "!munmap: addr=0x%llx length=0x%zx",
(unsigned long long)addr, length);
return retval;
}
/*
* ut_mprotect -- a mprotect call that cannot return -1
*/
int
ut_mprotect(const char *file, int line, const char *func, void *addr,
size_t len, int prot)
{
int retval = mprotect(addr, len, prot);
if (retval < 0)
ut_fatal(file, line, func,
"!mprotect: addr=0x%llx length=0x%zx prot=0x%x",
(unsigned long long)addr, len, prot);
return retval;
}
/*
* ut_ftruncate -- a ftruncate that cannot return -1
*/
int
ut_ftruncate(const char *file, int line, const char *func, int fd,
os_off_t length)
{
int retval = os_ftruncate(fd, length);
if (retval < 0)
ut_fatal(file, line, func, "!ftruncate: %d %llu",
fd, (unsigned long long)length);
return retval;
}
| 6,695 | 19.290909 | 77 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/requirements.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2020, Intel Corporation
#
"""Various requirements"""
import subprocess as sp
import ctypes
import sys
import os
import configurator as conf
import context as ctx
import futils
NDCTL_MIN_VERSION = '63'
class Requirements:
"""Various requirements"""
def __init__(self):
self.cfg = conf.Configurator().config
def _check_pkgconfig(self, pkg, min_ver):
"""
Run pkg-config to check if a package is installed
"""
proc = sp.run(['pkg-config', pkg, '--atleast-version', min_ver],
stdout=sp.PIPE, stderr=sp.STDOUT)
return proc.returncode == 0
def _is_ndctl_enabled(self):
path = futils.get_tool_path(ctx, "pmempool")
s = sp.check_output(["strings", path])
if "compiled with libndctl" in str(s):
return True
return False
def _check_is_admin(self):
if sys.platform == 'win32':
return ctypes.windll.shell32.IsUserAnAdmin() != 0
else:
return os.getuid() == 0
def check_ndctl(self):
is_ndctl = self._check_pkgconfig('libndctl', NDCTL_MIN_VERSION)
if not is_ndctl:
raise futils.Skip('libndctl (>=v{}) is not installed'
.format(NDCTL_MIN_VERSION))
def check_ndctl_enable(self):
if self._is_ndctl_enabled() is False:
raise futils.Skip('ndctl is disabled - binary not '
'compiled with libndctl')
def _check_ndctl_req_is_met(self, tc):
"""
Check if all conditions for the ndctl requirement are met
"""
require_ndctl, _ = ctx.get_requirement(tc, 'require_ndctl', ())
if not require_ndctl:
return True
self.check_ndctl_enable()
self.check_ndctl()
return True
def _check_admin_req_is_met(self, tc):
"""
Check if all conditions for the admin requirement are met
"""
require_admin, _ = ctx.get_requirement(tc, 'require_admin', ())
if not require_admin:
# admin is not required
return True
if not self.cfg.enable_admin_tests:
raise futils.Skip('admin tests are not enabled in config '
'(enable_admin_tests)')
if not self._check_is_admin():
raise futils.Fail('Error: admin tests are enabled in config, '
'but the user does not have administrative '
'privileges')
# user is admin
return True
def check_if_all_requirements_are_met(self, tc):
if not self._check_ndctl_req_is_met(tc):
return False
if not self._check_admin_req_is_met(tc):
return False
"""More requirements can be checked here"""
return True
def require_ndctl(tc):
"""Enable test only if ndctl is installed"""
ctx.add_requirement(tc, 'require_ndctl', True)
return tc
def require_admin(tc):
"""
Disable test if "enable_admin_tests" configuration is not set
"""
ctx.add_requirement(tc, 'require_admin', True)
return tc
| 3,204 | 27.616071 | 74 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/granularity.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
#
"""Granularity context classes and utilities"""
import os
import shutil
from enum import Enum, unique
import context as ctx
import configurator
import futils
class Granularity(metaclass=ctx.CtxType):
gran_detecto_arg = None
config_dir_field = None
config_force_field = None
force_env = None
pmem_force_env = None
def __init__(self, **kwargs):
futils.set_kwargs_attrs(self, kwargs)
self.config = configurator.Configurator().config
dir_ = os.path.abspath(getattr(self.config, self.config_dir_field))
self.testdir = os.path.join(dir_, self.tc_dirname)
force = getattr(self.config, self.config_force_field)
if force:
self.env = {
'PMEM2_FORCE_GRANULARITY': self.force_env,
# PMEM2_FORCE_GRANULARITY is implemented only by
# libpmem2. Corresponding PMEM_IS_PMEM_FORCE variable
# is set to support tests for older PMDK libraries.
'PMEM_IS_PMEM_FORCE': self.pmem_force_env
}
def setup(self, tools=None):
if not os.path.exists(self.testdir):
os.makedirs(self.testdir)
check_page = tools.gran_detecto(self.testdir, self.gran_detecto_arg)
if check_page.returncode != 0:
msg = check_page.stdout
detect = tools.gran_detecto(self.testdir, '-d')
msg = '{}{}{}'.format(os.linesep, msg, detect.stdout)
raise futils.Fail('Granularity check for {} failed: {}'
.format(self.testdir, msg))
def clean(self, *args, **kwargs):
shutil.rmtree(self.testdir, ignore_errors=True)
@classmethod
def testdir_defined(cls, config):
"""
Check if test directory used by specific granularity setup
is defined by test configuration
"""
try:
if not cls.config_dir_field:
return False
getattr(config, cls.config_dir_field)
except futils.Skip as s:
msg = futils.Message(config.unittest_log_level)
msg.print_verbose(s)
return False
else:
return True
@classmethod
def filter(cls, config, msg, tc):
"""
Acquire file system granularity for the test to be run
based on configuration and test requirements
"""
req_gran, kwargs = ctx.get_requirement(tc, 'granularity', None)
# remove granularities if respective test directories in
# test config are not defined
conf_defined = [c for c in config.granularity
if c.testdir_defined(config)]
if req_gran == Non:
return [Non(**kwargs), ]
if req_gran == _CACHELINE_OR_LESS:
tmp_req_gran = [Byte, CacheLine]
elif req_gran == _PAGE_OR_LESS:
tmp_req_gran = [Byte, CacheLine, Page]
elif req_gran == [ctx.Any, ]:
tmp_req_gran = ctx.Any.get(conf_defined)
else:
tmp_req_gran = req_gran
filtered = ctx.filter_contexts(conf_defined, tmp_req_gran)
kwargs['tc_dirname'] = tc.tc_dirname
if len(filtered) > 1 and req_gran == _CACHELINE_OR_LESS or \
req_gran == _PAGE_OR_LESS:
def order_by_smallest(elem):
ordered = [Byte, CacheLine, Page]
return ordered.index(elem)
# take the smallest available granularity
filtered.sort(key=order_by_smallest)
filtered = [filtered[0], ]
gs = []
for g in filtered:
try:
gs.append(g(**kwargs))
except futils.Skip as s:
msg.print_verbose('{}: SKIP: {}'.format(tc, s))
return gs
class Page(Granularity):
config_dir_field = 'page_fs_dir'
config_force_field = 'force_page'
force_env = 'PAGE'
pmem_force_env = '0'
gran_detecto_arg = '-p'
class CacheLine(Granularity):
config_dir_field = 'cacheline_fs_dir'
config_force_field = 'force_cacheline'
force_env = 'CACHE_LINE'
pmem_force_env = '1'
gran_detecto_arg = '-c'
class Byte(Granularity):
config_dir_field = 'byte_fs_dir'
config_force_field = 'force_byte'
force_env = 'BYTE'
pmem_force_env = '1'
gran_detecto_arg = '-b'
class Non(Granularity):
"""
No filesystem is used - granularity is irrelevant to the test.
To ensure that the test indeed does not use any filesystem,
accessing some fields of this class is prohibited.
"""
explicit = True
def __init__(self, **kwargs):
pass
def setup(self, tools=None):
pass
def cleanup(self, *args, **kwargs):
pass
def __getattribute__(self, name):
if name in ('dir', ):
raise AttributeError("'{}' attribute cannot be used if the"
" test is meant not to use any "
"filesystem"
.format(name))
else:
return super().__getattribute__(name)
# special kind of granularity requirement
_CACHELINE_OR_LESS = 'cacheline_or_less'
_PAGE_OR_LESS = 'page_or_less'
@unique
class _Granularity(Enum):
PAGE = Page
CACHELINE = CacheLine
BYTE = Byte
CL_OR_LESS = _CACHELINE_OR_LESS
PAGE_OR_LESS = _PAGE_OR_LESS
ANY = ctx.Any
PAGE = _Granularity.PAGE
CACHELINE = _Granularity.CACHELINE
BYTE = _Granularity.BYTE
CL_OR_LESS = _Granularity.CL_OR_LESS
PAGE_OR_LESS = _Granularity.PAGE_OR_LESS
ANY = _Granularity.ANY
def require_granularity(*granularity, **kwargs):
for g in granularity:
if not isinstance(g, _Granularity):
raise ValueError('selected granularity {} is invalid'
.format(g))
enum_values = [g.value for g in granularity]
def wrapped(tc):
ctx.add_requirement(tc, 'granularity', enum_values, **kwargs)
return tc
return wrapped
def no_testdir(**kwargs):
def wrapped(tc):
ctx.add_requirement(tc, 'granularity', Non, **kwargs)
return tc
return wrapped
| 6,257 | 28.242991 | 77 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/utils.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
"""Utilities for tests"""
import sys
import platform
HEADER_SIZE = 4096
#
# KiB, MiB, GiB ... -- byte unit prefixes
#
KiB = 2 ** 10
MiB = 2 ** 20
GiB = 2 ** 30
TiB = 2 ** 40
PiB = 2 ** 50
# platform.machine() used for detecting architectures
# gives different values for different systems.
# Key is a normalized value of possible returned architecture values.
NORMALIZED_ARCHS = {
'x86_64': ('AMD64', 'x86_64'),
'arm64': ('arm64', 'aarch64'),
'ppc64el': ('ppc64el', 'ppc64le')
}
def require_architectures(*archs):
"""Enable test only for specified architectures"""
def wrapped(tc):
this_arch = platform.machine()
# normalize this_arch value
for normalized, possible in NORMALIZED_ARCHS.items():
if this_arch in possible:
this_arch = normalized
if this_arch not in archs:
tc.enabled = False
return tc
return wrapped
def _os_only(tc, os_name):
"""
Disable test case (TEST[number] class) if NOT run on selected OS.
Otherwise, the test is not reenabled if it was already disabled
elsewhere.
Internal helper function.
"""
if not sys.platform.startswith(os_name):
tc.enabled = False
return tc
def _os_exclude(tc, os_name):
"""
Disable test case (TEST[number] class) on selected OS.
Internal helper function.
"""
if sys.platform.startswith(os_name):
tc.enabled = False
return tc
def windows_only(tc):
"""
Disable test case (TEST[number] class) if NOT run on Windows.
Use it as a class decorator.
"""
return _os_only(tc, 'win32')
def linux_only(tc):
"""
Disable test case (TEST[number] class) if NOT run on Linux.
Use it as a class decorator.
"""
return _os_only(tc, 'linux')
def freebsd_only(tc):
"""
Disable test case (TEST[number] class) if NOT run on FreeBSD.
Use it as a class decorator.
"""
return _os_only(tc, 'freebsd')
def windows_exclude(tc):
"""
Disable test case (TEST[number] class) on Windows.
Use it as a class decorator.
"""
return _os_exclude(tc, 'win32')
def linux_exclude(tc):
"""
Disable test case (TEST[number] class) on Linux.
Use it as a class decorator.
"""
return _os_exclude(tc, 'linux')
def freebsd_exclude(tc):
"""
Disable test case (TEST[number] class) on FreeBSD.
Use it as a class decorator.
"""
return _os_exclude(tc, 'freebsd')
| 2,557 | 21.051724 | 69 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_source.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* ut_pmem2_source.h -- utility helper functions for libpmem2 source tests
*/
#include <libpmem2.h>
#include "unittest.h"
#include "ut_pmem2_source.h"
#include "ut_pmem2_utils.h"
/*
* ut_pmem2_source_from_fd -- sets fd (cannot fail)
*/
void
ut_pmem2_source_from_fd(const char *file, int line, const char *func,
struct pmem2_source **src, int fd)
{
int ret = pmem2_source_from_fd(src, fd);
ut_pmem2_expect_return(file, line, func, ret, 0);
}
void
ut_pmem2_source_from_fh(const char *file, int line, const char *func,
struct pmem2_source **src, struct FHandle *f)
{
enum file_handle_type type = ut_fh_get_handle_type(f);
int ret;
if (type == FH_FD) {
int fd = ut_fh_get_fd(file, line, func, f);
#ifdef _WIN32
ret = pmem2_source_from_handle(src, (HANDLE)_get_osfhandle(fd));
#else
ret = pmem2_source_from_fd(src, fd);
#endif
} else if (type == FH_HANDLE) {
#ifdef _WIN32
HANDLE h = ut_fh_get_handle(file, line, func, f);
ret = pmem2_source_from_handle(src, h);
#else
ut_fatal(file, line, func,
"FH_HANDLE not supported on !Windows");
#endif
} else {
ut_fatal(file, line, func,
"unknown file handle type");
}
ut_pmem2_expect_return(file, line, func, ret, 0);
}
void
ut_pmem2_source_alignment(const char *file, int line, const char *func,
struct pmem2_source *src, size_t *al)
{
int ret = pmem2_source_alignment(src, al);
ut_pmem2_expect_return(file, line, func, ret, 0);
}
void
ut_pmem2_source_delete(const char *file, int line, const char *func,
struct pmem2_source **src)
{
int ret = pmem2_source_delete(src);
ut_pmem2_expect_return(file, line, func, ret, 0);
UT_ASSERTeq(*src, NULL);
}
void
ut_pmem2_source_size(const char *file, int line, const char *func,
struct pmem2_source *src, size_t *size)
{
int ret = pmem2_source_size(src, size);
ut_pmem2_expect_return(file, line, func, ret, 0);
}
| 1,929 | 24.064935 | 74 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_signal.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* ut_signal.c -- unit test signal operations
*/
#include "unittest.h"
#ifdef _WIN32
/*
* On Windows, Access Violation exception does not raise SIGSEGV signal.
* The trick is to catch the exception and... call the signal handler.
*/
/*
* Sigactions[] - allows registering more than one signal/exception handler
*/
static struct sigaction Sigactions[NSIG];
/*
* exception_handler -- called for unhandled exceptions
*/
static LONG CALLBACK
exception_handler(_In_ PEXCEPTION_POINTERS ExceptionInfo)
{
DWORD excode = ExceptionInfo->ExceptionRecord->ExceptionCode;
if (excode == EXCEPTION_ACCESS_VIOLATION)
Sigactions[SIGSEGV].sa_handler(SIGSEGV);
return EXCEPTION_CONTINUE_EXECUTION;
}
/*
* signal_handler_wrapper -- (internal) wrapper for user-defined signal handler
*
* Before the specified handler function is executed, signal disposition
* is reset to SIG_DFL. This wrapper allows to handle subsequent signals
* without the need to set the signal disposition again.
*/
static void
signal_handler_wrapper(int signum)
{
_crt_signal_t retval = signal(signum, signal_handler_wrapper);
if (retval == SIG_ERR)
UT_FATAL("!signal: %d", signum);
if (Sigactions[signum].sa_handler)
Sigactions[signum].sa_handler(signum);
else
UT_FATAL("handler for signal: %d is not defined", signum);
}
#endif
/*
* ut_sigaction -- a sigaction that cannot return < 0
*/
int
ut_sigaction(const char *file, int line, const char *func,
int signum, struct sigaction *act, struct sigaction *oldact)
{
#ifndef _WIN32
int retval = sigaction(signum, act, oldact);
if (retval != 0)
ut_fatal(file, line, func, "!sigaction: %s",
os_strsignal(signum));
return retval;
#else
UT_ASSERT(signum < NSIG);
os_mutex_lock(&Sigactions_lock);
if (oldact)
*oldact = Sigactions[signum];
if (act)
Sigactions[signum] = *act;
os_mutex_unlock(&Sigactions_lock);
if (signum == SIGABRT) {
ut_suppress_errmsg();
}
if (signum == SIGSEGV) {
AddVectoredExceptionHandler(0, exception_handler);
}
_crt_signal_t retval = signal(signum, signal_handler_wrapper);
if (retval == SIG_ERR)
ut_fatal(file, line, func, "!signal: %d", signum);
if (oldact != NULL)
oldact->sa_handler = retval;
return 0;
#endif
}
| 2,306 | 23.806452 | 79 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/tools.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
#
"""External tools integration"""
import os
import json
import sys
import subprocess as sp
import futils
try:
import envconfig
envconfig = envconfig.config
except ImportError:
# if file doesn't exist create dummy object
envconfig = {'GLOBAL_LIB_PATH': '', 'PMEM2_AVX512F_ENABLED': ''}
class Tools:
PMEMDETECT_FALSE = 0
PMEMDETECT_TRUE = 1
PMEMDETECT_ERROR = 2
def __init__(self, env, build):
self.env = env
self.build = build
global_lib_path = envconfig['GLOBAL_LIB_PATH']
if sys.platform == 'win32':
futils.add_env_common(self.env, {'PATH': global_lib_path})
futils.add_env_common(self.env, {'PATH': build.libdir})
else:
futils.add_env_common(self.env,
{'LD_LIBRARY_PATH': global_lib_path})
futils.add_env_common(self.env, {'LD_LIBRARY_PATH': build.libdir})
def _run_test_tool(self, name, *args):
exe = futils.get_test_tool_path(self.build, name)
if sys.platform == 'win32':
exe += '.exe'
return sp.run([exe, *args], env=self.env, stdout=sp.PIPE,
stderr=sp.STDOUT, universal_newlines=True)
def pmemdetect(self, *args):
return self._run_test_tool('pmemdetect', *args)
def gran_detecto(self, *args):
return self._run_test_tool('gran_detecto', *args)
def cpufd(self):
return self._run_test_tool('cpufd')
class Ndctl:
"""ndctl CLI handle"""
def __init__(self):
self.version = self._get_ndctl_version()
self.ndctl_list_output = self._get_ndctl_list_output('list')
def _get_ndctl_version(self):
proc = sp.run(['ndctl', '--version'], stdout=sp.PIPE, stderr=sp.STDOUT)
if proc.returncode != 0:
raise futils.Fail('checking if ndctl exists failed:{}{}'
.format(os.linesep, proc.stdout))
version = proc.stdout.strip()
return version
def _get_ndctl_list_output(self, *args):
proc = sp.run(['ndctl', *args], stdout=sp.PIPE, stderr=sp.STDOUT)
if proc.returncode != 0:
raise futils.Fail('ndctl list failed:{}{}'.format(os.linesep,
proc.stdout))
try:
ndctl_list_out = json.loads(proc.stdout)
except json.JSONDecodeError:
raise futils.Fail('Invalid "ndctl list" output (could '
'not read as JSON): {}'.format(proc.stdout))
return ndctl_list_out
def _get_dev_info(self, dev_path):
dev = None
devtypes = ('blockdev', 'chardev')
for d in self._get_ndctl_list_output('list'):
for dt in devtypes:
if dt in d and os.path.join('/dev', d[dt]) == dev_path:
dev = d
if not dev:
raise futils.Fail('ndctl does not recognize the device: "{}"'
.format(dev_path))
return dev
# for ndctl v63 we need to parse ndctl list in a different way than for v64
def _get_dev_info_63(self, dev_path):
dev = None
devtype = 'chardev'
daxreg = 'daxregion'
for d in self._get_ndctl_list_output('list', '-v'):
if daxreg in d:
devices = d[daxreg]['devices']
for device in devices:
if devtype in device and \
os.path.join('/dev', device[devtype]) == dev_path:
# only params from daxreg are intrested at this point,
# other values are read by _get_dev_info() earlier
dev = d[daxreg]
if not dev:
raise futils.Fail('ndctl does not recognize the device: "{}"'
.format(dev_path))
return dev
def _get_dev_param(self, dev_path, param):
p = None
dev = self._get_dev_info(dev_path)
try:
p = dev[param]
except KeyError:
dev = self._get_dev_info_63(dev_path)
p = dev[param]
return p
def get_dev_size(self, dev_path):
return int(self._get_dev_param(dev_path, 'size'))
def get_dev_alignment(self, dev_path):
return int(self._get_dev_param(dev_path, 'align'))
def get_dev_mode(self, dev_path):
return self._get_dev_param(dev_path, 'mode')
def is_devdax(self, dev_path):
return self.get_dev_mode(dev_path) == 'devdax'
def is_fsdax(self, dev_path):
return self.get_dev_mode(dev_path) == 'fsdax'
| 4,705 | 31.232877 | 79 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_backtrace.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2017, Intel Corporation */
/*
* ut_backtrace.c -- backtrace reporting routines
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "unittest.h"
#ifdef USE_LIBUNWIND
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <dlfcn.h>
#define PROCNAMELEN 256
/*
* ut_dump_backtrace -- dump stacktrace to error log using libunwind
*/
void
ut_dump_backtrace(void)
{
unw_context_t context;
unw_proc_info_t pip;
pip.unwind_info = NULL;
int ret = unw_getcontext(&context);
if (ret) {
UT_ERR("unw_getcontext: %s [%d]", unw_strerror(ret), ret);
return;
}
unw_cursor_t cursor;
ret = unw_init_local(&cursor, &context);
if (ret) {
UT_ERR("unw_init_local: %s [%d]", unw_strerror(ret), ret);
return;
}
ret = unw_step(&cursor);
char procname[PROCNAMELEN];
unsigned i = 0;
while (ret > 0) {
ret = unw_get_proc_info(&cursor, &pip);
if (ret) {
UT_ERR("unw_get_proc_info: %s [%d]", unw_strerror(ret),
ret);
break;
}
unw_word_t off;
ret = unw_get_proc_name(&cursor, procname, PROCNAMELEN, &off);
if (ret && ret != -UNW_ENOMEM) {
if (ret != -UNW_EUNSPEC) {
UT_ERR("unw_get_proc_name: %s [%d]",
unw_strerror(ret), ret);
}
strcpy(procname, "?");
}
void *ptr = (void *)(pip.start_ip + off);
Dl_info dlinfo;
const char *fname = "?";
uintptr_t in_object_offset = 0;
if (dladdr(ptr, &dlinfo) && dlinfo.dli_fname &&
*dlinfo.dli_fname) {
fname = dlinfo.dli_fname;
uintptr_t base = (uintptr_t)dlinfo.dli_fbase;
if ((uintptr_t)ptr >= base)
in_object_offset = (uintptr_t)ptr - base;
}
UT_ERR("%u: %s (%s%s+0x%lx) [%p] [0x%" PRIxPTR "]",
i++, fname, procname,
ret == -UNW_ENOMEM ? "..." : "", off, ptr,
in_object_offset);
ret = unw_step(&cursor);
if (ret < 0)
UT_ERR("unw_step: %s [%d]", unw_strerror(ret), ret);
}
}
#else /* USE_LIBUNWIND */
#define SIZE 100
#ifndef _WIN32
#include <execinfo.h>
/*
* ut_dump_backtrace -- dump stacktrace to error log using libc's backtrace
*/
void
ut_dump_backtrace(void)
{
int j, nptrs;
void *buffer[SIZE];
char **strings;
nptrs = backtrace(buffer, SIZE);
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
UT_ERR("!backtrace_symbols");
return;
}
for (j = 0; j < nptrs; j++)
UT_ERR("%u: %s", j, strings[j]);
free(strings);
}
#else /* _WIN32 */
#include <DbgHelp.h>
/*
* ut_dump_backtrace -- dump stacktrace to error log
*/
void
ut_dump_backtrace(void)
{
void *buffer[SIZE];
unsigned nptrs;
SYMBOL_INFO *symbol;
HANDLE proc_hndl = GetCurrentProcess();
SymInitialize(proc_hndl, NULL, TRUE);
nptrs = CaptureStackBackTrace(0, SIZE, buffer, NULL);
symbol = CALLOC(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(CHAR), 1);
symbol->MaxNameLen = MAX_SYM_NAME - 1;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (unsigned i = 0; i < nptrs; i++) {
if (SymFromAddr(proc_hndl, (DWORD64)buffer[i], 0, symbol)) {
UT_ERR("%u: %s [%p]", nptrs - i - 1, symbol->Name,
buffer[i]);
} else {
UT_ERR("%u: [%p]", nptrs - i - 1, buffer[i]);
}
}
FREE(symbol);
}
#endif /* _WIN32 */
#endif /* USE_LIBUNWIND */
/*
* ut_sighandler -- fatal signal handler
*/
void
ut_sighandler(int sig)
{
/*
* Usually SIGABRT is a result of ASSERT() or FATAL().
* We don't need backtrace, as the reason of the failure
* is logged in debug traces.
*/
if (sig != SIGABRT) {
UT_ERR("\n");
UT_ERR("Signal %d, backtrace:", sig);
ut_dump_backtrace();
UT_ERR("\n");
}
exit(128 + sig);
}
/*
* ut_register_sighandlers -- register signal handlers for various fatal signals
*/
void
ut_register_sighandlers(void)
{
signal(SIGSEGV, ut_sighandler);
signal(SIGABRT, ut_sighandler);
signal(SIGILL, ut_sighandler);
signal(SIGFPE, ut_sighandler);
signal(SIGINT, ut_sighandler);
#ifndef _WIN32
signal(SIGQUIT, ut_sighandler);
signal(SIGBUS, ut_sighandler);
#endif
}
| 3,915 | 18.678392 | 80 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pthread.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* ut_pthread.c -- unit test wrappers for pthread routines
*/
#include "unittest.h"
/*
* ut_thread_create -- a os_thread_create that cannot return an error
*/
int
ut_thread_create(const char *file, int line, const char *func,
os_thread_t *__restrict thread,
const os_thread_attr_t *__restrict attr,
void *(*start_routine)(void *), void *__restrict arg)
{
if ((errno = os_thread_create(thread, attr, start_routine, arg)) != 0)
ut_fatal(file, line, func, "!os_thread_create");
return 0;
}
/*
* ut_thread_join -- a os_thread_join that cannot return an error
*/
int
ut_thread_join(const char *file, int line, const char *func,
os_thread_t *thread, void **value_ptr)
{
if ((errno = os_thread_join(thread, value_ptr)) != 0)
ut_fatal(file, line, func, "!os_thread_join");
return 0;
}
| 901 | 23.378378 | 71 |
c
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_map.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* ut_pmem2_map.h -- utility helper functions for libpmem2 map tests
*/
#ifndef UT_PMEM2_MAP_H
#define UT_PMEM2_MAP_H 1
/* a pmem2_map() that can't return NULL */
#define PMEM2_MAP(cfg, src, map) \
ut_pmem2_map(__FILE__, __LINE__, __func__, cfg, src, map)
void ut_pmem2_map(const char *file, int line, const char *func,
struct pmem2_config *cfg, struct pmem2_source *src,
struct pmem2_map **map);
#endif /* UT_PMEM2_MAP_H */
| 522 | 25.15 | 68 |
h
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/poolset.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019, Intel Corporation
#
"""Tools which allows to easily create poolset files"""
from enum import Enum, unique
import os
import futils
from utils import KiB, MiB, GiB
POOL_MIN_SIZE = 8 * MiB
PART_MIN_SIZE = 2 * MiB
@unique
class CREATE(Enum):
"""
CREATE allows to create part files during creation of poolset file.
When ZEROED, HDR_ZEROED, DATA_ZEROED option is passed
user should specify fsize and optionally mode.
ZEROED - create a file filled with \0 characters
NON_ZEROED - create a file filled with \132 characters
HDR_ZEROED - create a file with a zeroed header and rest filled
with \132
"""
ZEROED = 0
NON_ZEROED = 1
HDR_ZEROED = 2
class _Poolset:
"""
An interface for easy poolset files creation.
To get new Poolset for testcase call ctx.new_poolset(name).
Example usage:
poolset = ctx.new_poolset('poolset')
poolset.set_parts(File('part0.pool', 10*MiB),
DDax(ctx, 'daxpath'))
poolset.add_replica(File('part0.rep1', 20*MiB),
File('part1.rep1', 5*MiB).Create(
t.CREATE.ZEROED, 100 * MiB))
poolset.add_replica(Dir('dirpart.rep1', 2*GiB))
poolset.add_remote('poolset.remote', '127.0.0.1')
poolset.set_nohdrs()
poolset.create()
"""
def __init__(self, path, ctx):
self.path = path
self.parts = []
self.replicas = []
self.options = []
self.remote = []
self.ctx = ctx
def set_parts(self, *parts):
"""
Adds a main pool to the poolset file.
The function accepts a list of Parts of any length.
Should not be called more than once.
"""
if not self.parts:
self.parts = list(parts)
else:
futils.fail('This function should not be called more than once.')
def add_replica(self, *parts):
"""
Adds local replica to poolset file.
The function accepts a list of Parts of any length.
Each function call create a new replica.
"""
self.replicas.append(parts)
def add_remote(self, path, node):
"""
Adds remote poolset file. A path should be relative to
the rpmemd poolset-dir. For details please see the
rpmemd(1) manual page.Each function call create new
remote replica.
"""
self.remote.append((path, node))
def set_singlehdr(self):
"""
If called, poolset will be created with SINGLEHDR option.
"""
self.options.append('SINGLEHDR')
def set_nohdrs(self):
"""
If called, poolset will be created with NOHDRS option.
"""
self.options.append('NOHDRS')
def create(self):
"""
Create a poolset file with basic space validation. If CREATE arguments
ware passed to parts, create parts files as well.
"""
self._check_pools_size()
required_size = self._get_required_size()
free_space = self.ctx.get_free_space()
if required_size > free_space:
futils.fail('Not enough space available to create parts '
'files. There is {}, and poolset requires {}'
.format(free_space, required_size))
for part in self.parts:
part._process(self.ctx)
for replica in self.replicas:
for part in replica:
part._process(self.ctx)
self.options = list(set(self.options))
poolsetpath = os.path.join(self.ctx.testdir, self.path)
with open(poolsetpath, 'w') as poolset:
print('PMEMPOOLSET', end='\n\n', file=poolset)
for option in self.options:
print('OPTION', option, end='\n\n', file=poolset)
for part in self.parts:
print(part, file=poolset)
print(file=poolset)
for replica in self.replicas:
print("REPLICA", file=poolset)
for part in replica:
print(part, file=poolset)
print(file=poolset)
for remote in self.remote:
print("REPLICA", remote[1], remote[0], file=poolset)
def _check_pools_size(self):
""""
Validate if pool and replicas have more than 8MiB (minimum pool size).
This function does not validate remote replicas sizes.
"""
size = 0
for part in self.parts:
size += part.size
if size < POOL_MIN_SIZE:
futils.fail('The pool has to have at least 8 MiB')
for replica in self.replicas:
size = 0
for part in replica:
size += part.size
if size < POOL_MIN_SIZE:
futils.fail('The pool has to have at least 8 MiB')
def _get_required_size(self):
"""
Returns size required to create all part files
"""
size = 0
for part in self.parts:
if part is File and part.create is not None:
size += part.size
for replica in self.replicas:
for part in replica:
if part is File and part.create is not None:
size += part.size
return size
class _Part:
"""
An abstraction for poolset parts
"""
def __init__(self, path, size):
if size < PART_MIN_SIZE:
futils.fail('The part should have at least 2 MiB')
self.size = size
self.path = path
def __str__(self):
return '{} {}'.format(self._format(self.size), self.path)
def _process(self, ctx):
"""
Should be overridden by classes whose objects need to create
files or directories
"""
pass
@staticmethod
def _format(number):
"""
Formats given number and returns equivalent string with size extension
"""
if number % GiB == 0:
return '{}G'.format(int(number / GiB))
elif number % MiB == 0:
return '{}M'.format(int(number / MiB))
elif number % KiB == 0:
return '{}K'.format(int(number / KiB))
else:
return str(number) + 'B'
class File(_Part):
"""
An interface to file parts creations.
By default it accepts 2 arguments path and size and does not create a
passed file. To force file creation use Create(create, fsize, mode=None)
method.
Example usage:
part0 = File('part0', 10 * MiB)
part1 = File('part1', 20 * MiB).Create(CREATE.ZEROED, 20 * MiB, 0o777)
part2 = File('part1', 20 * MiB).Create(CREATE.ZEROED, 20 * MiB)
"""
def __init__(self, path, size):
_Part.__init__(self, path, size)
self.create = None
def Create(self, create, fsize, mode=None):
self.fsize = fsize
self.mode = mode
self.create = create
return self
def _process(self, ctx):
"""
Create file adequately to passed 'create' argument
"""
if self.create == CREATE.ZEROED:
ctx.create_holey_file(self.fsize, self.path, self.mode)
if self.create == CREATE.NON_ZEROED:
ctx.create_non_zero_file(self.fsize, self.path, self.mode)
if self.create == CREATE.HDR_ZEROED:
ctx.create_zeroed_hdr_file(self.fsize, self.path, self.mode)
class DDax(_Part):
"""
An interface to device dax parts creation
"""
def __init__(self, ctx, path):
if not ctx.is_devdax(path):
futils.fail('Part with path "{}" does not point to dax device'
.format(path))
_Part.__init__(self, path, ctx.get_size(path))
class Dir(_Part):
"""
An interface to dir parts creation
"""
def __init__(self, path, size, mode=None):
_Part.__init__(self, path, size)
self.mode = mode
def _process(self, ctx):
ctx.mkdirs(self.path, self.mode)
| 8,081 | 29.269663 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/devdax.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
#
"""Device dax context classes and utilities"""
import copy
import itertools
import os
import sys
import context as ctx
import futils
import requirements as req
import tools
class DevDax():
"""
Class representing dax device and its parameters
"""
def __init__(self, name, alignment=None, min_size=None, max_size=None):
self.name = name
self.path = None
self._req_alignment = alignment
self._req_min_size = min_size
self._req_max_size = max_size
self.assigned = False
def __str__(self):
return self.name
def try_assign(self, path):
"""
Try assigning to real dax device, identified by its path,
provided it meets defined requirements. In case of success, set DevDax
object attributes (like size and/or alignment) to the real dax device
values and return True. Return False otherwise.
"""
ndctl = tools.Ndctl()
p_size = ndctl.get_dev_size(path)
p_align = ndctl.get_dev_alignment(path)
if self._req_min_size and p_size < self._req_min_size:
return False
if self._req_max_size and p_size > self._req_max_size:
return False
if self._req_alignment and p_align != self._req_alignment:
return False
self.path = path
self.size = p_size
self.alignment = p_align
self.assigned = True
return True
class DevDaxes():
"""
Dax device context class representing a set of dax devices required
for test
"""
def __init__(self, *dax_devices):
self.dax_devices = tuple(dax_devices)
for dd in dax_devices:
setattr(self, dd.name, dd)
def setup(self, **kwargs):
# DevDax tests always require ndctl
req.Requirements().check_ndctl_enable()
req.Requirements().check_ndctl()
tools = kwargs['tools']
for dd in self.dax_devices:
proc = tools.pmemdetect('-d', dd.path)
if proc.returncode != 0:
raise futils.Fail('checking {} with pmemdetect failed:{}{}'
.format(dd.path, os.linesep, proc.stdout))
def __str__(self):
return 'devdax'
@classmethod
def filter(cls, config, msg, tc):
dax_devices, _ = ctx.get_requirement(tc, 'devdax', ())
if not dax_devices:
return ctx.NO_CONTEXT
elif sys.platform == 'win32' and tc.enabled:
raise futils.Fail('dax device functionality required by "{}" is '
'not available on Windows. Please disable the '
'test for this platform'.format(tc))
if not config.device_dax_path:
raise futils.Skip('No dax devices defined in testconfig')
if len(dax_devices) > len(config.device_dax_path):
raise futils.Skip('Not enough dax devices defined in testconfig '
'({} needed)'.format(len(dax_devices)))
ndctl = tools.Ndctl()
for c in config.device_dax_path:
if not ndctl.is_devdax(c):
raise futils.Fail('{} is not a dax device'.format(c))
assigned = _try_assign_by_requirements(config.device_dax_path,
dax_devices)
if not assigned:
raise futils.Skip('Dax devices in test configuration do not '
'meet test requirements')
return [DevDaxes(*assigned), ]
def _try_assign_by_requirements(configured, required):
"""
Try assigning dax devices defined as paths in test configuration to
dax device objects taking their requirements into account.
Return a sequence of all requirement objects if they were
successfully assigned to existing dax, otherwise return None.
Since the order in which requirement objects are tried to be
assigned may affect the final outcome, all permutations are checked.
"""
permutations = itertools.permutations(required)
for p in permutations:
conf_copy = configured[:]
req_copy = copy.deepcopy(p)
for dd in req_copy:
for i, c in enumerate(conf_copy):
if dd.try_assign(c):
conf_copy.pop(i)
break
if not dd.assigned:
# at least one device dax requirement cannot be assigned
# to any of devices defined in the configuration,
# try another permutation
break
if all(dd.assigned for dd in req_copy):
return req_copy
return None
def require_devdax(*dax_devices, **kwargs):
def wrapped(tc):
ctx.add_requirement(tc, 'devdax', tuple(dax_devices), **kwargs)
return tc
return wrapped
| 4,912 | 31.536424 | 78 |
py
|
null |
NearPMSW-main/nearpm/shadow/pmdk-sd/src/test/unittest/ut_pmem2_config.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* ut_pmem2_config.h -- utility helper functions for libpmem2 config tests
*/
#include <libpmem2.h>
#include "unittest.h"
#include "ut_pmem2_config.h"
#include "ut_pmem2_utils.h"
/*
* ut_pmem2_config_new -- allocates cfg (cannot fail)
*/
void
ut_pmem2_config_new(const char *file, int line, const char *func,
struct pmem2_config **cfg)
{
int ret = pmem2_config_new(cfg);
ut_pmem2_expect_return(file, line, func, ret, 0);
UT_ASSERTne(*cfg, NULL);
}
/*
* pmem2_config_set_required_store_granularity -- sets granularity
*/
void
ut_pmem2_config_set_required_store_granularity(const char *file, int line,
const char *func, struct pmem2_config *cfg, enum pmem2_granularity g)
{
int ret = pmem2_config_set_required_store_granularity(cfg, g);
ut_pmem2_expect_return(file, line, func, ret, 0);
}
/*
* ut_pmem2_config_delete -- deallocates cfg (cannot fail)
*/
void
ut_pmem2_config_delete(const char *file, int line, const char *func,
struct pmem2_config **cfg)
{
int ret = pmem2_config_delete(cfg);
ut_pmem2_expect_return(file, line, func, ret, 0);
UT_ASSERTeq(*cfg, NULL);
}
| 1,181 | 23.122449 | 74 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.