Compare commits

...

22 Commits

Author SHA1 Message Date
openharmony_ci
a68260acc2 !1141 Revert LLVM toolchain version to 12 for weekly
Merge pull request !1141 from haotuo/revert_llvm12
2023-04-10 16:24:00 +00:00
haotuo
9770cc6de3 Revert LLVM toolchain to 12 for weekly version
Signed-off-by: haotuo <haotuo@huawei.com>
Change-Id: I53b79372c945a2ff5552afb0750cf344e4808d23
2023-04-10 18:13:05 +08:00
openharmony_ci
f332a06e4c !1134 Ignore warnings for llvm15 upgrade
Merge pull request !1134 from enable_llvm15
2023-04-04 07:03:22 +00:00
guzhihao4
1ba32406bb Ignore warnings for enable llvm15
Issue: #I6LPWU

Signed-off-by: guzhihao4 <guzhihao4@huawei.com>
Change-Id: I7b558fa46239081890ae005de65ba8d2bba1d134
2023-04-03 16:42:22 +08:00
openharmony_ci
249ea71a11 !1135 修复 hm_liteipc.c 处的 typo
Merge pull request !1135 from 邹亚龙/master
2023-04-03 07:53:57 +00:00
Yalong Zou
814f5affd0 fix: 修复 hm_liteipc.c 处的 typo
应拼写成 Receive, 因此此处的函数名称应当是 CheckReceivedMsg.

Signed-off-by: Yalong Zou <yalongz@hust.edu.cn>
2023-03-15 23:04:21 +08:00
openharmony_ci
4ff66c7f40 !1133 fix: 修复网络容器测试失败问题
Merge pull request !1133 from zhushengle/container_net
2023-03-15 02:10:46 +00:00
zhushengle
8f937c8771 fix: 修复网络容器测试失败问题
1.修复网络容器测试失败问题
2.调整测试用例之间的顺序,提高测试用例的稳定性
3.极限压测用例增加延时,等待系统资源回收,增加用例稳定性
4.优化网络容器测试用例重复代码

Close #I6L7VF
Signed-off-by: zhushengle <zhushengle@huawei.com>
Change-Id: If800793430c872c432f5fdf2d9c2d968fafb3973
2023-03-09 14:18:24 +08:00
openharmony_ci
2845efe801 !1129 fix:修复内核调用栈解析脚本bug
Merge pull request !1129 from zhangdengyu/fix_debug_script
2023-03-04 06:21:52 +00:00
openharmony_ci
8cc5209181 !1132 feat:修复使用不规范的测试用例
Merge pull request !1132 from zhangdengyu/muslUpdate0303
2023-03-04 05:55:16 +00:00
zhangdengyu
f995c7c7af feat:修复使用不规范的测试用例
1、在编译kernel/liteos_a测试用例时process、extended、libc三个模块出现报错,主要分为以下几种类型:
   1.1、函数返回值为int或其它类型,错误使用了返回NULL的断言宏。修改断言宏返回正确的类型。
   1.2、函数返回值为int或其它类型,错误的return了NULL。修改成正确的返回值类型。
   1.3、waitpid函数第三个参数为int类型,错误传入了NULL。修改成正确的入参类型。
   1.4、使用的断言宏传入的参数一个为int或其他类型,一个为NULL,类似不匹配。修改成匹配的类型。
   1.5、testsuites/unittest/process/basic/pthread/smoke/pthread_test_012.cpp中调用Syscall接口,
        第二个参数为in类型,错误的传入了NULL。修改入参为正确的类型。
2、hb set选择ipcamera_hispark_taurus,编译之后使用nfs将out/hispark_taurus/ipcamera_hispark_taurus/test/unittest/kernel/bin目录中的
   9个测试用例放到单板上进行测试,运行结果全部通过,并生成对应结果从xml文件,其中liteos_a_basic_unittest.bin无xml文件生成是由于gtest框架升级引入。

Close: #I6J7QK

Signed-off-by: zhangdengyu <zhangdengyu2@huawei.com>
Change-Id: Ifa977658bfc47ba85484e06465735cdffef3dbe2
2023-03-03 13:52:19 +08:00
openharmony_ci
a104497e08 !1127 feature: 内核libc升级
Merge pull request !1127 from Zhaotianyu/20230224libc_update
2023-02-28 11:34:24 +00:00
arvinzzz
b5ae9e25c6 feature: fix liteos_a_newlib_kernel compiler error & libc update
Signed-off-by: arvinzzz <zhaotianyu9@huawei.com>
Change-Id: I4a8c2cfb2ba044f000026f738c6da1781cb7db35
2023-02-28 11:07:14 +08:00
openharmony_ci
c2b5a5897f !1126 feat: 支持网络容器
Merge pull request !1126 from zhushengle/net_container
2023-02-28 03:02:24 +00:00
zhangdengyu
f924cc775b fix:修复内核调用栈解析脚本bug
方案描述:
1、修复内核调用栈解析脚本parse_mem_info.sh的bug,将多余符号(`)去除

BREAKING CHANGE:
无

Close:#I6I6BA

Signed-off-by: zhangdengyu <zhangdengyu2@huawei.com>
Change-Id: I0b0d7e5f6e79313e5f517f89395f4195883cfe06
2023-02-27 19:01:03 +08:00
zhushengle
5dc9a0f1a6 feat: 支持网络容器
BREAKING CHANGE:
支持网络容器对外变更:
1.支持网络容器
2.setns, clone, unshare接口支持CLONE_NEWNET

Close #I6HPH2

Signed-off-by: zhushengle <zhushengle@huawei.com>
Change-Id: Ibaa11056982d465d4006680c8d3fa4ae2b9f25b5
2023-02-25 12:30:09 +08:00
openharmony_ci
806bd80841 !1125 支持容器限额
Merge pull request !1125 from zhushengle/container_limit
2023-02-24 01:09:47 +00:00
zhushengle
c141a92544 feat 支持容器限额
BREAKING CHANGE:
支持容器限额对外变更:
1.在proc目录下增加sys/user目录,支持max_容器_container 配额文件

Close #I6HDQK

Signed-off-by: zhushengle <zhushengle@huawei.com>
Change-Id: Ieaac046182f679a6f49cbdc74593ab39fcb31f5f
2023-02-23 22:16:18 +08:00
openharmony_ci
10c5e2e666 !1124 限制对资源控制器的删除以及添加资源控制器测试用例
Merge pull request !1124 from zhushengle/cgroups_test
2023-02-23 09:02:50 +00:00
zhushengle
da9ce464dd feat: 添加cgroups测试用例
Close #I6H2AR

Signed-off-by: zhushengle <zhushengle@huawei.com>
Change-Id: I31a432b69ea5fbad137aa1bb947fff4b6fc307df
2023-02-23 16:16:31 +08:00
openharmony_ci
f0a435dce1 !1123 支持资源限额控制器
Merge pull request !1123 from zhushengle/cgroups_2
2023-02-23 03:50:44 +00:00
zhushengle
b45cdbda3e feat: 支持cgroups
BREAKING CHANGE:
支持cgroups对外变更:
1.在proc目录下支持plimits目录,支持ipc, pid, memory, devices, sched控制器

Close #I6GVPL

Signed-off-by: zhushengle <zhushengle@huawei.com>
Change-Id: Ib996e07bf148abce9e40290d6188b763b52e89bb
2023-02-23 09:32:17 +08:00
164 changed files with 12262 additions and 517 deletions

View File

@@ -251,7 +251,13 @@ config("container_config") {
"-DLOSCFG_IPC_CONTAINER",
"-DLOSCFG_TIME_CONTAINER",
"-DLOSCFG_USER_CONTAINER",
"-DLOSCFG_NET_CONTAINER",
"-DLOSCFG_PROC_PROCESS_DIR",
"-DLOSCFG_KERNEL_PLIMITS",
"-DLOSCFG_KERNEL_MEM_PLIMIT",
"-DLOSCFG_KERNEL_IPC_PLIMIT",
"-DLOSCFG_KERNEL_DEV_PLIMIT",
"-DLOSCFG_KERNEL_SCHED_PLIMIT",
]
}
}

View File

@@ -113,7 +113,9 @@ STATIC INLINE struct mqarray *GetMqueueCBByName(const CHAR *name)
STATIC INT32 DoMqueueDelete(struct mqarray *mqueueCB)
{
UINT32 ret;
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
OsIPCLimitMqFree();
#endif
if (mqueueCB->mq_name != NULL) {
LOS_MemFree(OS_SYS_MEM_ADDR, mqueueCB->mq_name);
mqueueCB->mq_name = NULL;
@@ -163,11 +165,29 @@ STATIC int SaveMqueueName(const CHAR *mqName, struct mqarray *mqueueCB)
return LOS_OK;
}
STATIC VOID MqueueCBInit(struct mqarray *mqueueCB, const struct mq_attr *attr, INT32 openFlag, UINT32 mode)
{
mqueueCB->unlinkflag = FALSE;
mqueueCB->unlink_ref = 0;
mqueueCB->mq_personal->mq_status = MQ_USE_MAGIC;
mqueueCB->mq_personal->mq_next = NULL;
mqueueCB->mq_personal->mq_posixdes = mqueueCB;
mqueueCB->mq_personal->mq_flags = (INT32)((UINT32)openFlag | ((UINT32)attr->mq_flags & (UINT32)FNONBLOCK));
mqueueCB->mq_personal->mq_mode = mode;
mqueueCB->mq_personal->mq_refcount = 0;
mqueueCB->mq_notify.pid = 0;
}
STATIC struct mqpersonal *DoMqueueCreate(const struct mq_attr *attr, const CHAR *mqName, INT32 openFlag, UINT32 mode)
{
struct mqarray *mqueueCB = NULL;
UINT32 mqueueID;
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
if (OsIPCLimitMqAlloc() != LOS_OK) {
return (struct mqpersonal *)-1;
}
#endif
UINT32 err = LOS_QueueCreate(NULL, attr->mq_maxmsg, &mqueueID, 0, attr->mq_msgsize);
if (map_errno(err) != ENOERR) {
goto ERROUT;
@@ -201,15 +221,7 @@ STATIC struct mqpersonal *DoMqueueCreate(const struct mq_attr *attr, const CHAR
goto ERROUT;
}
mqueueCB->unlinkflag = FALSE;
mqueueCB->unlink_ref = 0;
mqueueCB->mq_personal->mq_status = MQ_USE_MAGIC;
mqueueCB->mq_personal->mq_next = NULL;
mqueueCB->mq_personal->mq_posixdes = mqueueCB;
mqueueCB->mq_personal->mq_flags = (INT32)((UINT32)openFlag | ((UINT32)attr->mq_flags & (UINT32)FNONBLOCK));
mqueueCB->mq_personal->mq_mode = mode;
mqueueCB->mq_personal->mq_refcount = 0;
mqueueCB->mq_notify.pid = 0;
MqueueCBInit(mqueueCB, attr, openFlag, mode);
return mqueueCB->mq_personal;
ERROUT:
@@ -218,6 +230,9 @@ ERROUT:
LOS_MemFree(OS_SYS_MEM_ADDR, mqueueCB->mq_name);
mqueueCB->mq_name = NULL;
}
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
OsIPCLimitMqFree();
#endif
return (struct mqpersonal *)-1;
}

View File

@@ -38,10 +38,12 @@ kernel_module(module_name) {
"os_adapt/fs_cache_proc.c",
"os_adapt/mem_info.c",
"os_adapt/mounts_proc.c",
"os_adapt/plimits_proc.c",
"os_adapt/power_proc.c",
"os_adapt/proc_init.c",
"os_adapt/proc_vfs.c",
"os_adapt/process_proc.c",
"os_adapt/sys_user.c",
"os_adapt/uptime_proc.c",
"os_adapt/vmm_proc.c",
"src/proc_file.c",

View File

@@ -55,6 +55,16 @@ void ProcSysMemInfoInit(void);
void ProcFileSysInit(void);
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
void ProcLimitsInit(void);
#endif
void ProcEntryClearVnode(struct ProcDirEntry *entry);
void ProcDetachNode(struct ProcDirEntry *pn);
void RemoveProcEntryTravalsal(struct ProcDirEntry *pn);
void ProcPmInit(void);
void ProcVmmInit(void);
@@ -79,6 +89,7 @@ void ProcFdInit(void);
#ifdef LOSCFG_KERNEL_CONTAINER
void *ProcfsContainerGet(int fd, unsigned int *containerType);
void ProcSysUserInit(void);
#endif
#ifdef __cplusplus

View File

@@ -93,6 +93,15 @@ struct ProcFileOperations {
ssize_t (*readLink)(struct ProcDirEntry *pde, char *buf, size_t bufLen);
};
#ifdef LOSCFG_KERNEL_PLIMITS
struct ProcDirOperations {
int (*rmdir)(struct ProcDirEntry *parent, struct ProcDirEntry *pde, const char *name);
int (*mkdir)(struct ProcDirEntry *parent, const char *dirName, mode_t mode, struct ProcDirEntry **pde);
};
#endif
#define PROC_DATA_STATIC 0
#define PROC_DATA_FREE 1
struct ProcDirEntry {
uint uid;
uint gid;
@@ -101,6 +110,10 @@ struct ProcDirEntry {
const struct ProcFileOperations *procFileOps;
struct ProcFile *pf;
struct ProcDirEntry *next, *parent, *subdir;
#ifdef LOSCFG_KERNEL_PLIMITS
const struct ProcDirOperations *procDirOps;
#endif
int dataType;
void *data;
atomic_t count; /* open file count */
spinlock_t pdeUnloadLock;
@@ -111,6 +124,11 @@ struct ProcDirEntry {
enum VnodeType type;
};
struct ProcDataParm {
void *data;
int dataType;
};
struct ProcFile {
fmode_t fMode;
spinlock_t fLock;
@@ -274,7 +292,7 @@ extern struct ProcDirEntry *ProcCreate(const char *name, mode_t mode,
*
*/
extern struct ProcDirEntry *ProcCreateData(const char *name, mode_t mode, struct ProcDirEntry *parent,
const struct ProcFileOperations *procFileOps, void *data);
const struct ProcFileOperations *procFileOps, struct ProcDataParm *param);
/**
* @ingroup procfs
* @brief init proc fs

View File

@@ -0,0 +1,905 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <sys/statfs.h>
#include <stdio.h>
#include <unistd.h>
#include "stdlib.h"
#include "los_printf.h"
#include "los_base.h"
#include "los_seq_buf.h"
#include "internal.h"
#include "proc_fs.h"
#include "los_task_pri.h"
#include "los_process_pri.h"
#include "los_process.h"
#include "show.h"
#include "vnode.h"
#include "proc_file.h"
#include "user_copy.h"
#ifdef LOSCFG_KERNEL_PLIMITS
#include "los_plimits.h"
#define PLIMITS_ENTRY_NAME_MAX 64
#define PLIMITERSET_DELETE_ALLOC 4
#define UNITPTR_NULL ((uintptr_t)(0xFFFFFFFF))
#define PLIMIT_FILE_MODE_READ_WRITE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#define PLIMIT_FILE_MODE_READ_ONLY (S_IRUSR | S_IRGRP | S_IROTH)
#define PLIMIT_FILE_MODE_WRITE_ONLY (S_IWUSR)
#define PLIMIT_FILE_MODE_MASK_WRITE (~((mode_t)(S_IWUSR)))
#define PLIMIT_FILE_MODE_MASK_NONE (~((mode_t)(0)))
#define LOS_MAX_CACHE (UINT64)(0xFFFFFFFFFFFFFFFF)
#define PLIMIT_CAT_BUF_SIZE 512
#define MAX_PROTECTED_PROCESS_ID 14
#define UNITPTR_NULL ((uintptr_t)(0xFFFFFFFF))
static int ShowPids(struct SeqBuf *seqBuf, VOID *data);
static ssize_t PidMigrateFromProcLimiterSet(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t PidLimitReadPidLimit(struct SeqBuf *seqBuf, VOID *data);
static ssize_t PidLimitReadPriorityLimit(struct SeqBuf *seqBuf, VOID *data);
static ssize_t PriorityLimitVariableWrite(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t PidsMaxVariableWrite(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t ProcLimitsShowLimiters(struct SeqBuf *seqBuf, VOID *data);
static int ProcfsPlimitsMkdir(struct ProcDirEntry *parent, const char *dirName, mode_t mode, struct ProcDirEntry **pde);
static int ProcfsPlimitsRmdir(struct ProcDirEntry *parent, struct ProcDirEntry *pde, const char *name);
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
static ssize_t MemLimitReadLimit(struct SeqBuf *seqBuf, VOID *data);
static ssize_t MemLimitWriteLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t MemLimitStatShow(struct SeqBuf *seqBuf, VOID *data);
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
static ssize_t IPCLimitReadMqLimit(struct SeqBuf *seqBuf, VOID *data);
static ssize_t IPCLimitWriteMqLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t IPCLimitReadShmLimit(struct SeqBuf *seqBuf, VOID *data);
static ssize_t IPCLimitWriteShmLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t IPCLimitShowStat(struct SeqBuf *seqBuf, VOID *data);
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
static ssize_t DevLimitWriteAllow(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t DevLimitWriteDeny(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t DevLimitShow(struct SeqBuf *seqBuf, VOID *data);
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
static ssize_t SchedLimitReadPeriod(struct SeqBuf *seqBuf, VOID *data);
static ssize_t SchedLimitWritePeriod(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t SchedLimitReadQuota(struct SeqBuf *seqBuf, VOID *data);
static ssize_t SchedLimitWriteQuota(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos);
static ssize_t SchedLimitShow(struct SeqBuf *seqBuf, VOID *data);
#endif
struct PLimitsEntryOpt {
int id;
char name[PLIMITS_ENTRY_NAME_MAX];
mode_t mode;
uintptr_t offset;
struct ProcFileOperations ops;
};
static struct ProcDirOperations g_procDirOperations = {
.mkdir = ProcfsPlimitsMkdir,
.rmdir = ProcfsPlimitsRmdir,
};
static struct PLimitsEntryOpt g_plimitsEntryOpts[] = {
{
.id = PROCESS_LIMITER_COUNT,
.name = "plimits.limiters",
.mode = PLIMIT_FILE_MODE_READ_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.read = ProcLimitsShowLimiters,
}
},
{
.id = PROCESS_LIMITER_COUNT,
.name = "plimits.procs",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = UNITPTR_NULL,
.ops = {
.read = ShowPids,
.write = PidMigrateFromProcLimiterSet,
},
},
{
.id = PROCESS_LIMITER_ID_PIDS,
.name = "pids.max",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = PidLimitReadPidLimit,
.write = PidsMaxVariableWrite,
},
},
{
.id = PROCESS_LIMITER_ID_PIDS,
.name = "pids.priority",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = PidLimitReadPriorityLimit,
.write = PriorityLimitVariableWrite,
},
},
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
{
.id = PROCESS_LIMITER_ID_MEM,
.name = "memory.limit",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = MemLimitReadLimit,
.write = MemLimitWriteLimit,
},
},
{
.id = PROCESS_LIMITER_ID_MEM,
.name = "memory.stat",
.mode = PLIMIT_FILE_MODE_READ_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.read = MemLimitStatShow,
}
},
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
{
.id = PROCESS_LIMITER_ID_IPC,
.name = "ipc.mq_limit",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = IPCLimitReadMqLimit,
.write = IPCLimitWriteMqLimit,
}
},
{
.id = PROCESS_LIMITER_ID_IPC,
.name = "ipc.shm_limit",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = IPCLimitReadShmLimit,
.write = IPCLimitWriteShmLimit,
}
},
{
.id = PROCESS_LIMITER_ID_IPC,
.name = "ipc.stat",
.mode = PLIMIT_FILE_MODE_READ_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.read = IPCLimitShowStat,
}
},
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
{
.id = PROCESS_LIMITER_ID_DEV,
.name = "devices.allow",
.mode = PLIMIT_FILE_MODE_WRITE_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.write = DevLimitWriteAllow,
}
},
{
.id = PROCESS_LIMITER_ID_DEV,
.name = "devices.deny",
.mode = PLIMIT_FILE_MODE_WRITE_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.write = DevLimitWriteDeny,
}
},
{
.id = PROCESS_LIMITER_ID_DEV,
.name = "devices.list",
.mode = PLIMIT_FILE_MODE_READ_ONLY,
.offset = 0,
.ops = {
.read = DevLimitShow,
}
},
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
{
.id = PROCESS_LIMITER_ID_SCHED,
.name = "sched.period",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = SchedLimitReadPeriod,
.write = SchedLimitWritePeriod,
},
},
{
.id = PROCESS_LIMITER_ID_SCHED,
.name = "sched.quota",
.mode = PLIMIT_FILE_MODE_READ_WRITE,
.offset = 0,
.ops = {
.read = SchedLimitReadQuota,
.write = SchedLimitWriteQuota,
},
},
{
.id = PROCESS_LIMITER_ID_SCHED,
.name = "sched.stat",
.mode = PLIMIT_FILE_MODE_READ_ONLY,
.offset = UNITPTR_NULL,
.ops = {
.read = SchedLimitShow,
}
},
#endif
};
static unsigned int MemUserCopy(const char *src, size_t len, char **kbuf)
{
if (LOS_IsUserAddressRange((VADDR_T)(UINTPTR)src, len)) {
char *kernelBuf = LOS_MemAlloc(m_aucSysMem1, len + 1);
if (kernelBuf == NULL) {
return ENOMEM;
}
if (LOS_ArchCopyFromUser(kernelBuf, src, len) != 0) {
(VOID)LOS_MemFree(m_aucSysMem1, kernelBuf);
return EFAULT;
}
kernelBuf[len] = '\0';
*kbuf = kernelBuf;
return 0;
}
return 0;
}
static inline struct ProcDirEntry *GetCurrDirectory(struct ProcDirEntry *dirEntry)
{
return ((dirEntry == NULL) || S_ISDIR(dirEntry->mode)) ? dirEntry : dirEntry->parent;
}
static inline ProcLimiterSet *GetProcLimiterSetFromDirEntry(struct ProcDirEntry *dirEntry)
{
struct ProcDirEntry *currDirectory = GetCurrDirectory(dirEntry);
return (currDirectory == NULL) || (currDirectory->data == NULL) ? NULL : (ProcLimiterSet *)currDirectory->data;
}
static struct ProcDirEntry *ProcCreateLimiterFiles(struct ProcDirEntry *parentEntry,
struct PLimitsEntryOpt *entryOpt,
mode_t mode, void *data)
{
struct ProcDataParm dataParm = {
.data = data,
.dataType = PROC_DATA_STATIC,
};
struct ProcDirEntry *plimitFile = ProcCreateData(entryOpt->name, entryOpt->mode & mode, parentEntry,
&entryOpt->ops, &dataParm);
if (plimitFile == NULL) {
return NULL;
}
return plimitFile;
}
static void ProcLimiterDirEntryInit(struct ProcDirEntry *dirEntry, unsigned mask, mode_t mode)
{
struct ProcDirEntry *currDir = GetCurrDirectory(dirEntry);
if (currDir == NULL) {
return;
}
ProcLimiterSet *plimiterData = (ProcLimiterSet *)currDir->data;
if (plimiterData == NULL) {
return;
}
for (int index = 0; index < (sizeof(g_plimitsEntryOpts) / sizeof(struct PLimitsEntryOpt)); index++) {
struct PLimitsEntryOpt *entryOpt = &g_plimitsEntryOpts[index];
enum ProcLimiterID plimiterType = entryOpt->id;
if (!(BIT(plimiterType) & mask)) {
continue;
}
void *head = (entryOpt->offset == UNITPTR_NULL) ?
plimiterData : (void *)plimiterData->limitsList[plimiterType];
struct ProcDirEntry *entry = ProcCreateLimiterFiles(currDir, entryOpt, mode, head);
if (entry == NULL) {
RemoveProcEntry(currDir->name, NULL);
return;
}
}
return;
}
static ssize_t PLimitsCopyLimits(struct ProcDirEntry *dirEntry)
{
struct ProcDirEntry *parentPde = dirEntry->parent;
ProcLimiterSet *parentPLimits = (ProcLimiterSet *)parentPde->data;
if (parentPLimits == NULL) {
return -EINVAL;
}
ProcLimiterSet *newPLimits = OsPLimitsCreate(parentPLimits);
if (newPLimits == NULL) {
return -ENOMEM;
}
dirEntry->data = (VOID *)newPLimits;
dirEntry->dataType = PROC_DATA_STATIC;
dirEntry->procDirOps = parentPde->procDirOps;
ProcLimiterDirEntryInit(dirEntry, newPLimits->mask, PLIMIT_FILE_MODE_MASK_NONE);
return 0;
}
static int ProcfsPlimitsMkdir(struct ProcDirEntry *parent, const char *dirName, mode_t mode, struct ProcDirEntry **pde)
{
int ret;
if (strcmp(parent->name, "plimits") != 0) {
return -EPERM;
}
struct ProcDirEntry *plimitDir = ProcCreateData(dirName, S_IFDIR | mode, parent, NULL, NULL);
if (plimitDir == NULL) {
return -EINVAL;
}
ret = PLimitsCopyLimits(plimitDir);
if (ret != LOS_OK) {
ProcFreeEntry(plimitDir);
return -ENOSYS;
}
*pde = plimitDir;
return ret;
}
static int ProcfsPlimitsRmdir(struct ProcDirEntry *parent, struct ProcDirEntry *pde, const char *name)
{
if (pde == NULL) {
return -EINVAL;
}
ProcLimiterSet *plimits = GetProcLimiterSetFromDirEntry(pde);
pde->data = NULL;
unsigned ret = OsPLimitsFree(plimits);
if (ret != 0) {
pde->data = plimits;
return -ret;
}
spin_lock(&procfsLock);
ProcDetachNode(pde);
spin_unlock(&procfsLock);
RemoveProcEntryTravalsal(pde->subdir);
ProcFreeEntry(pde);
return 0;
}
static ssize_t ProcLimitsShowLimiters(struct SeqBuf *seqBuf, VOID *data)
{
ProcLimiterSet *plimits = (ProcLimiterSet *)data;
UINT32 mask;
if (plimits == NULL) {
return -LOS_NOK;
}
mask = plimits->mask;
if (mask & BIT(PROCESS_LIMITER_ID_PIDS)) {
LosBufPrintf(seqBuf, "%s ", "pids");
}
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
if (mask & BIT(PROCESS_LIMITER_ID_MEM)) {
LosBufPrintf(seqBuf, "%s ", "memory");
}
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
if (mask & BIT(PROCESS_LIMITER_ID_IPC)) {
LosBufPrintf(seqBuf, "%s ", "ipc");
}
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
if (mask & BIT(PROCESS_LIMITER_ID_DEV)) {
LosBufPrintf(seqBuf, "%s ", "devices");
}
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
if (mask & BIT(PROCESS_LIMITER_ID_SCHED)) {
LosBufPrintf(seqBuf, "%s ", "sched");
}
#endif
return LOS_OK;
}
#define PLIMITS_PID_STR_LENGTH 4
static int ShowPids(struct SeqBuf *seqBuf, VOID *data)
{
unsigned int size, pidMax;
if (data == NULL) {
return -EINVAL;
}
const ProcLimiterSet *plimits = (const ProcLimiterSet *)data;
pidMax = LOS_GetSystemProcessMaximum();
size = pidMax * sizeof(unsigned int);
unsigned int *pids = (unsigned int *)LOS_MemAlloc(m_aucSysMem1, size);
if (pids == NULL) {
return -ENOMEM;
}
(void)memset_s(pids, size, 0, size);
unsigned int ret = OsPLimitsPidsGet(plimits, pids, size);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, pids);
return -ret;
}
(void)LosBufPrintf(seqBuf, "\n");
for (unsigned int index = 0; index < pidMax; index++) {
if (pids[index] == 0) {
continue;
}
(void)LosBufPrintf(seqBuf, "%u ", index);
}
(void)LOS_MemFree(m_aucSysMem1, pids);
return 0;
}
static long long int GetPidLimitValue(struct ProcFile *pf, const CHAR *buf, size_t count)
{
long long int value;
char *kbuf = NULL;
if ((pf == NULL) || (pf->pPDE == NULL) || (buf == NULL) || (count <= 0)) {
return -EINVAL;
}
unsigned ret = MemUserCopy(buf, count, &kbuf);
if (ret != 0) {
return -ret;
} else if ((ret == 0) && (kbuf != NULL)) {
buf = (const char *)kbuf;
}
if (strspn(buf, "0123456789") != count) {
(void)LOS_MemFree(m_aucSysMem1, kbuf);
return -EINVAL;
}
value = strtoll(buf, NULL, 10); /* 10: decimal */
(void)LOS_MemFree(m_aucSysMem1, kbuf);
return value;
}
static ssize_t PidMigrateFromProcLimiterSet(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(VOID)ppos;
unsigned ret;
long long int pid = GetPidLimitValue(pf, buf, count);
if (pid < 0) {
return pid;
}
ProcLimiterSet *plimits = GetCurrDirectory(pf->pPDE)->data;
ret = OsPLimitsAddPid(plimits, (unsigned int)pid);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t PidLimitReadPidLimit(struct SeqBuf *seqBuf, VOID *data)
{
PidLimit *pidLimit = (PidLimit *)data;
if ((seqBuf == NULL) || (pidLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%u\n", pidLimit->pidLimit);
return 0;
}
static ssize_t PidLimitReadPriorityLimit(struct SeqBuf *seqBuf, VOID *data)
{
PidLimit *pidLimit = (PidLimit *)data;
if ((seqBuf == NULL) || (pidLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%u\n", pidLimit->priorityLimit);
return 0;
}
static ssize_t PriorityLimitVariableWrite(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if (value < 0) {
return value;
}
PidLimit *pidLimit = (PidLimit *)pf->pPDE->data;
unsigned ret = PidLimitSetPriorityLimit(pidLimit, (unsigned)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t PidsMaxVariableWrite(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if (value < 0) {
return value;
}
PidLimit *pidLimit = (PidLimit *)pf->pPDE->data;
unsigned ret = PidLimitSetPidLimit(pidLimit, (unsigned)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
static ssize_t MemLimitReadLimit(struct SeqBuf *seqBuf, VOID *data)
{
ProcMemLimiter *memLimit = (ProcMemLimiter *)data;
if ((seqBuf == NULL) || (memLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%llu\n", memLimit->limit);
return 0;
}
static ssize_t MemLimitWriteLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if ((value < 0) || (value > (long long int)OS_NULL_INT)) {
return value;
}
ProcMemLimiter *memLimit = (ProcMemLimiter *)pf->pPDE->data;
unsigned ret = OsMemLimitSetMemLimit(memLimit, (unsigned long long)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t MemLimitStatShow(struct SeqBuf *seqBuf, VOID *data)
{
ProcLimiterSet *plimits = (ProcLimiterSet *)data;
if ((seqBuf == NULL) || (plimits == NULL)) {
return -EINVAL;
}
UINT32 pidMax = LOS_GetSystemProcessMaximum();
UINT32 size = sizeof(ProcMemLimiter) + pidMax * sizeof(unsigned long long);
unsigned long long *usage = (unsigned long long *)LOS_MemAlloc(m_aucSysMem1, size);
if (usage == NULL) {
return -ENOMEM;
}
(void)memset_s(usage, size, 0, size);
unsigned int ret = OsPLimitsMemUsageGet(plimits, usage, size);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, usage);
return -ret;
}
ProcMemLimiter *memLimit = (ProcMemLimiter *)usage;
unsigned long long *memUsage = (unsigned long long *)((uintptr_t)usage + sizeof(ProcMemLimiter));
(void)LosBufPrintf(seqBuf, "\nMem used: %llu\n", memLimit->usage);
(void)LosBufPrintf(seqBuf, "Mem peak: %llu\n", memLimit->peak);
(void)LosBufPrintf(seqBuf, "Mem failed count: %u\n", memLimit->failcnt);
for (unsigned int index = 0; index < pidMax; index++) {
if (memUsage[index] == 0) {
continue;
}
(void)LosBufPrintf(seqBuf, "PID: %u mem used: %llu \n", index, memUsage[index]);
}
(void)LOS_MemFree(m_aucSysMem1, usage);
return 0;
}
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
static ssize_t IPCLimitReadMqLimit(struct SeqBuf *seqBuf, VOID *data)
{
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)data;
if ((seqBuf == NULL) || (ipcLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%u\n", ipcLimit->mqCountLimit);
return 0;
}
static ssize_t IPCLimitWriteMqLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if (value < 0) {
return value;
}
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)pf->pPDE->data;
unsigned ret = OsIPCLimitSetMqLimit(ipcLimit, (unsigned long long)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t IPCLimitReadShmLimit(struct SeqBuf *seqBuf, VOID *data)
{
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)data;
if ((seqBuf == NULL) || (ipcLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%u\n", ipcLimit->shmSizeLimit);
return 0;
}
static ssize_t IPCLimitWriteShmLimit(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if ((value < 0) || (value > (long long int)OS_NULL_INT)) {
return value;
}
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)pf->pPDE->data;
unsigned ret = OsIPCLimitSetShmLimit(ipcLimit, (unsigned long long)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t IPCLimitShowStat(struct SeqBuf *seqBuf, VOID *data)
{
ProcLimiterSet *plimits = (ProcLimiterSet *)data;
if ((seqBuf == NULL) || (plimits == NULL)) {
return -EINVAL;
}
unsigned int size = sizeof(ProcIPCLimit);
ProcIPCLimit *newIPCLimit = (ProcIPCLimit *)LOS_MemAlloc(m_aucSysMem1, size);
if (newIPCLimit == NULL) {
return -ENOMEM;
}
(void)memset_s(newIPCLimit, size, 0, size);
unsigned int ret = OsPLimitsIPCStatGet(plimits, newIPCLimit, size);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, newIPCLimit);
return -ret;
}
(void)LosBufPrintf(seqBuf, "mq count: %u\n", newIPCLimit->mqCount);
(void)LosBufPrintf(seqBuf, "mq failed count: %u\n", newIPCLimit->mqFailedCount);
(void)LosBufPrintf(seqBuf, "shm size: %u\n", newIPCLimit->shmSize);
(void)LosBufPrintf(seqBuf, "shm failed count: %u\n", newIPCLimit->shmFailedCount);
(void)LOS_MemFree(m_aucSysMem1, newIPCLimit);
return 0;
}
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
static ssize_t DevLimitWriteAllow(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
char *kbuf = NULL;
if ((pf == NULL) || (pf->pPDE == NULL) || (buf == NULL) || (count <= 0)) {
return -EINVAL;
}
unsigned ret = MemUserCopy(buf, count, &kbuf);
if (ret != 0) {
return -ret;
} else if ((ret == 0) && (kbuf != NULL)) {
buf = (const char *)kbuf;
}
ProcLimiterSet *plimit = (ProcLimiterSet *)pf->pPDE->data;
ret = OsDevLimitWriteAllow(plimit, buf, count);
(VOID)LOS_MemFree(m_aucSysMem1, kbuf);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t DevLimitWriteDeny(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
char *kbuf = NULL;
if ((pf == NULL) || (pf->pPDE == NULL) || (buf == NULL) || (count <= 0)) {
return -EINVAL;
}
unsigned ret = MemUserCopy(buf, count, &kbuf);
if (ret != 0) {
return -ret;
} else if ((ret == 0) && (kbuf != NULL)) {
buf = (const char *)kbuf;
}
ProcLimiterSet *plimit = (ProcLimiterSet *)pf->pPDE->data;
ret = OsDevLimitWriteDeny(plimit, buf, count);
(VOID)LOS_MemFree(m_aucSysMem1, kbuf);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t DevLimitShow(struct SeqBuf *seqBuf, VOID *data)
{
ProcDevLimit *devLimit = (ProcDevLimit *)data;
if ((seqBuf == NULL) || (devLimit == NULL)) {
return -EINVAL;
}
unsigned ret = OsDevLimitShow(devLimit, seqBuf);
if (ret != LOS_OK) {
return -ret;
}
return 0;
}
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
static ssize_t SchedLimitReadPeriod(struct SeqBuf *seqBuf, VOID *data)
{
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)data;
if ((seqBuf == NULL) || (schedLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%lld\n", schedLimit->period);
return 0;
}
static ssize_t SchedLimitWritePeriod(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if (value < 0) {
return value;
}
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)pf->pPDE->data;
unsigned ret = OsSchedLimitSetPeriod(schedLimit, (unsigned long long)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
static ssize_t SchedLimitReadQuota(struct SeqBuf *seqBuf, VOID *data)
{
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)data;
if ((seqBuf == NULL) || (schedLimit == NULL)) {
return -EINVAL;
}
(void)LosBufPrintf(seqBuf, "%lld\n", schedLimit->quota);
return 0;
}
static ssize_t SchedLimitWriteQuota(struct ProcFile *pf, const CHAR *buf, size_t count, loff_t *ppos)
{
(void)ppos;
long long int value = GetPidLimitValue(pf, buf, count);
if (value < 0) {
return value;
}
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)pf->pPDE->data;
unsigned ret = OsSchedLimitSetQuota(schedLimit, (unsigned long long)value);
if (ret != LOS_OK) {
return -ret;
}
return count;
}
#define TIME_CYCLE_TO_US(time) ((((UINT64)time) * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US)
#define SCHED_DEFAULT_VALUE (0x101010101010101)
static ssize_t SchedLimitShow(struct SeqBuf *seqBuf, VOID *data)
{
ProcLimiterSet *plimits = (ProcLimiterSet *)data;
if ((seqBuf == NULL) || (plimits == NULL)) {
return -EINVAL;
}
UINT32 pidMax = LOS_GetSystemProcessMaximum();
UINT32 size = pidMax * sizeof(unsigned long long);
unsigned long long *usage = (unsigned long long *)LOS_MemAlloc(m_aucSysMem1, size);
if (usage == NULL) {
return -ENOMEM;
}
(void)memset_s(usage, size, 1, size);
unsigned int ret = OsPLimitsSchedUsageGet(plimits, usage, size);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, usage);
return -ret;
}
for (unsigned int index = 0; index < pidMax; index++) {
if (usage[index] == SCHED_DEFAULT_VALUE) {
continue;
}
(void)LosBufPrintf(seqBuf, "PID: %u runTime: %llu us\n", index, TIME_CYCLE_TO_US(usage[index]));
}
(void)LOS_MemFree(m_aucSysMem1, usage);
return 0;
}
#endif
#define PROC_PLIMITS_MODE (S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
void ProcLimitsInit(void)
{
struct ProcDirEntry *parentPDE = CreateProcEntry("plimits", PROC_PLIMITS_MODE, NULL);
if (parentPDE == NULL) {
return;
}
ProcLimiterSet *plimits = OsRootPLimitsGet();
parentPDE->procDirOps = &g_procDirOperations;
parentPDE->data = (VOID *)plimits;
parentPDE->dataType = PROC_DATA_STATIC;
plimits->mask = BIT(PROCESS_LIMITER_ID_PIDS) | BIT(PROCESS_LIMITER_COUNT);
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
plimits->mask |= BIT(PROCESS_LIMITER_ID_MEM);
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
plimits->mask |= BIT(PROCESS_LIMITER_ID_IPC);
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
plimits->mask |= BIT(PROCESS_LIMITER_ID_DEV);
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
plimits->mask |= BIT(PROCESS_LIMITER_ID_SCHED);
#endif
ProcLimiterDirEntryInit(parentPDE, plimits->mask, PLIMIT_FILE_MODE_MASK_WRITE);
return;
}
#endif

View File

@@ -72,6 +72,12 @@ void ProcFsInit(void)
ProcSysMemInfoInit();
ProcFileSysInit();
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
ProcLimitsInit();
#endif
#ifdef LOSCFG_KERNEL_CONTAINER
ProcSysUserInit();
#endif
}
LOS_MODULE_INIT(ProcFsInit, LOS_INIT_LEVEL_KMOD_EXTENDED);

View File

@@ -239,6 +239,53 @@ int VfsProcfsStat(struct Vnode *node, struct stat *buf)
return LOS_OK;
}
#ifdef LOSCFG_KERNEL_PLIMITS
int VfsProcfsMkdir(struct Vnode *parent, const char *dirName, mode_t mode, struct Vnode **vnode)
{
struct ProcDirEntry *parentEntry = VnodeToEntry(parent);
struct ProcDirEntry *pde = NULL;
if ((parentEntry->procDirOps == NULL) || (parentEntry->procDirOps->mkdir == NULL)) {
return -ENOSYS;
}
int ret = parentEntry->procDirOps->mkdir(parentEntry, dirName, mode, &pde);
if ((ret < 0) || (pde == NULL)) {
return ret;
}
*vnode = EntryToVnode(pde);
(*vnode)->vop = parent->vop;
(*vnode)->parent = parent;
(*vnode)->originMount = parent->originMount;
if ((*vnode)->type == VNODE_TYPE_DIR) {
(*vnode)->mode = S_IFDIR | PROCFS_DEFAULT_MODE;
} else {
(*vnode)->mode = S_IFREG | PROCFS_DEFAULT_MODE;
}
return ret;
}
int VfsProcfsRmdir(struct Vnode *parent, struct Vnode *vnode, const char *dirName)
{
if (parent == NULL) {
return -EINVAL;
}
struct ProcDirEntry *parentEntry = VnodeToEntry(parent);
if ((parentEntry->procDirOps == NULL) || (parentEntry->procDirOps->rmdir == NULL)) {
return -ENOSYS;
}
struct ProcDirEntry *dirEntry = VnodeToEntry(vnode);
int ret = parentEntry->procDirOps->rmdir(parentEntry, dirEntry, dirName);
if (ret < 0) {
return ret;
}
vnode->data = NULL;
return 0;
}
#endif
int VfsProcfsReaddir(struct Vnode *node, struct fs_dirent_s *dir)
{
int result;
@@ -350,7 +397,7 @@ int VfsProcfsClose(struct file *filep)
VnodeHold();
struct Vnode *node = filep->f_vnode;
struct ProcDirEntry *pde = VnodeToEntry(node);
if (pde == NULL) {
if ((pde == NULL) || (pde->pf == NULL)) {
VnodeDrop();
return -EPERM;
}
@@ -410,6 +457,10 @@ static struct VnodeOps g_procfsVops = {
.Closedir = VfsProcfsClosedir,
.Truncate = VfsProcfsTruncate,
.Readlink = VfsProcfsReadlink,
#ifdef LOSCFG_KERNEL_PLIMITS
.Mkdir = VfsProcfsMkdir,
.Rmdir = VfsProcfsRmdir,
#endif
};
static struct file_operations_vfs g_procfsFops = {

View File

@@ -91,6 +91,8 @@ static ssize_t ProcessContainerLink(unsigned int containerID, ContainerType type
count = snprintf_s(buffer, bufLen, bufLen - 1, "'time:[%u]'", containerID);
} else if (type == USER_CONTAINER) {
count = snprintf_s(buffer, bufLen, bufLen - 1, "'user:[%u]'", containerID);
} else if (type == NET_CONTAINER) {
count = snprintf_s(buffer, bufLen, bufLen - 1, "'net:[%u]'", containerID);
}
if (count < 0) {
@@ -574,6 +576,14 @@ static struct ProcProcess g_procProcess[] = {
.fileOps = &UID_GID_MAP_FOPS
},
#endif
#ifdef LOSCFG_IPC_CONTAINER
{
.name = "container/net",
.mode = S_IFLNK,
.type = NET_CONTAINER,
.fileOps = &PID_CONTAINER_FOPS
},
#endif
#endif
};
@@ -588,6 +598,7 @@ void ProcFreeProcessDir(struct ProcDirEntry *processDir)
static struct ProcDirEntry *ProcCreatePorcess(UINT32 pid, struct ProcProcess *porcess, uintptr_t processCB)
{
int ret;
struct ProcDataParm dataParm;
char pidName[PROC_PID_DIR_LEN] = {0};
struct ProcessData *data = (struct ProcessData *)malloc(sizeof(struct ProcessData));
if (data == NULL) {
@@ -613,7 +624,9 @@ static struct ProcDirEntry *ProcCreatePorcess(UINT32 pid, struct ProcProcess *po
data->process = processCB;
data->type = porcess->type;
struct ProcDirEntry *container = ProcCreateData(pidName, porcess->mode, NULL, porcess->fileOps, (void *)data);
dataParm.data = data;
dataParm.dataType = PROC_DATA_FREE;
struct ProcDirEntry *container = ProcCreateData(pidName, porcess->mode, NULL, porcess->fileOps, &dataParm);
if (container == NULL) {
free(data);
PRINT_ERR("create /proc/%s error!\n", pidName);

228
fs/proc/os_adapt/sys_user.c Normal file
View File

@@ -0,0 +1,228 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <sys/statfs.h>
#include <sys/mount.h>
#include "proc_fs.h"
#include "internal.h"
#include "los_process_pri.h"
#include "user_copy.h"
#include "los_memory.h"
#ifdef LOSCFG_KERNEL_CONTAINER
struct ProcSysUser {
char *name;
mode_t mode;
int type;
const struct ProcFileOperations *fileOps;
};
static unsigned int MemUserCopy(const char *src, size_t len, char **kbuf)
{
if (LOS_IsUserAddressRange((VADDR_T)(UINTPTR)src, len)) {
char *kernelBuf = LOS_MemAlloc(m_aucSysMem1, len + 1);
if (kernelBuf == NULL) {
return ENOMEM;
}
if (LOS_ArchCopyFromUser(kernelBuf, src, len) != 0) {
(VOID)LOS_MemFree(m_aucSysMem1, kernelBuf);
return EFAULT;
}
kernelBuf[len] = '\0';
*kbuf = kernelBuf;
return 0;
}
return 0;
}
static int GetContainerLimitValue(struct ProcFile *pf, const CHAR *buf, size_t count)
{
int value;
char *kbuf = NULL;
if ((pf == NULL) || (pf->pPDE == NULL) || (buf == NULL) || (count <= 0)) {
return -EINVAL;
}
unsigned ret = MemUserCopy(buf, count, &kbuf);
if (ret != 0) {
return -ret;
} else if ((ret == 0) && (kbuf != NULL)) {
buf = (const char *)kbuf;
}
if (strspn(buf, "0123456789") != count) {
(void)LOS_MemFree(m_aucSysMem1, kbuf);
return -EINVAL;
}
value = atoi(buf);
(void)LOS_MemFree(m_aucSysMem1, kbuf);
return value;
}
static ssize_t ProcSysUserWrite(struct ProcFile *pf, const char *buf, size_t size, loff_t *ppos)
{
(void)ppos;
unsigned ret;
int value = GetContainerLimitValue(pf, buf, size);
if (value < 0) {
return -EINVAL;
}
ContainerType type = (ContainerType)(uintptr_t)pf->pPDE->data;
ret = OsSetContainerLimit(type, value);
if (ret != LOS_OK) {
return -EINVAL;
}
return size;
}
static int ProcSysUserRead(struct SeqBuf *seqBuf, void *v)
{
unsigned ret;
if ((seqBuf == NULL) || (v == NULL)) {
return EINVAL;
}
ContainerType type = (ContainerType)(uintptr_t)v;
ret = OsGetContainerLimit(type);
if (ret == OS_INVALID_VALUE) {
return EINVAL;
}
(void)LosBufPrintf(seqBuf, "\nlimit: %u\n", ret);
(void)LosBufPrintf(seqBuf, "count: %u\n", OsGetContainerCount(type));
return 0;
}
static const struct ProcFileOperations SYS_USER_OPT = {
.read = ProcSysUserRead,
.write = ProcSysUserWrite,
};
static struct ProcSysUser g_sysUser[] = {
#ifdef LOSCFG_MNT_CONTAINER
{
.name = "max_mnt_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = MNT_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_PID_CONTAINER
{
.name = "max_pid_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = PID_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_USER_CONTAINER
{
.name = "max_user_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = USER_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_UTS_CONTAINER
{
.name = "max_uts_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = UTS_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_UTS_CONTAINER
{
.name = "max_time_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = UTS_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_IPC_CONTAINER
{
.name = "max_ipc_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = IPC_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
#ifdef LOSCFG_NET_CONTAINER
{
.name = "max_net_container",
.mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
.type = NET_CONTAINER,
.fileOps = &SYS_USER_OPT
},
#endif
};
static int ProcCreateSysUser(struct ProcDirEntry *parent)
{
struct ProcDataParm parm;
for (int index = 0; index < (sizeof(g_sysUser) / sizeof(struct ProcSysUser)); index++) {
struct ProcSysUser *sysUser = &g_sysUser[index];
parm.data = (void *)(uintptr_t)sysUser->type;
parm.dataType = PROC_DATA_STATIC;
struct ProcDirEntry *userFile = ProcCreateData(sysUser->name, sysUser->mode, parent, sysUser->fileOps, &parm);
if (userFile == NULL) {
PRINT_ERR("create /proc/%s/%s error!\n", parent->name, sysUser->name);
return -1;
}
}
return 0;
}
#define PROC_SYS_USER_MODE (S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
void ProcSysUserInit(void)
{
struct ProcDirEntry *parentPDE = CreateProcEntry("sys", PROC_SYS_USER_MODE, NULL);
if (parentPDE == NULL) {
return;
}
struct ProcDirEntry *pde = CreateProcEntry("user", PROC_SYS_USER_MODE, parentPDE);
if (pde == NULL) {
PRINT_ERR("create /proc/process error!\n");
return;
}
int ret = ProcCreateSysUser(pde);
if (ret < 0) {
PRINT_ERR("Create proc sys user failed!\n");
}
return;
}
#endif

View File

@@ -296,7 +296,7 @@ static int ProcAddNode(struct ProcDirEntry *parent, struct ProcDirEntry *pn)
return 0;
}
static void ProcDetachNode(struct ProcDirEntry *pn)
void ProcDetachNode(struct ProcDirEntry *pn)
{
struct ProcDirEntry *parent = pn->parent;
struct ProcDirEntry **iter = NULL;
@@ -379,7 +379,7 @@ struct ProcDirEntry *CreateProcEntry(const char *name, mode_t mode, struct ProcD
return pde;
}
static void ProcEntryClearVnode(struct ProcDirEntry *entry)
void ProcEntryClearVnode(struct ProcDirEntry *entry)
{
struct Vnode *item = NULL;
struct Vnode *nextItem = NULL;
@@ -404,16 +404,14 @@ static void FreeProcEntry(struct ProcDirEntry *entry)
return;
}
ProcEntryClearVnode(entry);
if (entry->pf != NULL) {
free(entry->pf);
entry->pf = NULL;
}
if (entry->data != NULL) {
if ((entry->dataType == PROC_DATA_FREE) && (entry->data != NULL)) {
free(entry->data);
entry->data = NULL;
}
entry->data = NULL;
free(entry);
}
@@ -424,7 +422,7 @@ void ProcFreeEntry(struct ProcDirEntry *pn)
}
}
static void RemoveProcEntryTravalsal(struct ProcDirEntry *pn)
void RemoveProcEntryTravalsal(struct ProcDirEntry *pn)
{
if (pn == NULL) {
return;
@@ -432,6 +430,8 @@ static void RemoveProcEntryTravalsal(struct ProcDirEntry *pn)
RemoveProcEntryTravalsal(pn->next);
RemoveProcEntryTravalsal(pn->subdir);
ProcEntryClearVnode(pn);
ProcFreeEntry(pn);
}
@@ -461,6 +461,9 @@ void RemoveProcEntry(const char *name, struct ProcDirEntry *parent)
spin_unlock(&procfsLock);
RemoveProcEntryTravalsal(pn->subdir);
ProcEntryClearVnode(pn);
ProcFreeEntry(pn);
}
@@ -475,14 +478,17 @@ struct ProcDirEntry *ProcMkdir(const char *name, struct ProcDirEntry *parent)
}
struct ProcDirEntry *ProcCreateData(const char *name, mode_t mode, struct ProcDirEntry *parent,
const struct ProcFileOperations *procFileOps, void *data)
const struct ProcFileOperations *procFileOps, struct ProcDataParm *param)
{
struct ProcDirEntry *pde = CreateProcEntry(name, mode, parent);
if (pde != NULL) {
if (procFileOps != NULL) {
pde->procFileOps = procFileOps;
}
pde->data = data;
if (param != NULL) {
pde->data = param->data;
pde->dataType = param->dataType;
}
}
return pde;
}
@@ -644,7 +650,6 @@ int WriteProcFile(struct ProcDirEntry *pde, const void *buf, size_t len)
result = pde->procFileOps->write(pde->pf, (const char *)buf, len, &(pde->pf->fPos));
}
spin_unlock(&procfsLock);
return result;
}

View File

@@ -108,6 +108,11 @@ config USER_CONTAINER
default n
depends on KERNEL_CONTAINER
config NET_CONTAINER
bool "Enable net container"
default n
depends on KERNEL_CONTAINER
######################### config options of extended #####################
source "kernel/extended/Kconfig"

View File

@@ -36,6 +36,7 @@ kernel_module(module_name) {
"container/los_credentials.c",
"container/los_ipc_container.c",
"container/los_mnt_container.c",
"container/los_net_container.c",
"container/los_pid_container.c",
"container/los_time_container.c",
"container/los_user_container.c",

View File

@@ -27,12 +27,14 @@
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef LOSCFG_KERNEL_CONTAINER
#include "los_container_pri.h"
#include "los_process_pri.h"
#include "internal.h"
#ifdef LOSCFG_KERNEL_CONTAINER
STATIC Container g_rootContainer;
STATIC ContainerLimit g_containerLimit;
STATIC Atomic g_containerCount = 0xF0000000U;
#ifdef LOSCFG_USER_CONTAINER
STATIC Credentials *g_rootCredentials = NULL;
@@ -56,27 +58,182 @@ VOID OsContainerInitSystemProcess(LosProcessCB *processCB)
return;
}
UINT32 OsGetContainerLimit(ContainerType type)
{
switch (type) {
#ifdef LOSCFG_PID_CONTAINER
case PID_CONTAINER:
case PID_CHILD_CONTAINER:
return g_containerLimit.pidLimit;
#endif
#ifdef LOSCFG_USER_CONTAINER
case USER_CONTAINER:
return g_containerLimit.userLimit;
#endif
#ifdef LOSCFG_UTS_CONTAINER
case UTS_CONTAINER:
return g_containerLimit.utsLimit;
#endif
#ifdef LOSCFG_MNT_CONTAINER
case MNT_CONTAINER:
return g_containerLimit.mntLimit;
#endif
#ifdef LOSCFG_IPC_CONTAINER
case IPC_CONTAINER:
return g_containerLimit.ipcLimit;
#endif
#ifdef LOSCFG_TIME_CONTAINER
case TIME_CONTAINER:
case TIME_CHILD_CONTAINER:
return g_containerLimit.timeLimit;
#endif
#ifdef LOSCFG_NET_CONTAINER
case NET_CONTAINER:
return g_containerLimit.netLimit;
#endif
default:
break;
}
return OS_INVALID_VALUE;
}
UINT32 OsContainerLimitCheck(ContainerType type, UINT32 *containerCount)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
if ((*containerCount) >= OsGetContainerLimit(type)) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsSetContainerLimit(ContainerType type, UINT32 value)
{
UINT32 intSave;
if (value > LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
switch (type) {
#ifdef LOSCFG_PID_CONTAINER
case PID_CONTAINER:
case PID_CHILD_CONTAINER:
g_containerLimit.pidLimit = value;
break;
#endif
#ifdef LOSCFG_USER_CONTAINER
case USER_CONTAINER:
g_containerLimit.userLimit = value;
break;
#endif
#ifdef LOSCFG_UTS_CONTAINER
case UTS_CONTAINER:
g_containerLimit.utsLimit = value;
break;
#endif
#ifdef LOSCFG_MNT_CONTAINER
case MNT_CONTAINER:
g_containerLimit.mntLimit = value;
break;
#endif
#ifdef LOSCFG_IPC_CONTAINER
case IPC_CONTAINER:
g_containerLimit.ipcLimit = value;
break;
#endif
#ifdef LOSCFG_TIME_CONTAINER
case TIME_CONTAINER:
case TIME_CHILD_CONTAINER:
g_containerLimit.timeLimit = value;
break;
#endif
#ifdef LOSCFG_NET_CONTAINER
case NET_CONTAINER:
g_containerLimit.netLimit = value;
break;
#endif
default:
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsGetContainerCount(ContainerType type)
{
switch (type) {
#ifdef LOSCFG_PID_CONTAINER
case PID_CONTAINER:
case PID_CHILD_CONTAINER:
return OsGetPidContainerCount();
#endif
#ifdef LOSCFG_USER_CONTAINER
case USER_CONTAINER:
return OsGetUserContainerCount();
#endif
#ifdef LOSCFG_UTS_CONTAINER
case UTS_CONTAINER:
return OsGetUtsContainerCount();
#endif
#ifdef LOSCFG_MNT_CONTAINER
case MNT_CONTAINER:
return OsGetMntContainerCount();
#endif
#ifdef LOSCFG_IPC_CONTAINER
case IPC_CONTAINER:
return OsGetIpcContainerCount();
#endif
#ifdef LOSCFG_TIME_CONTAINER
case TIME_CONTAINER:
case TIME_CHILD_CONTAINER:
return OsGetTimeContainerCount();
#endif
#ifdef LOSCFG_NET_CONTAINER
case NET_CONTAINER:
return OsGetNetContainerCount();
#endif
default:
break;
}
return OS_INVALID_VALUE;
}
VOID OsInitRootContainer(VOID)
{
#ifdef LOSCFG_USER_CONTAINER
g_containerLimit.userLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
OsInitRootUserCredentials(&g_rootCredentials);
#endif
#ifdef LOSCFG_PID_CONTAINER
g_containerLimit.pidLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootPidContainer(&g_rootContainer.pidContainer);
g_rootContainer.pidForChildContainer = g_rootContainer.pidContainer;
#endif
#ifdef LOSCFG_UTS_CONTAINER
g_containerLimit.utsLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootUtsContainer(&g_rootContainer.utsContainer);
#endif
#ifdef LOSCFG_MNT_CONTAINER
g_containerLimit.mntLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootMntContainer(&g_rootContainer.mntContainer);
#endif
#ifdef LOSCFG_IPC_CONTAINER
g_containerLimit.ipcLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootIpcContainer(&g_rootContainer.ipcContainer);
#endif
#ifdef LOSCFG_TIME_CONTAINER
g_containerLimit.timeLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootTimeContainer(&g_rootContainer.timeContainer);
g_rootContainer.timeForChildContainer = g_rootContainer.timeContainer;
#endif
#ifdef LOSCFG_NET_CONTAINER
g_containerLimit.netLimit = LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT;
(VOID)OsInitRootNetContainer(&g_rootContainer.netContainer);
#endif
return;
}
@@ -133,10 +290,43 @@ STATIC UINT32 CopyContainers(UINTPTR flags, LosProcessCB *child, LosProcessCB *p
if (ret != LOS_OK) {
return ret;
}
#endif
#ifdef LOSCFG_NET_CONTAINER
ret = OsCopyNetContainer(flags, child, parent);
if (ret != LOS_OK) {
return ret;
}
#endif
return ret;
}
STATIC INLINE UINT32 GetContainerFlagsMask(VOID)
{
UINT32 mask = 0;
#ifdef LOSCFG_PID_CONTAINER
mask |= CLONE_NEWPID;
#endif
#ifdef LOSCFG_MNT_CONTAINER
mask |= CLONE_NEWNS;
#endif
#ifdef LOSCFG_IPC_CONTAINER
mask |= CLONE_NEWIPC;
#endif
#ifdef LOSCFG_USER_CONTAINER
mask |= CLONE_NEWUSER;
#endif
#ifdef LOSCFG_TIME_CONTAINER
mask |= CLONE_NEWTIME;
#endif
#ifdef LOSCFG_NET_CONTAINER
mask |= CLONE_NEWNET;
#endif
#ifdef LOSCFG_UTS_CONTAINER
mask |= CLONE_NEWUTS;
#endif
return mask;
}
/*
* called from clone. This now handles copy for Container and all
* namespaces therein.
@@ -149,7 +339,7 @@ UINT32 OsCopyContainers(UINTPTR flags, LosProcessCB *child, LosProcessCB *parent
flags &= ~CLONE_NEWTIME;
#endif
if (!(flags & (CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWTIME))) {
if (!(flags & GetContainerFlagsMask())) {
#ifdef LOSCFG_PID_CONTAINER
if (parent->container->pidContainer != parent->container->pidForChildContainer) {
goto CREATE_CONTAINER;
@@ -188,7 +378,7 @@ VOID OsContainerFree(LosProcessCB *processCB)
}
}
VOID OsContainersDestroy(LosProcessCB *processCB)
VOID OsOsContainersDestroyEarly(LosProcessCB *processCB)
{
/* All processes in the container must be destroyed before the container is destroyed. */
#ifdef LOSCFG_PID_CONTAINER
@@ -197,6 +387,13 @@ VOID OsContainersDestroy(LosProcessCB *processCB)
}
#endif
#ifdef LOSCFG_MNT_CONTAINER
OsMntContainerDestroy(processCB->container);
#endif
}
VOID OsContainersDestroy(LosProcessCB *processCB)
{
#ifdef LOSCFG_USER_CONTAINER
OsUserContainerDestroy(processCB);
#endif
@@ -205,10 +402,6 @@ VOID OsContainersDestroy(LosProcessCB *processCB)
OsUtsContainerDestroy(processCB->container);
#endif
#ifdef LOSCFG_MNT_CONTAINER
OsMntContainerDestroy(processCB->container);
#endif
#ifdef LOSCFG_IPC_CONTAINER
OsIpcContainerDestroy(processCB->container);
#endif
@@ -217,6 +410,10 @@ VOID OsContainersDestroy(LosProcessCB *processCB)
OsTimeContainerDestroy(processCB->container);
#endif
#ifdef LOSCFG_NET_CONTAINER
OsNetContainerDestroy(processCB->container);
#endif
#ifndef LOSCFG_PID_CONTAINER
UINT32 intSave;
SCHEDULER_LOCK(intSave);
@@ -256,6 +453,10 @@ STATIC VOID DeInitContainers(UINT32 flags, Container *container, LosProcessCB *p
OsTimeContainerDestroy(container);
#endif
#ifdef LOSCFG_NET_CONTAINER
OsNetContainerDestroy(container);
#endif
SCHEDULER_LOCK(intSave);
LOS_AtomicDec(&container->rc);
if (LOS_AtomicRead(&container->rc) == 0) {
@@ -299,6 +500,10 @@ UINT32 OsGetContainerID(LosProcessCB *processCB, ContainerType type)
return OsGetTimeContainerID(container->timeContainer);
case TIME_CHILD_CONTAINER:
return OsGetTimeContainerID(container->timeForChildContainer);
#endif
#ifdef LOSCFG_NET_CONTAINER
case NET_CONTAINER:
return OsGetNetContainerID(container->netContainer);
#endif
default:
break;
@@ -338,6 +543,12 @@ STATIC UINT32 UnshareCreateNewContainers(UINT32 flags, LosProcessCB *curr, Conta
if (ret != LOS_OK) {
return ret;
}
#endif
#ifdef LOSCFG_NET_CONTAINER
ret = OsUnshareNetContainer(flags, curr, newContainer);
if (ret != LOS_OK) {
return ret;
}
#endif
return ret;
}
@@ -348,8 +559,7 @@ INT32 OsUnshare(UINT32 flags)
UINT32 intSave;
LosProcessCB *curr = OsCurrProcessGet();
Container *oldContainer = curr->container;
UINT32 unshareFlags = CLONE_NEWPID | CLONE_NEWTIME | CLONE_NEWUTS | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUSER;
UINT32 unshareFlags = GetContainerFlagsMask();
if (!(flags & unshareFlags) || ((flags & (~unshareFlags)) != 0)) {
return -EINVAL;
}
@@ -408,6 +618,8 @@ STATIC UINT32 SetNsGetFlagByContainerType(UINT32 containerType)
case TIME_CONTAINER:
case TIME_CHILD_CONTAINER:
return CLONE_NEWTIME;
case NET_CONTAINER:
return CLONE_NEWNET;
default:
break;
}
@@ -446,13 +658,19 @@ STATIC UINT32 SetNsCreateNewContainers(UINT32 flags, Container *newContainer, Co
if (ret != LOS_OK) {
return ret;
}
#endif
#ifdef LOSCFG_NET_CONTAINER
ret = OsSetNsNetContainer(flags, container, newContainer);
if (ret != LOS_OK) {
return ret;
}
#endif
return LOS_OK;
}
STATIC UINT32 SetNsParamCheck(INT32 fd, INT32 type, UINT32 *flag, LosProcessCB **target)
{
UINT32 typeMask = CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWIPC | CLONE_NEWTIME | CLONE_NEWUSER;
UINT32 typeMask = GetContainerFlagsMask();
*flag = (UINT32)(type & typeMask);
UINT32 containerType = 0;

View File

@@ -121,6 +121,10 @@ UINT32 OsCopyIpcContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *pare
return LOS_OK;
}
if (OsContainerLimitCheck(IPC_CONTAINER, &g_currentIpcContainerNum) != LOS_OK) {
return EPERM;
}
return CreateIpcContainer(child, parent);
}
@@ -137,6 +141,10 @@ UINT32 OsUnshareIpcContainer(UINTPTR flags, LosProcessCB *curr, Container *newCo
return LOS_OK;
}
if (OsContainerLimitCheck(IPC_CONTAINER, &g_currentIpcContainerNum) != LOS_OK) {
return EPERM;
}
IpcContainer *ipcContainer = CreateNewIpcContainer(parentContainer);
if (ipcContainer == NULL) {
return ENOMEM;
@@ -206,4 +214,9 @@ IpcContainer *OsGetCurrIpcContainer(VOID)
{
return OsCurrProcessGet()->container->ipcContainer;
}
UINT32 OsGetIpcContainerCount(VOID)
{
return g_currentIpcContainerNum;
}
#endif

View File

@@ -28,6 +28,7 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef LOSCFG_MNT_CONTAINER
#include <unistd.h>
#include "los_mnt_container_pri.h"
#include "los_container_pri.h"
@@ -36,7 +37,6 @@
#include "vnode.h"
#include "internal.h"
#ifdef LOSCFG_MNT_CONTAINER
STATIC UINT32 g_currentMntContainerNum;
LIST_HEAD *GetContainerMntList(VOID)
@@ -124,6 +124,10 @@ UINT32 OsCopyMntContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *pare
return LOS_OK;
}
if (OsContainerLimitCheck(MNT_CONTAINER, &g_currentMntContainerNum) != LOS_OK) {
return EPERM;
}
ret = CreateMntContainer(child, parent);
if (ret != LOS_OK) {
return ret;
@@ -146,6 +150,10 @@ UINT32 OsUnshareMntContainer(UINTPTR flags, LosProcessCB *curr, Container *newCo
return LOS_OK;
}
if (OsContainerLimitCheck(MNT_CONTAINER, &g_currentMntContainerNum) != LOS_OK) {
return EPERM;
}
MntContainer *mntContainer = CreateNewMntContainer(parentContainer);
if (mntContainer == NULL) {
return ENOMEM;
@@ -237,4 +245,9 @@ UINT32 OsGetMntContainerID(MntContainer *mntContainer)
return mntContainer->containerID;
}
UINT32 OsGetMntContainerCount(VOID)
{
return g_currentMntContainerNum;
}
#endif

View File

@@ -0,0 +1,344 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_NET_CONTAINER
#include <sched.h>
#include "los_net_container_pri.h"
#include "los_config.h"
#include "los_memory.h"
#include "los_process_pri.h"
STATIC UINT32 g_currentNetContainerNum = 0;
STATIC NetContainer *g_rootNetContainer = NULL;
STATIC struct netif *NetifAlloc(VOID)
{
UINT32 size = sizeof(struct netif);
struct netif *netif = LOS_MemAlloc(m_aucSysMem1, size);
if (netif == NULL) {
return NULL;
}
(VOID)memset_s(netif, size, 0, size);
return netif;
}
STATIC VOID FreeNetif(struct netif *netif)
{
if (netif != NULL) {
if (netif->peer != NULL) {
netif_remove(netif->peer);
(VOID)LOS_MemFree(m_aucSysMem1, netif->peer);
}
netif_remove(netif);
(VOID)LOS_MemFree(m_aucSysMem1, netif);
}
}
STATIC UINT32 CreateVethNetif(NetContainer *netContainer, struct netif **veth)
{
struct netif *netif = NetifAlloc();
if (netif == NULL) {
return ENOMEM;
}
veth_init(netif, netContainer->group);
*veth = netif;
return LOS_OK;
}
STATIC UINT32 InitVethPair(NetContainer *netContainer)
{
struct netif *vethOfNetContainer = NULL;
struct netif *vethOfRootNetContainer = NULL;
UINT32 ret = CreateVethNetif(netContainer, &vethOfNetContainer);
if (ret != LOS_OK) {
return ret;
}
ret = CreateVethNetif(g_rootNetContainer, &vethOfRootNetContainer);
if (ret != LOS_OK) {
FreeNetif(vethOfNetContainer);
return ret;
}
vethOfNetContainer->peer = vethOfRootNetContainer;
vethOfRootNetContainer->peer = vethOfNetContainer;
return LOS_OK;
}
STATIC UINT32 InitLoopNetif(NetContainer *netContainer)
{
struct netif *loop_netif = NetifAlloc();
if (loop_netif == NULL) {
return ENOMEM;
}
netContainer->group->loop_netif = loop_netif;
netif_init(netContainer->group);
return LOS_OK;
}
STATIC UINT32 InitContainerNetifs(NetContainer *netContainer)
{
UINT32 ret = InitLoopNetif(netContainer);
if (ret != LOS_OK) {
return ret;
}
return InitVethPair(netContainer);
}
STATIC UINT32 InitNetGroup(NetContainer *netContainer)
{
UINT32 size = sizeof(struct net_group);
struct net_group *group = LOS_MemAlloc(m_aucSysMem1, size);
if (group == NULL) {
return ENOMEM;
}
(VOID)memset_s(group, size, 0, size);
netContainer->group = group;
return LOS_OK;
}
STATIC VOID FreeNetContainerGroup(struct net_group *group)
{
if (group == NULL) {
return;
}
struct netif *freeNetif = group->netif_list;
struct netif *nextNetif = NULL;
while (freeNetif != NULL) {
nextNetif = freeNetif->next;
FreeNetif(freeNetif);
freeNetif = nextNetif;
}
}
VOID OsNetContainerDestroy(Container *container)
{
UINT32 intSave;
if (container == NULL) {
return;
}
SCHEDULER_LOCK(intSave);
NetContainer *netContainer = container->netContainer;
if (netContainer == NULL) {
SCHEDULER_UNLOCK(intSave);
return;
}
LOS_AtomicDec(&netContainer->rc);
if (LOS_AtomicRead(&netContainer->rc) > 0) {
SCHEDULER_UNLOCK(intSave);
return;
}
g_currentNetContainerNum--;
SCHEDULER_UNLOCK(intSave);
FreeNetContainerGroup(netContainer->group);
container->netContainer = NULL;
(VOID)LOS_MemFree(m_aucSysMem1, netContainer->group);
(VOID)LOS_MemFree(m_aucSysMem1, netContainer);
return;
}
STATIC NetContainer *CreateNewNetContainer(NetContainer *parent)
{
NetContainer *netContainer = LOS_MemAlloc(m_aucSysMem1, sizeof(NetContainer));
if (netContainer == NULL) {
return NULL;
}
(VOID)memset_s(netContainer, sizeof(NetContainer), 0, sizeof(NetContainer));
netContainer->containerID = OsAllocContainerID();
if (parent != NULL) {
LOS_AtomicSet(&netContainer->rc, 1);
} else {
LOS_AtomicSet(&netContainer->rc, 3); /* 3: Three system processes */
}
return netContainer;
}
STATIC UINT32 CreateNetContainer(Container *container, NetContainer *parentContainer)
{
UINT32 intSave, ret;
NetContainer *newNetContainer = CreateNewNetContainer(parentContainer);
if (newNetContainer == NULL) {
return ENOMEM;
}
ret = InitNetGroup(newNetContainer);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, newNetContainer);
return ret;
}
ret = InitContainerNetifs(newNetContainer);
if (ret != LOS_OK) {
(VOID)LOS_MemFree(m_aucSysMem1, newNetContainer->group);
(VOID)LOS_MemFree(m_aucSysMem1, newNetContainer);
return ret;
}
SCHEDULER_LOCK(intSave);
g_currentNetContainerNum++;
container->netContainer = newNetContainer;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsCopyNetContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *parent)
{
UINT32 intSave;
NetContainer *currNetContainer = parent->container->netContainer;
if (!(flags & CLONE_NEWNET)) {
SCHEDULER_LOCK(intSave);
LOS_AtomicInc(&currNetContainer->rc);
child->container->netContainer = currNetContainer;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
if (OsContainerLimitCheck(NET_CONTAINER, &g_currentNetContainerNum) != LOS_OK) {
return EPERM;
}
return CreateNetContainer(child->container, currNetContainer);
}
UINT32 OsUnshareNetContainer(UINTPTR flags, LosProcessCB *curr, Container *newContainer)
{
UINT32 intSave;
NetContainer *parentContainer = curr->container->netContainer;
if (!(flags & CLONE_NEWNET)) {
SCHEDULER_LOCK(intSave);
newContainer->netContainer = parentContainer;
LOS_AtomicInc(&parentContainer->rc);
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
if (OsContainerLimitCheck(NET_CONTAINER, &g_currentNetContainerNum) != LOS_OK) {
return EPERM;
}
return CreateNetContainer(newContainer, parentContainer);
}
UINT32 OsSetNsNetContainer(UINT32 flags, Container *container, Container *newContainer)
{
if (flags & CLONE_NEWNET) {
newContainer->netContainer = container->netContainer;
LOS_AtomicInc(&container->netContainer->rc);
return LOS_OK;
}
newContainer->netContainer = OsCurrProcessGet()->container->netContainer;
LOS_AtomicInc(&newContainer->netContainer->rc);
return LOS_OK;
}
UINT32 OsGetNetContainerID(NetContainer *netContainer)
{
if (netContainer == NULL) {
return OS_INVALID_VALUE;
}
return netContainer->containerID;
}
STATIC struct net_group *DoGetNetGroupFromCurrProcess(VOID)
{
LosProcessCB *processCB = OsCurrProcessGet();
NetContainer *netContainer = processCB->container->netContainer;
return netContainer->group;
}
STATIC VOID DoSetNetifNetGroup(struct netif *netif, struct net_group *group)
{
netif->group = group;
}
STATIC struct net_group *DoGetNetGroupFromNetif(struct netif *netif)
{
return netif != NULL ? netif->group : NULL;
}
STATIC VOID DoSetIppcbNetGroup(struct ip_pcb *pcb, struct net_group *group)
{
pcb->group = group;
}
STATIC struct net_group *DoGetNetGroupFromIppcb(struct ip_pcb *pcb)
{
return pcb != NULL ? pcb->group : NULL;
}
struct net_group_ops netGroupOps = {
.get_curr_process_net_group = DoGetNetGroupFromCurrProcess,
.set_netif_net_group = DoSetNetifNetGroup,
.get_net_group_from_netif = DoGetNetGroupFromNetif,
.set_ippcb_net_group = DoSetIppcbNetGroup,
.get_net_group_from_ippcb = DoGetNetGroupFromIppcb,
};
UINT32 OsInitRootNetContainer(NetContainer **netContainer)
{
UINT32 intSave;
NetContainer *newNetContainer = CreateNewNetContainer(NULL);
if (newNetContainer == NULL) {
return ENOMEM;
}
newNetContainer->group = get_root_net_group();
set_default_net_group_ops(&netGroupOps);
SCHEDULER_LOCK(intSave);
g_currentNetContainerNum++;
*netContainer = newNetContainer;
g_rootNetContainer = newNetContainer;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsGetNetContainerCount(VOID)
{
return g_currentNetContainerNum;
}
#endif

View File

@@ -52,7 +52,18 @@ STATIC VOID FreeVpid(LosProcessCB *processCB)
processVid->vpid = OS_INVALID_VALUE;
LOS_ListTailInsert(&pidContainer->pidFreeList, &processVid->node);
LOS_AtomicDec(&pidContainer->rc);
pidContainer = pidContainer->parent;
PidContainer *parentPidContainer = pidContainer->parent;
if (LOS_AtomicRead(&pidContainer->rc) > 0) {
pidContainer = parentPidContainer;
continue;
}
g_currentPidContainerNum--;
(VOID)LOS_MemFree(m_aucSysMem1, pidContainer->rootPGroup);
(VOID)LOS_MemFree(m_aucSysMem1, pidContainer);
if (pidContainer == processCB->container->pidContainer) {
processCB->container->pidContainer = NULL;
}
pidContainer = parentPidContainer;
}
}
@@ -214,7 +225,7 @@ VOID OsPidContainerDestroyAllProcess(LosProcessCB *curr)
for (UINT32 index = 2; index < LOSCFG_BASE_CORE_PROCESS_LIMIT; index++) { /* 2: ordinary process */
SCHEDULER_LOCK(intSave);
LosProcessCB *processCB = OS_PCB_FROM_PID(index);
if (OsProcessIsUnused(processCB)) {
if (OsProcessIsUnused(processCB) || (processCB->parentProcess == NULL)) {
SCHEDULER_UNLOCK(intSave);
continue;
}
@@ -305,7 +316,7 @@ VOID OsPidContainerDestroy(Container *container, LosProcessCB *processCB)
}
}
if (LOS_AtomicRead(&pidContainer->rc) <= 0) {
if ((container->pidContainer != NULL) && (LOS_AtomicRead(&pidContainer->rc) <= 0)) {
g_currentPidContainerNum--;
container->pidContainer = NULL;
container->pidForChildContainer = NULL;
@@ -409,6 +420,10 @@ UINT32 OsCopyPidContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *pare
}
SCHEDULER_UNLOCK(intSave);
if (OsContainerLimitCheck(PID_CONTAINER, &g_currentPidContainerNum) != LOS_OK) {
return EPERM;
}
ret = CreatePidContainer(child, parent);
if (ret != LOS_OK) {
return ret;
@@ -445,6 +460,10 @@ UINT32 OsUnsharePidContainer(UINTPTR flags, LosProcessCB *curr, Container *newCo
return LOS_OK;
}
if (OsContainerLimitCheck(PID_CONTAINER, &g_currentPidContainerNum) != LOS_OK) {
return EPERM;
}
PidContainer *pidForChild = CreateNewPidContainer(curr->container->pidContainer);
if (pidForChild == NULL) {
return ENOMEM;
@@ -596,4 +615,9 @@ UINT32 OsGetPidContainerID(PidContainer *pidContainer)
return pidContainer->containerID;
}
UINT32 OsGetPidContainerCount(VOID)
{
return g_currentPidContainerNum;
}
#endif

View File

@@ -96,6 +96,10 @@ UINT32 OsCopyTimeContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *par
return LOS_OK;
}
if (OsContainerLimitCheck(TIME_CONTAINER, &g_currentTimeContainerNum) != LOS_OK) {
return EPERM;
}
return CreateTimeContainer(child, parent);
}
@@ -114,6 +118,10 @@ UINT32 OsUnshareTimeContainer(UINTPTR flags, LosProcessCB *curr, Container *newC
return LOS_OK;
}
if (OsContainerLimitCheck(TIME_CONTAINER, &g_currentTimeContainerNum) != LOS_OK) {
return EPERM;
}
TimeContainer *timeForChild = CreateNewTimeContainer(curr->container->timeContainer);
if (timeForChild == NULL) {
return ENOMEM;
@@ -242,4 +250,9 @@ UINT32 OsSetTimeContainerMonotonic(LosProcessCB *processCB, struct timespec64 *o
timeContainer->monotonic.tv_nsec = offsets->tv_nsec;
return LOS_OK;
}
UINT32 OsGetTimeContainerCount(VOID)
{
return g_currentTimeContainerNum;
}
#endif

View File

@@ -28,6 +28,7 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef LOSCFG_USER_CONTAINER
#include "los_user_container_pri.h"
#include "errno.h"
#include "ctype.h"
@@ -47,11 +48,14 @@
#define OCT 8
#define DEC 10
#ifdef LOSCFG_USER_CONTAINER
UINT32 g_currentUserContainerNum = 1;
UINT32 g_currentUserContainerNum = 0;
UINT32 OsCreateUserContainer(Credentials *newCredentials, UserContainer *parentUserContainer)
{
if (g_currentUserContainerNum >= OsGetContainerLimit(USER_CONTAINER)) {
return EPERM;
}
if ((parentUserContainer != NULL) && (parentUserContainer->level >= LEVEL_MAX)) {
return EINVAL;
}
@@ -95,7 +99,11 @@ VOID FreeUserContainer(UserContainer *userContainer)
userContainer->parent = NULL;
userContainer = parent;
g_currentUserContainerNum--;
} while ((userContainer != NULL) && (LOS_AtomicRead(&userContainer->rc) <= 0));
if (userContainer == NULL) {
break;
}
LOS_AtomicDec(&userContainer->rc);
} while (LOS_AtomicRead(&userContainer->rc) <= 0);
}
STATIC UidGidExtent *MapIdUpBase(UINT32 extents, UidGidMap *map, UINT32 id)
@@ -423,4 +431,9 @@ INT32 OsUserContainerMapWrite(struct ProcFile *fp, CHAR *kbuf, size_t count,
map->extentCount = newMap.extentCount;
return count;
}
UINT32 OsGetUserContainerCount(VOID)
{
return g_currentUserContainerNum;
}
#endif

View File

@@ -28,12 +28,11 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef LOSCFG_UTS_CONTAINER
#include "internal.h"
#include "los_uts_container_pri.h"
#include "los_process_pri.h"
#ifdef LOSCFG_UTS_CONTAINER
STATIC UINT32 g_currentUtsContainerNum;
STATIC UINT32 InitUtsContainer(struct utsname *name)
@@ -135,6 +134,10 @@ UINT32 OsCopyUtsContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *pare
return LOS_OK;
}
if (OsContainerLimitCheck(UTS_CONTAINER, &g_currentUtsContainerNum) != LOS_OK) {
return EPERM;
}
return CreateUtsContainer(child, parent);
}
@@ -151,6 +154,10 @@ UINT32 OsUnshareUtsContainer(UINTPTR flags, LosProcessCB *curr, Container *newCo
return LOS_OK;
}
if (OsContainerLimitCheck(UTS_CONTAINER, &g_currentUtsContainerNum) != LOS_OK) {
return EPERM;
}
UtsContainer *utsContainer = CreateNewUtsContainer(parentContainer);
if (utsContainer == NULL) {
return ENOMEM;
@@ -226,4 +233,8 @@ UINT32 OsGetUtsContainerID(UtsContainer *utsContainer)
return utsContainer->containerID;
}
UINT32 OsGetUtsContainerCount(VOID)
{
return g_currentUtsContainerNum;
}
#endif

View File

@@ -109,6 +109,7 @@ STATIC VOID GetProcessInfo(ProcessInfo *pcbInfo, const LosProcessCB *processCB)
(VOID)memcpy_s(pcbInfo->name, OS_PCB_NAME_LEN, processCB->processName, OS_PCB_NAME_LEN);
}
#ifdef LOSCFG_KERNEL_VM
STATIC VOID GetProcessMemInfo(ProcessInfo *pcbInfo, const LosProcessCB *processCB, LosVmSpace *vmSpace)
{
/* Process memory usage statistics, idle task defaults to 0 */
@@ -130,6 +131,7 @@ STATIC VOID GetProcessMemInfo(ProcessInfo *pcbInfo, const LosProcessCB *processC
}
}
}
#endif
STATIC VOID GetThreadInfo(ProcessThreadInfo *threadInfo, LosProcessCB *processCB)
{
@@ -182,7 +184,9 @@ UINT32 OsGetProcessThreadInfo(UINT32 pid, ProcessThreadInfo *threadInfo)
return LOS_NOK;
}
#ifdef LOSCFG_KERNEL_VM
GetProcessMemInfo(&threadInfo->processInfo, processCB, processCB->vmSpace);
#endif
SCHEDULER_LOCK(intSave);
GetProcessInfo(&threadInfo->processInfo, processCB);
@@ -210,11 +214,14 @@ STATIC VOID ProcessMemUsageGet(ProcessInfo *pcbArray)
pcbInfo->status = OS_PROCESS_FLAG_UNUSED;
continue;
}
#ifdef LOSCFG_KERNEL_VM
LosVmSpace *vmSpace = processCB->vmSpace;
#endif
SCHEDULER_UNLOCK(intSave);
#ifdef LOSCFG_KERNEL_VM
GetProcessMemInfo(pcbInfo, processCB, vmSpace);
#endif
}
}

View File

@@ -442,7 +442,7 @@ LITE_OS_SEC_TEXT VOID OsProcessResourcesToFree(LosProcessCB *processCB)
#endif
#ifdef LOSCFG_KERNEL_CONTAINER
OsContainersDestroy(processCB);
OsOsContainersDestroyEarly(processCB);
#endif
#ifdef LOSCFG_FS_VFS
@@ -452,6 +452,13 @@ LITE_OS_SEC_TEXT VOID OsProcessResourcesToFree(LosProcessCB *processCB)
processCB->files = NULL;
#endif
#ifdef LOSCFG_KERNEL_CONTAINER
OsContainersDestroy(processCB);
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
OsPLimitsDeleteProcess(processCB);
#endif
if (processCB->resourceLimit != NULL) {
(VOID)LOS_MemFree((VOID *)m_aucSysMem0, processCB->resourceLimit);
processCB->resourceLimit = NULL;
@@ -606,7 +613,9 @@ UINT32 OsProcessInit(VOID)
#ifdef LOSCFG_KERNEL_CONTAINER
OsInitRootContainer();
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
OsProcLimiterSetInit();
#endif
SystemProcessEarlyInit(OsGetIdleProcess());
SystemProcessEarlyInit(OsGetUserInitProcess());
SystemProcessEarlyInit(OsGetKernelInitProcess());
@@ -883,6 +892,13 @@ STATIC UINT32 OsSystemProcessInit(LosProcessCB *processCB, UINT32 flags, const C
}
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
ret = OsPLimitsAddProcess(NULL, processCB);
if (ret != LOS_OK) {
ret = LOS_ENOMEM;
goto EXIT;
}
#endif
return LOS_OK;
EXIT:
@@ -2066,6 +2082,13 @@ STATIC INT32 OsCopyProcess(UINT32 flags, const CHAR *name, UINTPTR sp, UINT32 si
if (ret != LOS_OK) {
goto ERROR_INIT;
}
#ifdef LOSCFG_KERNEL_PLIMITS
ret = OsPLimitsAddProcess(run->plimits, child);
if (ret != LOS_OK) {
goto ERROR_INIT;
}
#endif
#endif
ret = OsForkInitPCB(flags, child, name, sp, size);
@@ -2134,6 +2157,9 @@ LITE_OS_SEC_TEXT INT32 OsClone(UINT32 flags, UINTPTR sp, UINT32 size)
#ifdef LOSCFG_USER_CONTAINER
cloneFlag |= CLONE_NEWUSER;
#endif
#ifdef LOSCFG_NET_CONTAINER
cloneFlag |= CLONE_NEWNET;
#endif
#endif
if (flags & (~cloneFlag)) {

View File

@@ -51,6 +51,9 @@
#ifdef LOSCFG_TIME_CONTAINER
#include "los_time_container_pri.h"
#endif
#ifdef LOSCFG_NET_CONTAINER
#include "los_net_container_pri.h"
#endif
typedef enum {
CONTAINER = 0,
@@ -62,6 +65,7 @@ typedef enum {
USER_CONTAINER,
TIME_CONTAINER,
TIME_CHILD_CONTAINER,
NET_CONTAINER,
CONTAINER_MAX,
} ContainerType;
@@ -84,14 +88,43 @@ typedef struct Container {
struct TimeContainer *timeContainer;
struct TimeContainer *timeForChildContainer;
#endif
#ifdef LOSCFG_NET_CONTAINER
struct NetContainer *netContainer;
#endif
} Container;
typedef struct TagContainerLimit {
#ifdef LOSCFG_PID_CONTAINER
UINT32 pidLimit;
#endif
#ifdef LOSCFG_UTS_CONTAINER
UINT32 utsLimit;
#endif
#ifdef LOSCFG_MNT_CONTAINER
UINT32 mntLimit;
#endif
#ifdef LOSCFG_IPC_CONTAINER
UINT32 ipcLimit;
#endif
#ifdef LOSCFG_TIME_CONTAINER
UINT32 timeLimit;
#endif
#ifdef LOSCFG_USER_CONTAINER
UINT32 userLimit;
#endif
#ifdef LOSCFG_NET_CONTAINER
UINT32 netLimit;
#endif
} ContainerLimit;
VOID OsContainerInitSystemProcess(LosProcessCB *processCB);
VOID OsInitRootContainer(VOID);
UINT32 OsCopyContainers(UINTPTR flags, LosProcessCB *child, LosProcessCB *parent, UINT32 *processID);
VOID OsOsContainersDestroyEarly(LosProcessCB *processCB);
VOID OsContainersDestroy(LosProcessCB *processCB);
VOID OsContainerFree(LosProcessCB *processCB);
@@ -104,5 +137,12 @@ INT32 OsUnshare(UINT32 flags);
INT32 OsSetNs(INT32 fd, INT32 type);
UINT32 OsGetContainerLimit(ContainerType type);
UINT32 OsContainerLimitCheck(ContainerType type, UINT32 *containerCount);
UINT32 OsSetContainerLimit(ContainerType type, UINT32 value);
UINT32 OsGetContainerCount(ContainerType type);
#endif
#endif /* _LOS_CONTAINER_PRI_H */

View File

@@ -72,6 +72,8 @@ UINT32 OsGetIpcContainerID(IpcContainer *ipcContainer);
IpcContainer *OsGetCurrIpcContainer(VOID);
UINT32 OsGetIpcContainerCount(VOID);
#define IPC_ALL_QUEUE (OsGetCurrIpcContainer()->allQueue)
#define FREE_QUEUE_LIST (OsGetCurrIpcContainer()->freeQueueList)

View File

@@ -61,5 +61,6 @@ VOID OsMntContainerDestroy(struct Container *container);
UINT32 OsGetMntContainerID(MntContainer *mntContainer);
UINT32 OsGetMntContainerCount(VOID);
#endif
#endif

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_NET_CONTAINER_PRI_H
#define _LOS_NET_CONTAINER_PRI_H
#include <lwip/net_group.h>
#include <lwip/netif.h>
#include <lwip/ip.h>
#include "los_atomic.h"
#ifdef LOSCFG_NET_CONTAINER
typedef struct ProcessCB LosProcessCB;
struct Container;
typedef struct NetContainer {
Atomic rc;
struct net_group *group;
UINT32 containerID;
} NetContainer;
UINT32 OsInitRootNetContainer(NetContainer **ipcContainer);
UINT32 OsCopyNetContainer(UINTPTR flags, LosProcessCB *child, LosProcessCB *parent);
UINT32 OsUnshareNetContainer(UINTPTR flags, LosProcessCB *curr, struct Container *newContainer);
UINT32 OsSetNsNetContainer(UINT32 flags, struct Container *container, struct Container *newContainer);
VOID OsNetContainerDestroy(struct Container *container);
UINT32 OsGetNetContainerID(NetContainer *ipcContainer);
UINT32 OsGetNetContainerCount(VOID);
#endif
#endif /* _LOS_NET_CONTAINER_PRI_H */

View File

@@ -106,4 +106,6 @@ UINT32 OsAllocVtid(LosTaskCB *taskCB, const LosProcessCB *processCB);
UINT32 OsGetPidContainerID(PidContainer *pidContainer);
BOOL OsPidContainerProcessParentIsRealParent(const LosProcessCB *processCB, const LosProcessCB *curr);
UINT32 OsGetPidContainerCount(VOID);
#endif /* _LOS_PID_CONTAINER_PRI_H */

View File

@@ -50,6 +50,9 @@
#ifdef LOSCFG_KERNEL_CONTAINER
#include "los_container_pri.h"
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
#include "los_plimits.h"
#endif
#ifdef __cplusplus
#if __cplusplus
@@ -139,6 +142,11 @@ typedef struct ProcessCB {
#ifdef LOSCFG_PROC_PROCESS_DIR
struct ProcDirEntry *procDir;
#endif
#ifdef LOSCFG_KERNEL_PLIMITS
ProcLimiterSet *plimits;
LOS_DL_LIST plimitsList; /* plimit process list */
PLimitsData limitStat;
#endif
} LosProcessCB;
extern LosProcessCB *g_processCBArray;

View File

@@ -429,7 +429,7 @@ typedef struct TagTaskCB {
PidContainer *pidContainer;
#endif
#ifdef LOSCFG_IPC_CONTAINER
BOOL cloneIpc;
BOOL cloneIpc;
#endif
} LosTaskCB;
@@ -619,6 +619,10 @@ STATIC INLINE VOID SchedTaskUnfreeze(LosTaskCB *taskCB)
g_taskScheduled &= ~(1U << (cpuid)); \
} while (0);
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
BOOL OsSchedLimitCheckTime(LosTaskCB *task);
#endif
STATIC INLINE LosTaskCB *HPFRunqueueTopTaskGet(HPFRunqueue *rq)
{
LosTaskCB *newTask = NULL;
@@ -634,6 +638,12 @@ STATIC INLINE LosTaskCB *HPFRunqueueTopTaskGet(HPFRunqueue *rq)
while (bitmap) {
UINT32 priority = CLZ(bitmap);
LOS_DL_LIST_FOR_EACH_ENTRY(newTask, &queueList->priQueList[priority], LosTaskCB, pendList) {
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
if (!OsSchedLimitCheckTime(newTask)) {
bitmap &= ~(1U << (OS_PRIORITY_QUEUE_NUM - priority - 1));
continue;
}
#endif
#ifdef LOSCFG_KERNEL_SMP
if (newTask->cpuAffiMask & (1U << cpuid)) {
#endif

View File

@@ -54,6 +54,7 @@ extern "C" {
/* scheduler lock */
extern SPIN_LOCK_S g_taskSpin;
#define SCHEDULER_HELD() LOS_SpinHeld(&g_taskSpin)
#define SCHEDULER_LOCK(state) LOS_SpinLockSave(&g_taskSpin, &(state))
#define SCHEDULER_UNLOCK(state) LOS_SpinUnlockRestore(&g_taskSpin, state)

View File

@@ -62,6 +62,8 @@ UINT32 OsGetTimeContainerMonotonic(LosProcessCB *processCB, struct timespec64 *o
UINT32 OsSetTimeContainerMonotonic(LosProcessCB *processCB, struct timespec64 *offsets);
UINT32 OsGetTimeContainerCount(VOID);
#define CLOCK_MONOTONIC_TIME_BASE (OsGetCurrTimeContainer()->monotonic)
#endif

View File

@@ -76,5 +76,7 @@ UINT32 OsMakeKgid(UserContainer *userContainer, UINT32 gid);
INT32 OsUserContainerMapWrite(struct ProcFile *fp, CHAR *buf, size_t count,
INT32 capSetid, UidGidMap *map, UidGidMap *parentMap);
UINT32 OsGetUserContainerCount(VOID);
#endif
#endif

View File

@@ -60,5 +60,6 @@ struct utsname *OsGetCurrUtsName(VOID);
UINT32 OsGetUtsContainerID(UtsContainer *utsContainer);
UINT32 OsGetUtsContainerCount(VOID);
#endif
#endif /* _LOS_UTS_CONTAINER_PRI_H */

View File

@@ -98,6 +98,9 @@ STATIC VOID HPFTimeSliceUpdate(SchedRunqueue *rq, LosTaskCB *taskCB, UINT64 curr
taskCB->schedStat.timeSliceRealTime += incTime;
#endif
}
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
OsSchedLimitUpdateRuntime(taskCB, currTime, incTime);
#endif
taskCB->irqUsedTime = 0;
taskCB->startTime = currTime;
if (taskCB->timeSlice <= OS_TIME_SLICE_MIN) {

View File

@@ -359,6 +359,12 @@ STATUS_T OsVmPageFaultHandler(VADDR_T vaddr, UINT32 flags, ExcContext *frame)
return LOS_ERRNO_VM_ACCESS_DENIED;
}
#ifdef LOSCFG_KERNEL_PLIMITS
if (OsMemLimitCheckAndMemAdd(PAGE_SIZE) != LOS_OK) {
return LOS_ERRNO_VM_NO_MEMORY;
}
#endif
(VOID)LOS_MuxAcquire(&space->regionMux);
region = LOS_RegionFind(space, vaddr);
if (region == NULL) {
@@ -450,6 +456,9 @@ VMM_MAP_FAILED:
}
CHECK_FAILED:
OsFaultTryFixup(frame, excVaddr, &status);
#ifdef LOSCFG_KERNEL_PLIMITS
OsMemLimitMemFree(PAGE_SIZE);
#endif
DONE:
(VOID)LOS_MuxRelease(&space->regionMux);
return status;

View File

@@ -34,7 +34,9 @@
#include "los_vm_phys.h"
#include "los_vm_boot.h"
#include "los_vm_filemap.h"
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
#include "los_plimits.h"
#endif
#ifdef LOSCFG_KERNEL_VM
@@ -81,7 +83,8 @@ VOID OsVmPageStartup(VOID)
* struct LosVmPage occupied, which satisfies the equation:
* nPage * sizeof(LosVmPage) + nPage * PAGE_SIZE = OsVmPhysPageNumGet() * PAGE_SIZE.
*/
nPage = OsVmPhysPageNumGet() * PAGE_SIZE / (sizeof(LosVmPage) + PAGE_SIZE);
UINT32 pageNum = OsVmPhysPageNumGet();
nPage = pageNum * PAGE_SIZE / (sizeof(LosVmPage) + PAGE_SIZE);
g_vmPageArraySize = nPage * sizeof(LosVmPage);
g_vmPageArray = (LosVmPage *)OsVmBootMemAlloc(g_vmPageArraySize);
@@ -89,6 +92,9 @@ VOID OsVmPageStartup(VOID)
OsVmPhysSegAdd();
OsVmPhysInit();
#ifdef LOSCFG_KERNEL_PLIMITS
OsMemLimitSetLimit(pageNum * PAGE_SIZE);
#endif
for (segID = 0; segID < g_vmPhysSegNum; segID++) {
seg = &g_vmPhysSeg[segID];

View File

@@ -456,6 +456,9 @@ VOID LOS_PhysPagesFreeContiguous(VOID *ptr, size_t nPages)
OsVmPhysPagesFreeContiguous(page, nPages);
LOS_SpinUnlockRestore(&seg->freeListLock, intSave);
#ifdef LOSCFG_KERNEL_PLIMITS
OsMemLimitMemFree(nPages * PAGE_SIZE);
#endif
}
PADDR_T OsKVaddrToPaddr(VADDR_T kvaddr)
@@ -503,6 +506,9 @@ VOID LOS_PhysPageFree(LosVmPage *page)
LOS_SpinUnlockRestore(&seg->freeListLock, intSave);
}
#ifdef LOSCFG_KERNEL_PLIMITS
OsMemLimitMemFree(PAGE_SIZE);
#endif
}
LosVmPage *LOS_PhysPageAlloc(VOID)

View File

@@ -193,40 +193,58 @@ STATIC VOID ShmPagesRefDec(struct shmIDSource *seg)
}
}
STATIC INT32 ShmAllocSeg(key_t key, size_t size, INT32 shmflg)
STATIC INT32 ShmAllocSegCheck(key_t key, size_t *size, INT32 *segNum)
{
INT32 i;
INT32 segNum = -1;
struct shmIDSource *seg = NULL;
size_t count;
if ((size == 0) || (size < IPC_SHM_INFO.shmmin) ||
(size > IPC_SHM_INFO.shmmax)) {
if ((*size == 0) || (*size < IPC_SHM_INFO.shmmin) ||
(*size > IPC_SHM_INFO.shmmax)) {
return -EINVAL;
}
size = LOS_Align(size, PAGE_SIZE);
if ((IPC_SHM_USED_PAGE_COUNT + (size >> PAGE_SHIFT)) > IPC_SHM_INFO.shmall) {
*size = LOS_Align(*size, PAGE_SIZE);
if ((IPC_SHM_USED_PAGE_COUNT + (*size >> PAGE_SHIFT)) > IPC_SHM_INFO.shmall) {
return -ENOMEM;
}
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
if (OsIPCLimitShmAlloc(*size) != LOS_OK) {
return -ENOMEM;
}
#endif
for (i = 0; i < IPC_SHM_INFO.shmmni; i++) {
if (IPC_SHM_SEGS[i].status & SHM_SEG_FREE) {
IPC_SHM_SEGS[i].status &= ~SHM_SEG_FREE;
segNum = i;
*segNum = i;
break;
}
}
if (segNum < 0) {
if (*segNum < 0) {
return -ENOSPC;
}
return 0;
}
STATIC INT32 ShmAllocSeg(key_t key, size_t size, INT32 shmflg)
{
INT32 segNum = -1;
struct shmIDSource *seg = NULL;
size_t count;
INT32 ret = ShmAllocSegCheck(key, &size, &segNum);
if (ret < 0) {
return ret;
}
seg = &IPC_SHM_SEGS[segNum];
count = LOS_PhysPagesAlloc(size >> PAGE_SHIFT, &seg->node);
if (count != (size >> PAGE_SHIFT)) {
(VOID)LOS_PhysPagesFree(&seg->node);
seg->status = SHM_SEG_FREE;
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
OsIPCLimitShmFree(size);
#endif
return -ENOMEM;
}
@@ -264,6 +282,9 @@ STATIC INLINE VOID ShmFreeSeg(struct shmIDSource *seg, UINT32 *shmUsedPageCount)
VM_ERR("free physical pages failed, count = %d, size = %d", count, seg->ds.shm_segsz >> PAGE_SHIFT);
return;
}
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
OsIPCLimitShmFree(seg->ds.shm_segsz);
#endif
if (shmUsedPageCount != NULL) {
(*shmUsedPageCount) -= seg->ds.shm_segsz >> PAGE_SHIFT;
}

View File

@@ -389,6 +389,14 @@ extern UINT32 __heap_end;
#define VERSION_NUM(a, b, c, d) (((a) << 24) | ((b) << 16) | (c) << 8 | (d))
#define KERNEL_OPEN_VERSION_NUM VERSION_NUM(KERNEL_MAJOR, KERNEL_MINOR, KERNEL_PATCH, KERNEL_ITRE)
/**
* @ingroup los_config
* The container limit
*/
#ifndef LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT
#define LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT 10
#endif
/****************************** Exception information configuration ******************************/
#ifdef LOSCFG_SAVE_EXCINFO
/**

View File

@@ -42,6 +42,7 @@ group("extended") {
"lms",
"perf",
"pipes",
"plimit",
"power",
"trace",
"vdso",
@@ -62,5 +63,6 @@ config("public") {
"perf:public",
"lms:public",
"power:public",
"plimit:public",
]
}

View File

@@ -76,6 +76,31 @@ config KERNEL_PIPE
help
Answer Y to enable LiteOS support pipes.
config KERNEL_PLIMITS
bool "Enable plimits Feature"
default n
depends on KERNEL_EXTKERNEL
config KERNEL_MEM_PLIMIT
bool "Enable mem limits Feature"
default n
depends on KERNEL_PLIMITS
config KERNEL_IPC_PLIMIT
bool "Enable ipc limits Feature"
default n
depends on KERNEL_PLIMITS
config KERNEL_DEV_PLIMIT
bool "Enable dev limits Feature"
default n
depends on KERNEL_PLIMITS
config KERNEL_SCHED_PLIMIT
bool "Enable sched limits Feature"
default n
depends on KERNEL_PLIMITS
config BASE_CORE_HILOG
bool "Enable Hilog"
default y
@@ -104,4 +129,4 @@ source "kernel/extended/perf/Kconfig"
source "kernel/extended/lms/Kconfig"
######################### config options of hilog #########################
source "kernel/extended/hilog/Kconfig"
source "kernel/extended/hilog/Kconfig"

View File

@@ -1094,7 +1094,7 @@ ERROR_COPY:
return ret;
}
LITE_OS_SEC_TEXT STATIC UINT32 CheckRecievedMsg(IpcListNode *node, IpcContent *content, LosTaskCB *tcb)
LITE_OS_SEC_TEXT STATIC UINT32 CheckReceivedMsg(IpcListNode *node, IpcContent *content, LosTaskCB *tcb)
{
UINT32 ret = LOS_OK;
if (node == NULL) {
@@ -1184,7 +1184,7 @@ LITE_OS_SEC_TEXT STATIC UINT32 LiteIpcRead(IpcContent *content)
LOS_ListDelete(listNode);
node = LOS_DL_LIST_ENTRY(listNode, IpcListNode, listNode);
SCHEDULER_UNLOCK(intSave);
ret = CheckRecievedMsg(node, content, tcb);
ret = CheckReceivedMsg(node, content, tcb);
if (ret == LOS_OK) {
break;
}

View File

@@ -0,0 +1,46 @@
# Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. 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.
#
# 3. 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 HOLDER 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.
import("//kernel/liteos_a/liteos.gni")
module_switch = true
module_name = get_path_info(rebase_path("."), "name")
kernel_module(module_name) {
sources = [
"los_devicelimit.c",
"los_ipclimit.c",
"los_memlimit.c",
"los_plimits.c",
"los_processlimit.c",
"los_schedlimit.c",
]
}
config("public") {
include_dirs = [ "." ]
}

View File

@@ -0,0 +1,35 @@
# Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. 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.
#
# 3. 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 HOLDER 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.
include $(LITEOSTOPDIR)/config.mk
MODULE_NAME := $(notdir $(shell pwd))
LOCAL_SRCS := $(wildcard *.c)
include $(MODULE)

View File

@@ -0,0 +1,599 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
#include "los_seq_buf.h"
#include "los_bitmap.h"
#include "los_process_pri.h"
#include "los_devicelimit.h"
#define TYPE_CHAR_LEN (1)
#define DEVICE_NAME_PREFIX_SPACE (1)
#define DEVICE_ACCESS_MAXLEN (3)
#define BUF_SEPARATOR (5)
STATIC ProcDevLimit *g_procDevLimit = NULL;
VOID OsDevLimitInit(UINTPTR limit)
{
ProcDevLimit *deviceLimit = (ProcDevLimit *)limit;
deviceLimit->behavior = DEVLIMIT_DEFAULT_ALLOW;
LOS_ListInit(&(deviceLimit->accessList));
g_procDevLimit = deviceLimit;
}
VOID *OsDevLimitAlloc(VOID)
{
ProcDevLimit *plimit = (ProcDevLimit *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcDevLimit));
if (plimit == NULL) {
return NULL;
}
(VOID)memset_s(plimit, sizeof(ProcDevLimit), 0, sizeof(ProcDevLimit));
LOS_ListInit(&(plimit->accessList));
plimit->behavior = DEVLIMIT_DEFAULT_NONE;
return (VOID *)plimit;
}
STATIC VOID DevAccessListDelete(ProcDevLimit *devLimit)
{
DevAccessItem *delItem = NULL;
DevAccessItem *tmpItem = NULL;
LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(delItem, tmpItem, &devLimit->accessList, DevAccessItem, list) {
LOS_ListDelete(&delItem->list);
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)delItem);
}
}
VOID OsDevLimitFree(UINTPTR limit)
{
ProcDevLimit *devLimit = (ProcDevLimit *)limit;
if (devLimit == NULL) {
return;
}
DevAccessListDelete(devLimit);
(VOID)LOS_MemFree(m_aucSysMem1, devLimit);
}
STATIC UINT32 DevLimitCopyAccess(ProcDevLimit *devLimitDest, ProcDevLimit *devLimitSrc)
{
DevAccessItem *tmpItem = NULL;
INT32 itemSize = sizeof(DevAccessItem);
devLimitDest->behavior = devLimitSrc->behavior;
LOS_DL_LIST_FOR_EACH_ENTRY(tmpItem, &devLimitSrc->accessList, DevAccessItem, list) {
DevAccessItem *newItem = (DevAccessItem *)LOS_MemAlloc(m_aucSysMem1, itemSize);
if (newItem == NULL) {
return ENOMEM;
}
(VOID)memcpy_s(newItem, sizeof(DevAccessItem), tmpItem, sizeof(DevAccessItem));
LOS_ListTailInsert(&devLimitDest->accessList, &newItem->list);
}
return LOS_OK;
}
VOID OsDevLimitCopy(UINTPTR dest, UINTPTR src)
{
ProcDevLimit *devLimitDest = (ProcDevLimit *)dest;
ProcDevLimit *devLimitSrc = (ProcDevLimit *)src;
(VOID)DevLimitCopyAccess(devLimitDest, devLimitSrc);
devLimitDest->parent = (ProcDevLimit *)src;
}
STATIC INLINE INT32 IsSpace(INT32 c)
{
return (c == ' ' || (unsigned)c - '\t' < BUF_SEPARATOR);
}
STATIC UINT32 ParseItemAccess(const CHAR *buf, DevAccessItem *item)
{
switch (*buf) {
case 'a':
item->type = DEVLIMIT_DEV_ALL;
return LOS_OK;
case 'b':
item->type = DEVLIMIT_DEV_BLOCK;
break;
case 'c':
item->type = DEVLIMIT_DEV_CHAR;
break;
default:
return EINVAL;
}
buf += DEVICE_NAME_PREFIX_SPACE;
if (!IsSpace(*buf)) {
return EINVAL;
}
buf += DEVICE_NAME_PREFIX_SPACE;
for (INT32 count = 0; count < sizeof(item->name) - 1; count++) {
if (IsSpace(*buf)) {
break;
}
item->name[count] = *buf;
buf += TYPE_CHAR_LEN;
}
if (!IsSpace(*buf)) {
return EINVAL;
}
buf += DEVICE_NAME_PREFIX_SPACE;
for (INT32 i = 0; i < DEVICE_ACCESS_MAXLEN; i++) {
switch (*buf) {
case 'r':
item->access |= DEVLIMIT_ACC_READ;
break;
case 'w':
item->access |= DEVLIMIT_ACC_WRITE;
break;
case 'm':
item->access |= DEVLIMIT_ACC_MKNOD;
break;
case '\n':
case '\0':
i = DEVICE_ACCESS_MAXLEN;
break;
default:
return EINVAL;
}
buf += TYPE_CHAR_LEN;
}
return LOS_OK;
}
STATIC BOOL DevLimitMayAllowAll(ProcDevLimit *parent)
{
if (parent == NULL) {
return TRUE;
}
return (parent->behavior == DEVLIMIT_DEFAULT_ALLOW);
}
STATIC BOOL DevLimitHasChildren(ProcLimitSet *procLimitSet, ProcDevLimit *devLimit)
{
ProcLimitSet *parent = procLimitSet;
ProcLimitSet *childProcLimitSet = NULL;
if (devLimit == NULL) {
return FALSE;
}
LOS_DL_LIST_FOR_EACH_ENTRY(childProcLimitSet, &(procLimitSet->childList), ProcLimitSet, childList) {
if (childProcLimitSet == NULL) {
continue;
}
if (childProcLimitSet->parent != parent) {
continue;
}
if (!((childProcLimitSet->mask) & BIT(PROCESS_LIMITER_ID_DEV))) {
continue;
}
return TRUE;
}
return FALSE;
}
STATIC UINT32 DealItemAllAccess(ProcLimitSet *procLimitSet, ProcDevLimit *devLimit,
ProcDevLimit *devParentLimit, INT32 filetype)
{
switch (filetype) {
case DEVLIMIT_ALLOW: {
if (DevLimitHasChildren(procLimitSet, devLimit)) {
return EINVAL;
}
if (!DevLimitMayAllowAll(devParentLimit)) {
return EPERM;
}
DevAccessListDelete(devLimit);
devLimit->behavior = DEVLIMIT_DEFAULT_ALLOW;
if (devParentLimit == NULL) {
break;
}
DevLimitCopyAccess(devLimit, devParentLimit);
break;
}
case DEVLIMIT_DENY: {
if (DevLimitHasChildren(procLimitSet, devLimit)) {
return EINVAL;
}
DevAccessListDelete(devLimit);
devLimit->behavior = DEVLIMIT_DEFAULT_DENY;
break;
}
default:
return EINVAL;
}
return LOS_OK;
}
STATIC BOOL DevLimitMatchItemPartial(LOS_DL_LIST *list, DevAccessItem *item)
{
if ((list == NULL) || (item == NULL)) {
return FALSE;
}
if (LOS_ListEmpty(list)) {
return FALSE;
}
DevAccessItem *walk = NULL;
LOS_DL_LIST_FOR_EACH_ENTRY(walk, list, DevAccessItem, list) {
if (item->type != walk->type) {
continue;
}
if ((strcmp(walk->name, "*") != 0) && (strcmp(item->name, "*") != 0)
&& (strcmp(walk->name, item->name) != 0)) {
continue;
}
if (!(item->access & ~(walk->access))) {
return TRUE;
}
}
return FALSE;
}
STATIC BOOL DevLimitParentAllowsRmItem(ProcDevLimit *devParentLimit, DevAccessItem *item)
{
if (devParentLimit == NULL) {
return TRUE;
}
/* Make sure you're not removing part or a whole item existing in the parent plimits */
return !DevLimitMatchItemPartial(&devParentLimit->accessList, item);
}
STATIC BOOL DevLimitMatchItem(LOS_DL_LIST *list, DevAccessItem *item)
{
if ((list == NULL) || (item == NULL)) {
return FALSE;
}
if (LOS_ListEmpty(list)) {
return FALSE;
}
DevAccessItem *walk = NULL;
LOS_DL_LIST_FOR_EACH_ENTRY(walk, list, DevAccessItem, list) {
if (item->type != walk->type) {
continue;
}
if ((strcmp(walk->name, "*") != 0) && (strcmp(walk->name, item->name) != 0)) {
continue;
}
if (!(item->access & ~(walk->access))) {
return TRUE;
}
}
return FALSE;
}
/**
* This is used to make sure a child plimits won't have more privileges than its parent
*/
STATIC BOOL DevLimitVerifyNewItem(ProcDevLimit *parent, DevAccessItem *item, INT32 currBehavior)
{
if (parent == NULL) {
return TRUE;
}
if (parent->behavior == DEVLIMIT_DEFAULT_ALLOW) {
if (currBehavior == DEVLIMIT_DEFAULT_ALLOW) {
return TRUE;
}
return !DevLimitMatchItemPartial(&parent->accessList, item);
}
return DevLimitMatchItem(&parent->accessList, item);
}
STATIC BOOL DevLimitParentAllowsAddItem(ProcDevLimit *devParentLimit, DevAccessItem *item, INT32 currBehavior)
{
return DevLimitVerifyNewItem(devParentLimit, item, currBehavior);
}
STATIC VOID DevLimitAccessListRm(ProcDevLimit *devLimit, DevAccessItem *item)
{
if ((item == NULL) || (devLimit == NULL)) {
return;
}
DevAccessItem *walk, *tmp = NULL;
LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(walk, tmp, &devLimit->accessList, DevAccessItem, list) {
if (walk->type != item->type) {
continue;
}
if (strcmp(walk->name, item->name) != 0) {
continue;
}
walk->access &= ~item->access;
if (!walk->access) {
LOS_ListDelete(&walk->list);
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)walk);
}
}
}
STATIC UINT32 DevLimitAccessListAdd(ProcDevLimit *devLimit, DevAccessItem *item)
{
if ((item == NULL) || (devLimit == NULL)) {
return ENOMEM;
}
DevAccessItem *walk = NULL;
DevAccessItem *newItem = (DevAccessItem *)LOS_MemAlloc(m_aucSysMem1, sizeof(DevAccessItem));
if (newItem == NULL) {
return ENOMEM;
}
(VOID)memcpy_s(newItem, sizeof(DevAccessItem), item, sizeof(DevAccessItem));
LOS_DL_LIST_FOR_EACH_ENTRY(walk, &devLimit->accessList, DevAccessItem, list) {
if (walk->type != item->type) {
continue;
}
if (strcmp(walk->name, item->name) != 0) {
continue;
}
walk->access |= item->access;
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)newItem);
newItem = NULL;
}
if (newItem != NULL) {
LOS_ListTailInsert(&devLimit->accessList, &newItem->list);
}
return LOS_OK;
}
/**
* Revalidate permissions
*/
STATIC VOID DevLimitRevalidateActiveItems(ProcDevLimit *devLimit, ProcDevLimit *devParentLimit)
{
if ((devLimit == NULL) || (devParentLimit == NULL)) {
return;
}
DevAccessItem *walK = NULL;
DevAccessItem *tmp = NULL;
LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(walK, tmp, &devLimit->accessList, DevAccessItem, list) {
if (!DevLimitParentAllowsAddItem(devParentLimit, walK, devLimit->behavior)) {
DevLimitAccessListRm(devLimit, walK);
}
}
}
/**
* propagates a new item to the children
*/
STATIC UINT32 DevLimitPropagateItem(ProcLimitSet *procLimitSet, ProcDevLimit *devLimit, DevAccessItem *item)
{
UINT32 ret = LOS_OK;
ProcLimitSet *parent = procLimitSet;
ProcLimitSet *childProcLimitSet = NULL;
if ((procLimitSet == NULL) || (item == NULL)) {
return ENOMEM;
}
if (devLimit == NULL) {
return LOS_OK;
}
LOS_DL_LIST_FOR_EACH_ENTRY(childProcLimitSet, &procLimitSet->childList, ProcLimitSet, childList) {
if (childProcLimitSet == NULL) {
continue;
}
if (childProcLimitSet->parent != parent) {
continue;
}
if (!((childProcLimitSet->mask) & BIT(PROCESS_LIMITER_ID_DEV))) {
continue;
}
ProcDevLimit *devLimitChild = (ProcDevLimit *)childProcLimitSet->limitsList[PROCESS_LIMITER_ID_DEV];
if (devLimit->behavior == DEVLIMIT_DEFAULT_ALLOW &&
devLimitChild->behavior == DEVLIMIT_DEFAULT_ALLOW) {
ret = DevLimitAccessListAdd(devLimitChild, item);
} else {
DevLimitAccessListRm(devLimitChild, item);
}
DevLimitRevalidateActiveItems(devLimitChild, (ProcDevLimit *)parent->limitsList[PROCESS_LIMITER_ID_DEV]);
}
return ret;
}
STATIC UINT32 DevLimitUpdateAccess(ProcLimitSet *procLimitSet, const CHAR *buf, INT32 filetype)
{
UINT32 ret;
UINT32 intSave;
DevAccessItem item = {0};
SCHEDULER_LOCK(intSave);
ProcDevLimit *devLimit = (ProcDevLimit *)(procLimitSet->limitsList[PROCESS_LIMITER_ID_DEV]);
ProcDevLimit *devParentLimit = devLimit->parent;
ret = ParseItemAccess(buf, &item);
if (ret != LOS_OK) {
SCHEDULER_UNLOCK(intSave);
return ret;
}
if (item.type == DEVLIMIT_DEV_ALL) {
ret = DealItemAllAccess(procLimitSet, devLimit, devParentLimit, filetype);
SCHEDULER_UNLOCK(intSave);
return ret;
}
switch (filetype) {
case DEVLIMIT_ALLOW: {
if (devLimit->behavior == DEVLIMIT_DEFAULT_ALLOW) {
if (!DevLimitParentAllowsRmItem(devParentLimit, &item)) {
SCHEDULER_UNLOCK(intSave);
return EPERM;
}
DevLimitAccessListRm(devLimit, &item);
break;
}
if (!DevLimitParentAllowsAddItem(devParentLimit, &item, devLimit->behavior)) {
SCHEDULER_UNLOCK(intSave);
return EPERM;
}
ret = DevLimitAccessListAdd(devLimit, &item);
break;
}
case DEVLIMIT_DENY: {
if (devLimit->behavior == DEVLIMIT_DEFAULT_DENY) {
DevLimitAccessListRm(devLimit, &item);
} else {
ret = DevLimitAccessListAdd(devLimit, &item);
}
// update child access list
ret = DevLimitPropagateItem(procLimitSet, devLimit, &item);
break;
}
default:
ret = EINVAL;
break;
}
SCHEDULER_UNLOCK(intSave);
return ret;
}
UINT32 OsDevLimitWriteAllow(ProcLimitSet *plimit, const CHAR *buf, UINT32 size)
{
(VOID)size;
return DevLimitUpdateAccess(plimit, buf, DEVLIMIT_ALLOW);
}
UINT32 OsDevLimitWriteDeny(ProcLimitSet *plimit, const CHAR *buf, UINT32 size)
{
(VOID)size;
return DevLimitUpdateAccess(plimit, buf, DEVLIMIT_DENY);
}
STATIC VOID DevLimitItemSetAccess(CHAR *acc, INT16 access)
{
INT32 index = 0;
(VOID)memset_s(acc, ACCLEN, 0, ACCLEN);
if (access & DEVLIMIT_ACC_READ) {
acc[index++] = 'r';
}
if (access & DEVLIMIT_ACC_WRITE) {
acc[index++] = 'w';
}
if (access & DEVLIMIT_ACC_MKNOD) {
acc[index++] = 'm';
}
}
STATIC CHAR DevLimitItemTypeToChar(INT16 type)
{
if (type == DEVLIMIT_DEV_ALL) {
return 'a';
} else if (type == DEVLIMIT_DEV_CHAR) {
return 'c';
} else if (type == DEVLIMIT_DEV_BLOCK) {
return 'b';
}
return 'X';
}
UINT32 OsDevLimitShow(ProcDevLimit *devLimit, struct SeqBuf *seqBuf)
{
DevAccessItem *item = NULL;
CHAR acc[ACCLEN];
UINT32 intSave;
if ((devLimit == NULL) || (seqBuf == NULL)) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
if (devLimit->behavior == DEVLIMIT_DEFAULT_ALLOW) {
DevLimitItemSetAccess(acc, DEVLIMIT_ACC_MASK);
SCHEDULER_UNLOCK(intSave);
LosBufPrintf(seqBuf, "%c %s %s\n", DevLimitItemTypeToChar(DEVLIMIT_DEV_ALL), "*", acc);
return LOS_OK;
}
LOS_DL_LIST_FOR_EACH_ENTRY(item, &devLimit->accessList, DevAccessItem, list) {
DevLimitItemSetAccess(acc, item->access);
LosBufPrintf(seqBuf, "%c %s %s\n", DevLimitItemTypeToChar(item->type), item->name, acc);
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
STATIC INLINE INT16 ConversionDevType(INT32 vnodeType)
{
INT16 type = 0;
if (vnodeType == VNODE_TYPE_BLK) {
type = DEVLIMIT_DEV_BLOCK;
} else if (vnodeType == VNODE_TYPE_CHR) {
type = DEVLIMIT_DEV_CHAR;
}
return type;
}
STATIC INLINE INT16 ConversionDevAccess(INT32 flags)
{
INT16 access = 0;
if ((flags & O_ACCMODE) == O_RDONLY) {
access |= DEVLIMIT_ACC_READ;
}
if (flags & O_WRONLY) {
access |= DEVLIMIT_ACC_WRITE;
}
if (flags & O_RDWR) {
access |= DEVLIMIT_ACC_WRITE | DEVLIMIT_ACC_READ;
}
if (flags & O_CREAT) {
access |= DEVLIMIT_ACC_MKNOD;
}
return access;
}
UINT32 OsDevLimitCheckPermission(INT32 vnodeType, const CHAR *pathName, INT32 flags)
{
BOOL matched = FALSE;
DevAccessItem item = {0};
LosProcessCB *run = OsCurrProcessGet();
if ((run == NULL) || (run->plimits == NULL)) {
return LOS_OK;
}
if (pathName == NULL) {
return EINVAL;
}
ProcDevLimit *devLimit = (ProcDevLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_DEV];
item.type = ConversionDevType(vnodeType);
item.access = ConversionDevAccess(flags);
LOS_ListInit(&(item.list));
(VOID)strncpy_s(item.name, PATH_MAX, pathName, PATH_MAX);
if (devLimit->behavior == DEVLIMIT_DEFAULT_ALLOW) {
matched = !DevLimitMatchItemPartial(&devLimit->accessList, &item);
} else {
matched = DevLimitMatchItem(&devLimit->accessList, &item);
}
if (!matched) {
return EPERM;
}
return LOS_OK;
}
#endif

View File

@@ -0,0 +1,96 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_DEVICELIMIT_H
#define _LOS_DEVICELIMIT_H
#include "los_typedef.h"
#include "los_list.h"
#include "vfs_config.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
#define DEVLIMIT_ACC_MKNOD 1
#define DEVLIMIT_ACC_READ 2
#define DEVLIMIT_ACC_WRITE 4
#define DEVLIMIT_ACC_MASK (DEVLIMIT_ACC_MKNOD | DEVLIMIT_ACC_READ | DEVLIMIT_ACC_WRITE)
#define DEVLIMIT_DEV_BLOCK 1
#define DEVLIMIT_DEV_CHAR 2
#define DEVLIMIT_DEV_ALL 4 /* all devices */
#define DEVLIMIT_ALLOW 1
#define DEVLIMIT_DENY 2
#define ACCLEN 4
struct SeqBuf;
typedef struct TagPLimiterSet ProcLimitSet;
enum DevLimitBehavior {
DEVLIMIT_DEFAULT_NONE,
DEVLIMIT_DEFAULT_ALLOW,
DEVLIMIT_DEFAULT_DENY,
};
typedef struct DevAccessItem {
INT16 type;
INT16 access;
LOS_DL_LIST list;
CHAR name[PATH_MAX];
} DevAccessItem;
typedef struct ProcDevLimit {
struct ProcDevLimit *parent;
UINT8 allowFile;
UINT8 denyFile;
LOS_DL_LIST accessList; // device belong to devicelimite
enum DevLimitBehavior behavior;
} ProcDevLimit;
VOID OsDevLimitInit(UINTPTR limit);
VOID *OsDevLimitAlloc(VOID);
VOID OsDevLimitFree(UINTPTR limit);
VOID OsDevLimitCopy(UINTPTR dest, UINTPTR src);
UINT32 OsDevLimitWriteAllow(ProcLimitSet *plimit, const CHAR *buf, UINT32 size);
UINT32 OsDevLimitWriteDeny(ProcLimitSet *plimit, const CHAR *buf, UINT32 size);
UINT32 OsDevLimitShow(ProcDevLimit *devLimit, struct SeqBuf *seqBuf);
UINT32 OsDevLimitCheckPermission(INT32 vnodeType, const CHAR *pathName, INT32 flags);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif /* _LOS_DEVICELIMIT_H */

View File

@@ -0,0 +1,249 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
#include "los_ipclimit.h"
#include "los_process_pri.h"
STATIC ProcIPCLimit *g_rootIPCLimit = NULL;
#define PLIMIT_IPC_SHM_LIMIT_MAX 0xFFFFFFFF
VOID OsIPCLimitInit(UINTPTR limite)
{
ProcIPCLimit *plimite = (ProcIPCLimit *)limite;
plimite->mqCountLimit = LOSCFG_BASE_IPC_QUEUE_LIMIT;
plimite->shmSizeLimit = PLIMIT_IPC_SHM_LIMIT_MAX;
g_rootIPCLimit = plimite;
}
VOID *OsIPCLimitAlloc(VOID)
{
ProcIPCLimit *plimite = (ProcIPCLimit *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcIPCLimit));
if (plimite == NULL) {
return NULL;
}
(VOID)memset_s(plimite, sizeof(ProcIPCLimit), 0, sizeof(ProcIPCLimit));
return (VOID *)plimite;
}
VOID OsIPCLimitFree(UINTPTR limite)
{
ProcIPCLimit *plimite = (ProcIPCLimit *)limite;
if (plimite == NULL) {
return;
}
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)plimite);
}
VOID OsIPCLimitCopy(UINTPTR dest, UINTPTR src)
{
ProcIPCLimit *plimiteDest = (ProcIPCLimit *)dest;
ProcIPCLimit *plimiteSrc = (ProcIPCLimit *)src;
plimiteDest->mqCountLimit = plimiteSrc->mqCountLimit;
plimiteDest->shmSizeLimit = plimiteSrc->shmSizeLimit;
return;
}
BOOL OsIPCLimiteMigrateCheck(UINTPTR curr, UINTPTR parent)
{
ProcIPCLimit *currIpcLimit = (ProcIPCLimit *)curr;
ProcIPCLimit *parentIpcLimit = (ProcIPCLimit *)parent;
if ((currIpcLimit->mqCount + parentIpcLimit->mqCount) >= parentIpcLimit->mqCountLimit) {
return FALSE;
}
if ((currIpcLimit->shmSize + parentIpcLimit->shmSize) >= parentIpcLimit->shmSizeLimit) {
return FALSE;
}
return TRUE;
}
VOID OsIPCLimitMigrate(UINTPTR currLimit, UINTPTR parentLimit, UINTPTR process)
{
ProcIPCLimit *currIpcLimit = (ProcIPCLimit *)currLimit;
ProcIPCLimit *parentIpcLimit = (ProcIPCLimit *)parentLimit;
LosProcessCB *pcb = (LosProcessCB *)process;
if (pcb == NULL) {
parentIpcLimit->mqCount += currIpcLimit->mqCount;
parentIpcLimit->mqFailedCount += currIpcLimit->mqFailedCount;
parentIpcLimit->shmSize += currIpcLimit->shmSize;
parentIpcLimit->shmFailedCount += currIpcLimit->shmFailedCount;
return;
}
parentIpcLimit->mqCount -= pcb->limitStat.mqCount;
parentIpcLimit->shmSize -= pcb->limitStat.shmSize;
currIpcLimit->mqCount += pcb->limitStat.mqCount;
currIpcLimit->shmSize += pcb->limitStat.shmSize;
}
BOOL OsIPCLimitAddProcessCheck(UINTPTR limit, UINTPTR process)
{
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)limit;
LosProcessCB *pcb = (LosProcessCB *)process;
if ((ipcLimit->mqCount + pcb->limitStat.mqCount) >= ipcLimit->mqCountLimit) {
return FALSE;
}
if ((ipcLimit->shmSize + pcb->limitStat.shmSize) >= ipcLimit->shmSizeLimit) {
return FALSE;
}
return TRUE;
}
VOID OsIPCLimitAddProcess(UINTPTR limit, UINTPTR process)
{
LosProcessCB *pcb = (LosProcessCB *)process;
ProcIPCLimit *plimits = (ProcIPCLimit *)limit;
plimits->mqCount += pcb->limitStat.mqCount;
plimits->shmSize += pcb->limitStat.shmSize;
return;
}
VOID OsIPCLimitDelProcess(UINTPTR limit, UINTPTR process)
{
LosProcessCB *pcb = (LosProcessCB *)process;
ProcIPCLimit *plimits = (ProcIPCLimit *)limit;
plimits->mqCount -= pcb->limitStat.mqCount;
plimits->shmSize -= pcb->limitStat.shmSize;
return;
}
UINT32 OsIPCLimitSetMqLimit(ProcIPCLimit *ipcLimit, UINT32 value)
{
UINT32 intSave;
if ((ipcLimit == NULL) || (value == 0) || (value > LOSCFG_BASE_IPC_QUEUE_LIMIT)) {
return EINVAL;
}
if (ipcLimit == g_rootIPCLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
if (value < ipcLimit->mqCount) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
ipcLimit->mqCountLimit = value;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsIPCLimitSetShmLimit(ProcIPCLimit *ipcLimit, UINT32 value)
{
UINT32 intSave;
if ((ipcLimit == NULL) || (value == 0) || (value > PLIMIT_IPC_SHM_LIMIT_MAX)) {
return EINVAL;
}
if (ipcLimit == g_rootIPCLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
if (value < ipcLimit->shmSize) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
ipcLimit->shmSizeLimit = value;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsIPCLimitMqAlloc(VOID)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
LosProcessCB *run = OsCurrProcessGet();
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_IPC];
if (ipcLimit->mqCount >= ipcLimit->mqCountLimit) {
ipcLimit->mqFailedCount++;
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
run->limitStat.mqCount++;
ipcLimit->mqCount++;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
VOID OsIPCLimitMqFree(VOID)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
LosProcessCB *run = OsCurrProcessGet();
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_IPC];
ipcLimit->mqCount--;
run->limitStat.mqCount--;
SCHEDULER_UNLOCK(intSave);
return;
}
UINT32 OsIPCLimitShmAlloc(UINT32 size)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
LosProcessCB *run = OsCurrProcessGet();
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_IPC];
if ((ipcLimit->shmSize + size) >= ipcLimit->shmSizeLimit) {
ipcLimit->shmFailedCount++;
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
run->limitStat.shmSize += size;
ipcLimit->shmSize += size;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
VOID OsIPCLimitShmFree(UINT32 size)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
LosProcessCB *run = OsCurrProcessGet();
ProcIPCLimit *ipcLimit = (ProcIPCLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_IPC];
ipcLimit->shmSize -= size;
run->limitStat.shmSize -= size;
SCHEDULER_UNLOCK(intSave);
return;
}
#endif

View File

@@ -0,0 +1,92 @@
/*
* Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_IPCLIMIT_H
#define _LOS_IPCLIMIT_H
#include "los_typedef.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
typedef struct ProcIPCLimit {
UINT32 mqCount;
UINT32 mqFailedCount;
UINT32 mqCountLimit;
UINT32 shmSize;
UINT32 shmFailedCount;
UINT32 shmSizeLimit;
} ProcIPCLimit;
enum IPCStatType {
IPC_STAT_TYPE_MQ = 0,
IPC_STAT_TYPE_SHM = 3,
IPC_STAT_TYPE_BUT // buttock
};
enum IPCStatOffset {
IPC_STAT_OFFSET_MQ = 0,
IPC_STAT_OFFSET_SHM = 3,
IPC_STAT_OFFSET_BUT // buttock
};
enum StatItem {
STAT_ITEM_TOTAL,
STAT_ITEM_FAILED,
STAT_ITEM_LIMIT,
STAT_ITEM_BUT // buttock
};
VOID OsIPCLimitInit(UINTPTR limite);
VOID *OsIPCLimitAlloc(VOID);
VOID OsIPCLimitFree(UINTPTR limite);
VOID OsIPCLimitCopy(UINTPTR dest, UINTPTR src);
BOOL OsIPCLimiteMigrateCheck(UINTPTR curr, UINTPTR parent);
VOID OsIPCLimitMigrate(UINTPTR currLimit, UINTPTR parentLimit, UINTPTR process);
BOOL OsIPCLimitAddProcessCheck(UINTPTR limit, UINTPTR process);
VOID OsIPCLimitAddProcess(UINTPTR limit, UINTPTR process);
VOID OsIPCLimitDelProcess(UINTPTR limit, UINTPTR process);
UINT32 OsIPCLimitSetMqLimit(ProcIPCLimit *ipcLimit, UINT32 value);
UINT32 OsIPCLimitSetShmLimit(ProcIPCLimit *ipcLimit, UINT32 value);
UINT32 OsIPCLimitMqAlloc(VOID);
VOID OsIPCLimitMqFree(VOID);
UINT32 OsIPCLimitShmAlloc(UINT32 size);
VOID OsIPCLimitShmFree(UINT32 size);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif /* _LOS_IPCIMIT_H */

View File

@@ -0,0 +1,223 @@
/*
* Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
#include <stdlib.h>
#include <securec.h>
#include "los_config.h"
#include "los_hook.h"
#include "los_process_pri.h"
#include "los_plimits.h"
STATIC ProcMemLimiter *g_procMemLimiter = NULL;
VOID OsMemLimiterInit(UINTPTR limite)
{
ProcMemLimiter *procMemLimiter = (ProcMemLimiter *)limite;
procMemLimiter->limit = OS_NULL_INT;
g_procMemLimiter = procMemLimiter;
}
VOID OsMemLimitSetLimit(UINT32 limit)
{
g_procMemLimiter->limit = limit;
}
VOID *OsMemLimiterAlloc(VOID)
{
ProcMemLimiter *plimite = (ProcMemLimiter *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcMemLimiter));
if (plimite == NULL) {
return NULL;
}
(VOID)memset_s(plimite, sizeof(ProcMemLimiter), 0, sizeof(ProcMemLimiter));
return (VOID *)plimite;
}
VOID OsMemLimiterFree(UINTPTR limite)
{
ProcMemLimiter *plimite = (ProcMemLimiter *)limite;
if (plimite == NULL) {
return;
}
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)limite);
}
VOID OsMemLimiterCopy(UINTPTR dest, UINTPTR src)
{
ProcMemLimiter *plimiteDest = (ProcMemLimiter *)dest;
ProcMemLimiter *plimiteSrc = (ProcMemLimiter *)src;
plimiteDest->limit = plimiteSrc->limit;
return;
}
BOOL MemLimiteMigrateCheck(UINTPTR curr, UINTPTR parent)
{
ProcMemLimiter *currMemLimit = (ProcMemLimiter *)curr;
ProcMemLimiter *parentMemLimit = (ProcMemLimiter *)parent;
if ((currMemLimit->usage + parentMemLimit->usage) >= parentMemLimit->limit) {
return FALSE;
}
return TRUE;
}
VOID OsMemLimiterMigrate(UINTPTR currLimit, UINTPTR parentLimit, UINTPTR process)
{
ProcMemLimiter *currMemLimit = (ProcMemLimiter *)currLimit;
ProcMemLimiter *parentMemLimit = (ProcMemLimiter *)parentLimit;
LosProcessCB *pcb = (LosProcessCB *)process;
if (pcb == NULL) {
parentMemLimit->usage += currMemLimit->usage;
parentMemLimit->failcnt += currMemLimit->failcnt;
if (parentMemLimit->peak < parentMemLimit->usage) {
parentMemLimit->peak = parentMemLimit->usage;
}
return;
}
parentMemLimit->usage -= pcb->limitStat.memUsed;
currMemLimit->usage += pcb->limitStat.memUsed;
}
BOOL OsMemLimitAddProcessCheck(UINTPTR limit, UINTPTR process)
{
ProcMemLimiter *memLimit = (ProcMemLimiter *)limit;
LosProcessCB *pcb = (LosProcessCB *)process;
if ((memLimit->usage + pcb->limitStat.memUsed) > memLimit->limit) {
return FALSE;
}
return TRUE;
}
VOID OsMemLimitAddProcess(UINTPTR limit, UINTPTR process)
{
LosProcessCB *pcb = (LosProcessCB *)process;
ProcMemLimiter *plimits = (ProcMemLimiter *)limit;
plimits->usage += pcb->limitStat.memUsed;
if (plimits->peak < plimits->usage) {
plimits->peak = plimits->usage;
}
return;
}
VOID OsMemLimitDelProcess(UINTPTR limit, UINTPTR process)
{
LosProcessCB *pcb = (LosProcessCB *)process;
ProcMemLimiter *plimits = (ProcMemLimiter *)limit;
plimits->usage -= pcb->limitStat.memUsed;
return;
}
UINT32 OsMemLimitSetMemLimit(ProcMemLimiter *memLimit, UINT64 value)
{
UINT32 intSave;
if ((memLimit == NULL) || (value == 0)) {
return EINVAL;
}
if (memLimit == g_procMemLimiter) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
if (value < memLimit->usage) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
memLimit->limit = value;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
#define MEM_LIMIT_LOCK(state, locked) do { \
if (SCHEDULER_HELD()) { \
locked = TRUE; \
} else { \
SCHEDULER_LOCK(state); \
} \
} while (0)
#define MEM_LIMIT_UNLOCK(state, locked) do { \
if (!locked) { \
SCHEDULER_UNLOCK(state); \
} \
} while (0)
UINT32 OsMemLimitCheckAndMemAdd(UINT32 size)
{
UINT32 intSave;
BOOL locked = FALSE;
MEM_LIMIT_LOCK(intSave, locked);
LosProcessCB *run = OsCurrProcessGet();
UINT32 currProcessID = run->processID;
if ((run == NULL) || (run->plimits == NULL)) {
MEM_LIMIT_UNLOCK(intSave, locked);
return LOS_OK;
}
ProcMemLimiter *memLimit = (ProcMemLimiter *)run->plimits->limitsList[PROCESS_LIMITER_ID_MEM];
if ((memLimit->usage + size) > memLimit->limit) {
memLimit->failcnt++;
MEM_LIMIT_UNLOCK(intSave, locked);
PRINT_ERR("plimits: process %u adjust the memory limit of Plimits group\n", currProcessID);
return ENOMEM;
}
memLimit->usage += size;
run->limitStat.memUsed += size;
if (memLimit->peak < memLimit->usage) {
memLimit->peak = memLimit->usage;
}
MEM_LIMIT_UNLOCK(intSave, locked);
return LOS_OK;
}
VOID OsMemLimitMemFree(UINT32 size)
{
UINT32 intSave;
BOOL locked = FALSE;
MEM_LIMIT_LOCK(intSave, locked);
LosProcessCB *run = OsCurrProcessGet();
if ((run == NULL) || (run->plimits == NULL)) {
MEM_LIMIT_UNLOCK(intSave, locked);
return;
}
ProcMemLimiter *memLimit = (ProcMemLimiter *)run->plimits->limitsList[PROCESS_LIMITER_ID_MEM];
if (run->limitStat.memUsed > size) {
run->limitStat.memUsed -= size;
memLimit->usage -= size;
}
MEM_LIMIT_UNLOCK(intSave, locked);
}
#endif

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_MEMLIMIT_H
#define _LOS_MEMLIMIT_H
#include "los_typedef.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
typedef struct ProcMemLimiter {
UINT64 usage;
UINT64 limit;
UINT64 peak;
UINT32 failcnt;
} ProcMemLimiter;
VOID OsMemLimiterInit(UINTPTR limite);
VOID *OsMemLimiterAlloc(VOID);
VOID OsMemLimiterFree(UINTPTR limite);
VOID OsMemLimiterCopy(UINTPTR dest, UINTPTR src);
BOOL MemLimiteMigrateCheck(UINTPTR curr, UINTPTR parent);
VOID OsMemLimiterMigrate(UINTPTR currLimit, UINTPTR parentLimit, UINTPTR process);
BOOL OsMemLimitAddProcessCheck(UINTPTR limit, UINTPTR process);
VOID OsMemLimitAddProcess(UINTPTR limit, UINTPTR process);
VOID OsMemLimitDelProcess(UINTPTR limit, UINTPTR process);
UINT32 OsMemLimitSetMemLimit(ProcMemLimiter *memLimit, UINT64 value);
VOID OsMemLimitSetLimit(UINTPTR limit);
UINT32 OsMemLimitCheckAndMemAdd(UINT32 size);
VOID OsMemLimitMemFree(UINT32 size);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif /* _LOS_MEMLIMIT_H */

View File

@@ -0,0 +1,434 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_PLIMITS
#include "los_base.h"
#include "los_process_pri.h"
#include "hal_timer.h"
#include "los_plimits.h"
typedef struct PlimiteOperations {
VOID (*LimiterInit)(UINTPTR);
VOID *(*LimiterAlloc)(VOID);
VOID (*LimiterFree)(UINTPTR);
VOID (*LimiterCopy)(UINTPTR, UINTPTR);
BOOL (*LimiterAddProcessCheck)(UINTPTR, UINTPTR);
VOID (*LimiterAddProcess)(UINTPTR, UINTPTR);
VOID (*LimiterDelProcess)(UINTPTR, UINTPTR);
BOOL (*LimiterMigrateCheck)(UINTPTR, UINTPTR);
VOID (*LimiterMigrate)(UINTPTR, UINTPTR, UINTPTR);
} PlimiteOperations;
static PlimiteOperations g_limiteOps[PROCESS_LIMITER_COUNT] = {
[PROCESS_LIMITER_ID_PIDS] = {
.LimiterInit = PidLimiterInit,
.LimiterAlloc = PidLimiterAlloc,
.LimiterFree = PidLimterFree,
.LimiterCopy = PidLimiterCopy,
.LimiterAddProcessCheck = OsPidLimitAddProcessCheck,
.LimiterAddProcess = OsPidLimitAddProcess,
.LimiterDelProcess = OsPidLimitDelProcess,
.LimiterMigrateCheck = PidLimitMigrateCheck,
.LimiterMigrate = NULL,
},
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
[PROCESS_LIMITER_ID_MEM] = {
.LimiterInit = OsMemLimiterInit,
.LimiterAlloc = OsMemLimiterAlloc,
.LimiterFree = OsMemLimiterFree,
.LimiterCopy = OsMemLimiterCopy,
.LimiterAddProcessCheck = OsMemLimitAddProcessCheck,
.LimiterAddProcess = OsMemLimitAddProcess,
.LimiterDelProcess = OsMemLimitDelProcess,
.LimiterMigrateCheck = MemLimiteMigrateCheck,
.LimiterMigrate = OsMemLimiterMigrate,
},
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
[PROCESS_LIMITER_ID_SCHED] = {
.LimiterInit = OsSchedLimitInit,
.LimiterAlloc = OsSchedLimitAlloc,
.LimiterFree = OsSchedLimitFree,
.LimiterCopy = OsSchedLimitCopy,
.LimiterAddProcessCheck = NULL,
.LimiterAddProcess = NULL,
.LimiterDelProcess = NULL,
.LimiterMigrateCheck = NULL,
.LimiterMigrate = NULL,
},
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
[PROCESS_LIMITER_ID_DEV] = {
.LimiterInit = OsDevLimitInit,
.LimiterAlloc = OsDevLimitAlloc,
.LimiterFree = OsDevLimitFree,
.LimiterCopy = OsDevLimitCopy,
.LimiterAddProcessCheck = NULL,
.LimiterAddProcess = NULL,
.LimiterDelProcess = NULL,
.LimiterMigrateCheck = NULL,
.LimiterMigrate = NULL,
},
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
[PROCESS_LIMITER_ID_IPC] = {
.LimiterInit = OsIPCLimitInit,
.LimiterAlloc = OsIPCLimitAlloc,
.LimiterFree = OsIPCLimitFree,
.LimiterCopy = OsIPCLimitCopy,
.LimiterAddProcessCheck = OsIPCLimitAddProcessCheck,
.LimiterAddProcess = OsIPCLimitAddProcess,
.LimiterDelProcess = OsIPCLimitDelProcess,
.LimiterMigrateCheck = OsIPCLimiteMigrateCheck,
.LimiterMigrate = OsIPCLimitMigrate,
},
#endif
};
STATIC ProcLimiterSet *g_rootPLimite = NULL;
ProcLimiterSet *OsRootPLimitsGet(VOID)
{
return g_rootPLimite;
}
UINT32 OsProcLimiterSetInit(VOID)
{
g_rootPLimite = (ProcLimiterSet *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcLimiterSet));
if (g_rootPLimite == NULL) {
return ENOMEM;
}
(VOID)memset_s(g_rootPLimite, sizeof(ProcLimiterSet), 0, sizeof(ProcLimiterSet));
LOS_ListInit(&g_rootPLimite->childList);
LOS_ListInit(&g_rootPLimite->processList);
ProcLimiterSet *procLimiterSet = g_rootPLimite;
for (INT32 plimiteID = 0; plimiteID < PROCESS_LIMITER_COUNT; ++plimiteID) {
procLimiterSet->limitsList[plimiteID] = (UINTPTR)g_limiteOps[plimiteID].LimiterAlloc();
if (procLimiterSet->limitsList[plimiteID] == (UINTPTR)NULL) {
OsPLimitsFree(procLimiterSet);
return ENOMEM;
}
if (g_limiteOps[plimiteID].LimiterInit != NULL) {
g_limiteOps[plimiteID].LimiterInit(procLimiterSet->limitsList[plimiteID]);
}
}
return LOS_OK;
}
STATIC VOID PLimitsDeleteProcess(LosProcessCB *processCB)
{
if ((processCB == NULL) || (processCB->plimits == NULL)) {
return;
}
ProcLimiterSet *plimits = processCB->plimits;
for (UINT32 limitsID = 0; limitsID < PROCESS_LIMITER_COUNT; limitsID++) {
if (g_limiteOps[limitsID].LimiterDelProcess == NULL) {
continue;
}
g_limiteOps[limitsID].LimiterDelProcess(plimits->limitsList[limitsID], (UINTPTR)processCB);
}
plimits->pidCount--;
LOS_ListDelete(&processCB->plimitsList);
processCB->plimits = NULL;
return;
}
STATIC UINT32 PLimitsAddProcess(ProcLimiterSet *plimits, LosProcessCB *processCB)
{
UINT32 limitsID;
if (plimits == NULL) {
plimits = g_rootPLimite;
}
if (processCB->plimits == g_rootPLimite) {
return EPERM;
}
if (processCB->plimits == plimits) {
return LOS_OK;
}
for (limitsID = 0; limitsID < PROCESS_LIMITER_COUNT; limitsID++) {
if (g_limiteOps[limitsID].LimiterAddProcessCheck == NULL) {
continue;
}
if (!g_limiteOps[limitsID].LimiterAddProcessCheck(plimits->limitsList[limitsID], (UINTPTR)processCB)) {
return EACCES;
}
}
PLimitsDeleteProcess(processCB);
for (limitsID = 0; limitsID < PROCESS_LIMITER_COUNT; limitsID++) {
if (g_limiteOps[limitsID].LimiterAddProcess == NULL) {
continue;
}
g_limiteOps[limitsID].LimiterAddProcess(plimits->limitsList[limitsID], (UINTPTR)processCB);
}
LOS_ListTailInsert(&plimits->processList, &processCB->plimitsList);
plimits->pidCount++;
processCB->plimits = plimits;
return LOS_OK;
}
UINT32 OsPLimitsAddProcess(ProcLimiterSet *plimits, LosProcessCB *processCB)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
UINT32 ret = PLimitsAddProcess(plimits, processCB);
SCHEDULER_UNLOCK(intSave);
return ret;
}
UINT32 OsPLimitsAddPid(ProcLimiterSet *plimits, UINT32 pid)
{
UINT32 intSave, ret;
if ((plimits == NULL) || OS_PID_CHECK_INVALID(pid) || (pid == 0)) {
return EINVAL;
}
if (plimits == g_rootPLimite) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
LosProcessCB *processCB = OS_PCB_FROM_PID((unsigned int)pid);
if (OsProcessIsInactive(processCB)) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
ret = PLimitsAddProcess(plimits, processCB);
SCHEDULER_UNLOCK(intSave);
return ret;
}
VOID OsPLimitsDeleteProcess(LosProcessCB *processCB)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
PLimitsDeleteProcess(processCB);
SCHEDULER_UNLOCK(intSave);
}
UINT32 OsPLimitsPidsGet(const ProcLimiterSet *plimits, UINT32 *pids, UINT32 size)
{
UINT32 intSave;
LosProcessCB *processCB = NULL;
UINT32 minSize = LOS_GetSystemProcessMaximum() * sizeof(UINT32);
if ((plimits == NULL) || (pids == NULL) || (size < minSize)) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
LOS_DL_LIST *listHead = (LOS_DL_LIST *)&plimits->processList;
if (LOS_ListEmpty(listHead)) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
LOS_DL_LIST_FOR_EACH_ENTRY(processCB, listHead, LosProcessCB, plimitsList) {
pids[OsGetPid(processCB)] = 1;
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
STATIC VOID PLimitsProcessMerge(ProcLimiterSet *currPLimits, ProcLimiterSet *parentPLimits)
{
LOS_DL_LIST *head = &currPLimits->processList;
while (!LOS_ListEmpty(head)) {
LosProcessCB *processCB = LOS_DL_LIST_ENTRY(head->pstNext, LosProcessCB, plimitsList);
PLimitsDeleteProcess(processCB);
PLimitsAddProcess(parentPLimits, processCB);
}
LOS_ListDelete(&currPLimits->childList);
currPLimits->parent = NULL;
return;
}
STATIC UINT32 PLimitsMigrateCheck(ProcLimiterSet *currPLimits, ProcLimiterSet *parentPLimits)
{
for (UINT32 limiteID = 0; limiteID < PROCESS_LIMITER_COUNT; limiteID++) {
UINTPTR currLimit = currPLimits->limitsList[limiteID];
UINTPTR parentLimit = parentPLimits->limitsList[limiteID];
if (g_limiteOps[limiteID].LimiterMigrateCheck == NULL) {
continue;
}
if (!g_limiteOps[limiteID].LimiterMigrateCheck(currLimit, parentLimit)) {
return EPERM;
}
}
return LOS_OK;
}
UINT32 OsPLimitsFree(ProcLimiterSet *currPLimits)
{
UINT32 intSave, ret;
if (currPLimits == NULL) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
ProcLimiterSet *parentPLimits = currPLimits->parent;
ret = PLimitsMigrateCheck(currPLimits, parentPLimits);
if (ret != LOS_OK) {
SCHEDULER_UNLOCK(intSave);
return ret;
}
PLimitsProcessMerge(currPLimits, parentPLimits);
SCHEDULER_UNLOCK(intSave);
for (INT32 limiteID = 0; limiteID < PROCESS_LIMITER_COUNT; ++limiteID) {
UINTPTR procLimiter = currPLimits->limitsList[limiteID];
if (g_limiteOps[limiteID].LimiterFree != NULL) {
g_limiteOps[limiteID].LimiterFree(procLimiter);
}
}
(VOID)LOS_MemFree(m_aucSysMem1, currPLimits);
return LOS_OK;
}
ProcLimiterSet *OsPLimitsCreate(ProcLimiterSet *parentPLimits)
{
UINT32 intSave;
ProcLimiterSet *newPLimits = (ProcLimiterSet *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcLimiterSet));
if (newPLimits == NULL) {
return NULL;
}
(VOID)memset_s(newPLimits, sizeof(ProcLimiterSet), 0, sizeof(ProcLimiterSet));
LOS_ListInit(&newPLimits->childList);
LOS_ListInit(&newPLimits->processList);
SCHEDULER_LOCK(intSave);
newPLimits->parent = parentPLimits;
newPLimits->level = parentPLimits->level + 1;
newPLimits->mask = parentPLimits->mask;
for (INT32 plimiteID = 0; plimiteID < PROCESS_LIMITER_COUNT; ++plimiteID) {
newPLimits->limitsList[plimiteID] = (UINTPTR)g_limiteOps[plimiteID].LimiterAlloc();
if (newPLimits->limitsList[plimiteID] == (UINTPTR)NULL) {
SCHEDULER_UNLOCK(intSave);
OsPLimitsFree(newPLimits);
return NULL;
}
if (g_limiteOps[plimiteID].LimiterCopy != NULL) {
g_limiteOps[plimiteID].LimiterCopy(newPLimits->limitsList[plimiteID],
parentPLimits->limitsList[plimiteID]);
}
}
LOS_ListTailInsert(&g_rootPLimite->childList, &newPLimits->childList);
(VOID)PLimitsDeleteProcess(OsCurrProcessGet());
(VOID)PLimitsAddProcess(newPLimits, OsCurrProcessGet());
SCHEDULER_UNLOCK(intSave);
return newPLimits;
}
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
UINT32 OsPLimitsMemUsageGet(ProcLimiterSet *plimits, UINT64 *usage, UINT32 size)
{
UINT32 intSave;
LosProcessCB *processCB = NULL;
UINT32 minSize = LOS_GetSystemProcessMaximum() * sizeof(UINT64) + sizeof(ProcMemLimiter);
ProcMemLimiter *memLimit = (ProcMemLimiter *)usage;
UINT64 *memSuage = (UINT64 *)((UINTPTR)usage + sizeof(ProcMemLimiter));
if ((plimits == NULL) || (usage == NULL) || (size < minSize)) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
(VOID)memcpy_s(memLimit, sizeof(ProcMemLimiter),
(VOID *)plimits->limitsList[PROCESS_LIMITER_ID_MEM], sizeof(ProcMemLimiter));
LOS_DL_LIST *listHead = (LOS_DL_LIST *)&plimits->processList;
if (LOS_ListEmpty(listHead)) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
LOS_DL_LIST_FOR_EACH_ENTRY(processCB, listHead, LosProcessCB, plimitsList) {
memSuage[OsGetPid(processCB)] = processCB->limitStat.memUsed;
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
UINT32 OsPLimitsIPCStatGet(ProcLimiterSet *plimits, ProcIPCLimit *ipc, UINT32 size)
{
UINT32 intSave;
if ((plimits == NULL) || (ipc == NULL) || (size != sizeof(ProcIPCLimit))) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
(VOID)memcpy_s(ipc, sizeof(ProcIPCLimit),
(VOID *)plimits->limitsList[PROCESS_LIMITER_ID_IPC], sizeof(ProcIPCLimit));
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
UINT32 OsPLimitsSchedUsageGet(ProcLimiterSet *plimits, UINT64 *usage, UINT32 size)
{
UINT32 intSave;
LosProcessCB *processCB = NULL;
UINT32 minSize = LOS_GetSystemProcessMaximum() * sizeof(UINT64);
if ((plimits == NULL) || (usage == NULL) || (size < minSize)) {
return EINVAL;
}
SCHEDULER_LOCK(intSave);
LOS_DL_LIST *listHead = (LOS_DL_LIST *)&plimits->processList;
if (LOS_ListEmpty(listHead)) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
LOS_DL_LIST_FOR_EACH_ENTRY(processCB, listHead, LosProcessCB, plimitsList) {
usage[OsGetPid(processCB)] = processCB->limitStat.allRuntime;
}
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
#endif
#endif

View File

@@ -0,0 +1,114 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_PLIMITS_H
#define _LOS_PLIMITS_H
#include "los_list.h"
#include "los_typedef.h"
#include "los_processlimit.h"
#include "los_memlimit.h"
#include "los_ipclimit.h"
#include "los_devicelimit.h"
#include "los_schedlimit.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
/* proc limit set lock */
#define PLIMITS_MIN_PERIOD_IN_US 1000000
#define PLIMITS_MIN_QUOTA_IN_US 1
#define PLIMITS_DELETE_WAIT_TIME 1000
typedef struct ProcessCB LosProcessCB;
enum ProcLimiterID {
PROCESS_LIMITER_ID_PIDS = 0,
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
PROCESS_LIMITER_ID_MEM,
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
PROCESS_LIMITER_ID_SCHED,
#endif
#ifdef LOSCFG_KERNEL_DEV_PLIMIT
PROCESS_LIMITER_ID_DEV,
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
PROCESS_LIMITER_ID_IPC,
#endif
PROCESS_LIMITER_COUNT,
};
typedef struct {
#ifdef LOSCFG_KERNEL_MEM_PLIMIT
UINT64 memUsed;
#endif
#ifdef LOSCFG_KERNEL_IPC_PLIMIT
UINT32 mqCount;
UINT32 shmSize;
#endif
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
UINT64 allRuntime;
#endif
} PLimitsData;
typedef struct TagPLimiterSet {
struct TagPLimiterSet *parent; /* plimite parent */
LOS_DL_LIST childList; /* plimite childList */
LOS_DL_LIST processList;
UINT32 pidCount;
UINTPTR limitsList[PROCESS_LIMITER_COUNT]; /* plimite list */
UINT32 mask; /* each bit indicates that a limite exists */
UINT8 level; /* plimits hierarchy level */
} ProcLimiterSet;
typedef struct ProcessCB LosProcessCB;
ProcLimiterSet *OsRootPLimitsGet(VOID);
UINT32 OsPLimitsAddProcess(ProcLimiterSet *plimits, LosProcessCB *processCB);
UINT32 OsPLimitsAddPid(ProcLimiterSet *plimits, UINT32 pid);
VOID OsPLimitsDeleteProcess(LosProcessCB *processCB);
UINT32 OsPLimitsPidsGet(const ProcLimiterSet *plimits, UINT32 *pids, UINT32 size);
UINT32 OsPLimitsFree(ProcLimiterSet *currPLimits);
ProcLimiterSet *OsPLimitsCreate(ProcLimiterSet *parentProcLimiterSet);
UINT32 OsProcLimiterSetInit(VOID);
UINT32 OsPLimitsMemUsageGet(ProcLimiterSet *plimits, UINT64 *usage, UINT32 size);
UINT32 OsPLimitsIPCStatGet(ProcLimiterSet *plimits, ProcIPCLimit *ipc, UINT32 size);
UINT32 OsPLimitsSchedUsageGet(ProcLimiterSet *plimits, UINT64 *usage, UINT32 size);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif /* _LOS_PLIMITS_H */

View File

@@ -0,0 +1,182 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_PLIMITS
#include "los_config.h"
#include "los_process_pri.h"
#include "los_process.h"
#include "los_plimits.h"
#include "los_task_pri.h"
#include "los_processlimit.h"
STATIC PidLimit *g_rootPidLimit = NULL;
VOID PidLimiterInit(UINTPTR limit)
{
PidLimit *pidLimit = (PidLimit *)limit;
if (pidLimit == NULL) {
return;
}
pidLimit->pidLimit = LOS_GetSystemProcessMaximum();
pidLimit->priorityLimit = OS_USER_PROCESS_PRIORITY_HIGHEST;
g_rootPidLimit = pidLimit;
}
VOID *PidLimiterAlloc(VOID)
{
PidLimit *plimite = (PidLimit *)LOS_MemAlloc(m_aucSysMem1, sizeof(PidLimit));
if (plimite == NULL) {
return NULL;
}
(VOID)memset_s(plimite, sizeof(PidLimit), 0, sizeof(PidLimit));
return (VOID *)plimite;
}
VOID PidLimterFree(UINTPTR limit)
{
PidLimit *pidLimit = (PidLimit *)limit;
if (pidLimit == NULL) {
return;
}
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)limit);
}
BOOL PidLimitMigrateCheck(UINTPTR curr, UINTPTR parent)
{
PidLimit *currPidLimit = (PidLimit *)curr;
PidLimit *parentPidLimit = (PidLimit *)parent;
if ((currPidLimit == NULL) || (parentPidLimit == NULL)) {
return FALSE;
}
if ((currPidLimit->pidCount + parentPidLimit->pidCount) >= parentPidLimit->pidLimit) {
return FALSE;
}
return TRUE;
}
BOOL OsPidLimitAddProcessCheck(UINTPTR limit, UINTPTR process)
{
(VOID)process;
PidLimit *pidLimit = (PidLimit *)limit;
if (pidLimit->pidCount >= pidLimit->pidLimit) {
return FALSE;
}
return TRUE;
}
VOID OsPidLimitAddProcess(UINTPTR limit, UINTPTR process)
{
(VOID)process;
PidLimit *plimits = (PidLimit *)limit;
plimits->pidCount++;
return;
}
VOID OsPidLimitDelProcess(UINTPTR limit, UINTPTR process)
{
(VOID)process;
PidLimit *plimits = (PidLimit *)limit;
plimits->pidCount--;
return;
}
VOID PidLimiterCopy(UINTPTR curr, UINTPTR parent)
{
PidLimit *currPidLimit = (PidLimit *)curr;
PidLimit *parentPidLimit = (PidLimit *)parent;
if ((currPidLimit == NULL) || (parentPidLimit == NULL)) {
return;
}
currPidLimit->pidLimit = parentPidLimit->pidLimit;
currPidLimit->priorityLimit = parentPidLimit->priorityLimit;
currPidLimit->pidCount = 0;
return;
}
UINT32 PidLimitSetPidLimit(PidLimit *pidLimit, UINT32 pidMax)
{
UINT32 intSave;
if ((pidLimit == NULL) || (pidMax > LOS_GetSystemProcessMaximum())) {
return EINVAL;
}
if (pidLimit == g_rootPidLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
if (pidLimit->pidCount >= pidMax) {
SCHEDULER_UNLOCK(intSave);
return EPERM;
}
pidLimit->pidLimit = pidMax;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 PidLimitSetPriorityLimit(PidLimit *pidLimit, UINT32 priority)
{
UINT32 intSave;
if ((pidLimit == NULL) ||
(priority < OS_USER_PROCESS_PRIORITY_HIGHEST) ||
(priority > OS_PROCESS_PRIORITY_LOWEST)) {
return EINVAL;
}
if (pidLimit == g_rootPidLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
pidLimit->priorityLimit = priority;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT16 OsPidLimitGetPriorityLimit(VOID)
{
UINT32 intSave;
SCHEDULER_LOCK(intSave);
LosProcessCB *run = OsCurrProcessGet();
PidLimit *pidLimit = (PidLimit *)run->plimits->limitsList[PROCESS_LIMITER_ID_PIDS];
UINT16 priority = pidLimit->priorityLimit;
SCHEDULER_UNLOCK(intSave);
return priority;
}
#endif

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_PROCESSLIMIT_H
#define _LOS_PROCESSLIMIT_H
#include "los_list.h"
#include "los_typedef.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
typedef struct PidLimit {
UINT32 pidLimit;
UINT32 priorityLimit;
UINT32 pidCount;
} PidLimit;
VOID PidLimiterInit(UINTPTR limit);
VOID *PidLimiterAlloc(VOID);
VOID PidLimterFree(UINTPTR limit);
VOID PidLimiterCopy(UINTPTR curr, UINTPTR parent);
BOOL PidLimitMigrateCheck(UINTPTR curr, UINTPTR parent);
BOOL OsPidLimitAddProcessCheck(UINTPTR limit, UINTPTR process);
VOID OsPidLimitAddProcess(UINTPTR limit, UINTPTR process);
VOID OsPidLimitDelProcess(UINTPTR limit, UINTPTR process);
UINT32 PidLimitSetPidLimit(PidLimit *pidLimit, UINT32 pidMax);
UINT32 PidLimitSetPriorityLimit(PidLimit *pidLimit, UINT32 priority);
UINT16 OsPidLimitGetPriorityLimit(VOID);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif

View File

@@ -0,0 +1,151 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifdef LOSCFG_KERNEL_SCHED_PLIMIT
#include "los_schedlimit.h"
#include "los_process_pri.h"
STATIC ProcSchedLimiter *g_procSchedLimit = NULL;
VOID OsSchedLimitInit(UINTPTR limit)
{
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)limit;
schedLimit->period = 0;
schedLimit->quota = 0;
g_procSchedLimit = schedLimit;
}
VOID *OsSchedLimitAlloc(VOID)
{
ProcSchedLimiter *plimit = (ProcSchedLimiter *)LOS_MemAlloc(m_aucSysMem1, sizeof(ProcSchedLimiter));
if (plimit == NULL) {
return NULL;
}
(VOID)memset_s(plimit, sizeof(ProcSchedLimiter), 0, sizeof(ProcSchedLimiter));
return (VOID *)plimit;
}
VOID OsSchedLimitFree(UINTPTR limit)
{
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)limit;
if (schedLimit == NULL) {
return;
}
(VOID)LOS_MemFree(m_aucSysMem1, (VOID *)limit);
}
VOID OsSchedLimitCopy(UINTPTR dest, UINTPTR src)
{
ProcSchedLimiter *plimitDest = (ProcSchedLimiter *)dest;
ProcSchedLimiter *plimitSrc = (ProcSchedLimiter *)src;
plimitDest->period = plimitSrc->period;
plimitDest->quota = plimitSrc->quota;
return;
}
VOID OsSchedLimitUpdateRuntime(LosTaskCB *runTask, UINT64 currTime, INT32 incTime)
{
LosProcessCB *run = (LosProcessCB *)runTask->processCB;
if ((run == NULL) || (run->plimits == NULL)) {
return;
}
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)run->plimits->limitsList[PROCESS_LIMITER_ID_SCHED];
run->limitStat.allRuntime += incTime;
if ((schedLimit->period <= 0) || (schedLimit->quota <= 0)) {
return;
}
if ((schedLimit->startTime <= currTime) && (schedLimit->allRuntime < schedLimit->quota)) {
schedLimit->allRuntime += incTime;
return;
}
if (schedLimit->startTime <= currTime) {
schedLimit->startTime = currTime + schedLimit->period;
schedLimit->allRuntime = 0;
}
}
BOOL OsSchedLimitCheckTime(LosTaskCB *task)
{
UINT64 currTime = OsGetCurrSchedTimeCycle();
LosProcessCB *processCB = (LosProcessCB *)task->processCB;
if ((processCB == NULL) || (processCB->plimits == NULL)) {
return TRUE;
}
ProcSchedLimiter *schedLimit = (ProcSchedLimiter *)processCB->plimits->limitsList[PROCESS_LIMITER_ID_SCHED];
if (schedLimit->startTime >= currTime) {
return FALSE;
}
return TRUE;
}
UINT32 OsSchedLimitSetPeriod(ProcSchedLimiter *schedLimit, UINT64 value)
{
UINT32 intSave;
if (schedLimit == NULL) {
return EINVAL;
}
if (schedLimit == g_procSchedLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
schedLimit->period = value;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
UINT32 OsSchedLimitSetQuota(ProcSchedLimiter *schedLimit, UINT64 value)
{
UINT32 intSave;
if (schedLimit == NULL) {
return EINVAL;
}
if (schedLimit == g_procSchedLimit) {
return EPERM;
}
SCHEDULER_LOCK(intSave);
if (value > (UINT64)schedLimit->period) {
SCHEDULER_UNLOCK(intSave);
return EINVAL;
}
schedLimit->quota = value;
SCHEDULER_UNLOCK(intSave);
return LOS_OK;
}
#endif

View File

@@ -0,0 +1,68 @@
/*
* Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LOS_SCHEDLIMIT_H
#define _LOS_SCHEDLIMIT_H
#include "los_typedef.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
#define CORE_US_PER_SECOND (1000 * 1000) /* 1000 * 1000 us per second */
typedef struct TagTaskCB LosTaskCB;
typedef struct ProcSchedLimiter {
UINT64 startTime;
UINT64 endTime;
UINT64 period;
UINT64 quota;
UINT64 allRuntime;
} ProcSchedLimiter;
VOID OsSchedLimitInit(UINTPTR limit);
VOID *OsSchedLimitAlloc(VOID);
VOID OsSchedLimitFree(UINTPTR limit);
VOID OsSchedLimitCopy(UINTPTR dest, UINTPTR src);
VOID OsSchedLimitUpdateRuntime(LosTaskCB *runTask, UINT64 currTime, INT32 incTime);
UINT32 OsSchedLimitSetPeriod(ProcSchedLimiter *schedLimit, UINT64 value);
UINT32 OsSchedLimitSetQuota(ProcSchedLimiter *schedLimit, UINT64 value);
BOOL OsSchedLimitCheckTime(LosTaskCB *task);
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
#endif /* _LOS_SCHEDLIMIT_H */

View File

@@ -273,7 +273,9 @@ int print_netif(struct netif *netif, char *print_buf, unsigned int buf_len)
#if LWIP_IPV6
char *addr = NULL;
#endif
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_net_group_from_netif(netif);
#endif
if (buf_len < 1) {
goto out;
}
@@ -348,7 +350,11 @@ int print_netif(struct netif *netif, char *print_buf, unsigned int buf_len)
tmp += ret;
buf_len -= (unsigned int)ret;
#ifdef LOSCFG_NET_CONTAINER
if ((group->netif_default == netif) && (netif_is_up(netif))) {
#else
if (netif_default == netif && netif_is_up(netif)) {
#endif
ret = snprintf_s(tmp, buf_len, (buf_len - 1), " %s", "Default");
if ((ret <= 0) || ((unsigned int)ret >= buf_len))
goto out;
@@ -432,8 +438,12 @@ void lwip_ifconfig_show_internal(void *arg)
struct netif *netif = NULL;
struct ifconfig_option *ifconfig_cmd = (struct ifconfig_option *)arg;
int ret;
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_curr_process_net_group();
if (group->netif_list == NULL) {
#else
if (netif_list == NULL) {
#endif
ret = snprintf_s(ifconfig_cmd->cb_print_buf, PRINT_BUF_LEN - ifconfig_cmd->print_len,
((PRINT_BUF_LEN - ifconfig_cmd->print_len) - 1), "Device not init\n");
if ((ret > 0) && ((unsigned int)ret < (PRINT_BUF_LEN - ifconfig_cmd->print_len))) {
@@ -445,7 +455,11 @@ void lwip_ifconfig_show_internal(void *arg)
if (ifconfig_cmd->iface[0] == '\0') {
/* display all netif */
#ifdef LOSCFG_NET_CONTAINER
for (netif = group->netif_list; netif != NULL; netif = netif->next) {
#else
for (netif = netif_list; netif != NULL; netif = netif->next) {
#endif
ret = print_netif(netif, ifconfig_cmd->cb_print_buf + ifconfig_cmd->print_len,
PRINT_BUF_LEN - ifconfig_cmd->print_len);
ifconfig_cmd->print_len += (unsigned int)ret;
@@ -486,7 +500,9 @@ void lwip_ifconfig_internal(void *arg)
int ret;
s8_t idx;
err_t err;
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_curr_process_net_group();
#endif
ifconfig_cmd = (struct ifconfig_option *)arg;
netif = netif_find(ifconfig_cmd->iface);
if (netif == NULL) {
@@ -521,13 +537,22 @@ void lwip_ifconfig_internal(void *arg)
/* reset gateway if new and previous ipaddr not in same net */
if (!ip_addr_netcmp_val(&ip_addr, &netif->ip_addr, ip_2_ip4(&netif->netmask))) {
ip_addr_set_zero(&netif->gw);
#ifdef LOSCFG_NET_CONTAINER
if (netif == group->netif_default) {
(void)netif_set_default(NULL, group);
#else
if (netif == netif_default) {
(void)netif_set_default(NULL);
#endif
}
}
/* lwip disallow two netif sit in same net at the same time */
#ifdef LOSCFG_NET_CONTAINER
loc_netif = group->netif_list;
#else
loc_netif = netif_list;
#endif
while (loc_netif != NULL) {
if (loc_netif == netif) {
loc_netif = loc_netif->next;
@@ -577,7 +602,11 @@ void lwip_ifconfig_internal(void *arg)
#endif
if (netif_ip4_netmask(netif)->addr != ip_2_ip4(&netmask)->addr) {
/* lwip disallow two netif sit in same net at the same time */
#ifdef LOSCFG_NET_CONTAINER
loc_netif = group->netif_list;
#else
loc_netif = netif_list;
#endif
while (loc_netif != NULL) {
if (loc_netif == netif) {
loc_netif = loc_netif->next;
@@ -594,8 +623,13 @@ void lwip_ifconfig_internal(void *arg)
/* check if gateway still reachable */
if (!ip_addr_netcmp(&netif->gw, &netif->ip_addr, ip_2_ip4(&netmask))) {
ip_addr_set_zero(&(netif->gw));
#ifdef LOSCFG_NET_CONTAINER
if (netif == group->netif_default) {
(void)netif_set_default(NULL, group);
#else
if (netif == netif_default) {
(void)netif_set_default(NULL);
#endif
}
}
}
@@ -630,9 +664,15 @@ void lwip_ifconfig_internal(void *arg)
goto out;
}
#ifdef LOSCFG_NET_CONTAINER
if (group->netif_default != netif) {
ip_addr_set_zero(&netif->gw);
(void)netif_set_default(netif, group);
#else
if (netif_default != netif) {
ip_addr_set_zero(&netif->gw);
(void)netif_set_default(netif);
#endif
}
#if LWIP_DHCP
@@ -1255,7 +1295,9 @@ void lwip_arp_internal(void *arg)
ip4_addr_t ipaddr;
err_t ret = 0;
int type = 0;
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_curr_process_net_group();
#endif
if (arp_cmd->iface[0] == 'd' && arp_cmd->iface[1] == 'e') {
netif = NULL;
} else {
@@ -1302,7 +1344,11 @@ void lwip_arp_internal(void *arg)
if (netif != NULL) {
ret = etharp_delete_arp_entry(netif, &ipaddr);
} else {
#ifdef LOSCFG_NET_CONTAINER
for (netif = group->netif_list; netif != NULL; netif = netif->next) {
#else
for (netif = netif_list; netif != NULL; netif = netif->next) {
#endif
ret = etharp_delete_arp_entry(netif, &ipaddr);
if (ret == ERR_OK) {
/* only can del success one time */

View File

@@ -202,7 +202,11 @@ void netifapi_netif_rmv_ip6_address(struct netif *netif, ip_addr_t *ipaddr)
(void)err;
}
#ifdef LOSCFG_NET_CONTAINER
static struct netif *netif_find_by_name(const char *name, struct net_group *group)
#else
static struct netif *netif_find_by_name(const char *name)
#endif
{
struct netif *netif = NULL;
@@ -212,7 +216,11 @@ static struct netif *netif_find_by_name(const char *name)
return NULL;
}
#ifdef LOSCFG_NET_CONTAINER
NETIF_FOREACH(netif, group) {
#else
NETIF_FOREACH(netif) {
#endif
if (strcmp("lo", name) == 0 && (netif->name[0] == 'l' && netif->name[1] == 'o')) {
LWIP_DEBUGF(NETIF_DEBUG, ("netif_find_by_name: found lo\n"));
return netif;
@@ -234,7 +242,12 @@ static err_t netifapi_do_find_by_name(struct tcpip_api_call_data *m)
* We know it works because the structs have been instantiated as struct netifapi_msg */
struct netifapi_msg *msg = (struct netifapi_msg *)(void *)m;
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_curr_process_net_group();
msg->netif = netif_find_by_name(msg->msg.ifs.name, group);
#else
msg->netif = netif_find_by_name(msg->msg.ifs.name);
#endif
return ERR_OK;
}
@@ -341,7 +354,6 @@ err_t etharp_delete_arp_entry(struct netif *netif, ip4_addr_t *ipaddr)
return 0;
}
err_t lwip_dns_setserver(u8_t numdns, ip_addr_t *dnsserver)
{
(void)numdns;

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#ifndef _LWIP_PORTING_IP_H_
#define _LWIP_PORTING_IP_H_
#define IP_PCB_NETGROUP ;struct net_group *group
#include_next <lwip/ip.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* _LWIP_PORTING_IP_H_ */

View File

@@ -41,12 +41,27 @@
#define LWIP_NETIF_CLIENT_DATA_INDEX_DHCP LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, \
LWIP_NETIF_CLIENT_DATA_INDEX_DHCPS
#endif
#ifdef LOSCFG_NET_CONTAINER
#include "lwip/net_group.h"
#define VETH_DRIVER_IF 2
void veth_init(struct netif *netif, struct net_group *group);
#define linkoutput linkoutput; \
void (*drv_send)(struct netif *netif, struct pbuf *p); \
u8_t (*drv_set_hwaddr)(struct netif *netif, u8_t *addr, u8_t len); \
void (*drv_config)(struct netif *netif, u32_t config_flags, u8_t setBit); \
char full_name[IFNAMSIZ]; \
struct net_group *group; \
struct netif *peer; \
u16_t link_layer_type
#else
#define linkoutput linkoutput; \
void (*drv_send)(struct netif *netif, struct pbuf *p); \
u8_t (*drv_set_hwaddr)(struct netif *netif, u8_t *addr, u8_t len); \
void (*drv_config)(struct netif *netif, u32_t config_flags, u8_t setBit); \
char full_name[IFNAMSIZ]; \
u16_t link_layer_type
#endif
#include_next <lwip/netif.h>
#undef linkoutput
#if LWIP_DHCPS

View File

@@ -35,6 +35,9 @@
#include <lwip/etharp.h>
#include <lwip/sockets.h>
#include <lwip/ethip6.h>
#ifdef LOSCFG_NET_CONTAINER
#include <lwip/tcpip.h>
#endif
#define LWIP_NETIF_HOSTNAME_DEFAULT "default"
#define LINK_SPEED_OF_YOUR_NETIF_IN_BPS 100000000 // 100Mbps
@@ -62,7 +65,11 @@ driverif_init_ifname(struct netif *netif)
"%s%d", prefix, i) < 0) {
break;
}
#ifdef LOSCFG_NET_CONTAINER
NETIF_FOREACH(tmpnetif, get_net_group_from_netif(netif)) {
#else
NETIF_FOREACH(tmpnetif) {
#endif
if (strcmp(tmpnetif->full_name, netif->full_name) == 0) {
break;
}
@@ -314,3 +321,60 @@ driverif_init(struct netif *netif)
LWIP_DEBUGF(DRIVERIF_DEBUG, ("driverif_init : Initialized netif 0x%p\n", (void *)netif));
return ERR_OK;
}
#ifdef LOSCFG_NET_CONTAINER
static err_t netif_veth_output(struct netif *netif, struct pbuf *p, const ip4_addr_t *addr)
{
LWIP_UNUSED_ARG(addr);
return netif_loop_output(netif->peer, p);
}
static void veth_init_fullname(struct netif *netif)
{
struct netif *tmpnetif = NULL;
for (int i = 0; i < LWIP_NETIF_IFINDEX_MAX_EX; ++i) {
if (snprintf_s(netif->full_name, sizeof(netif->full_name), sizeof(netif->full_name) - 1,
"%s%d", "veth", i) < 0) {
break;
}
NETIF_FOREACH(tmpnetif, get_net_group_from_netif(netif)) {
if (strcmp(tmpnetif->full_name, netif->full_name) == 0) {
break;
}
}
if (tmpnetif == NULL) {
return;
}
}
netif->full_name[0] = '\0';
}
static err_t netif_vethif_init(struct netif *netif)
{
LWIP_ASSERT("netif_vethif_init: invalid netif", netif != NULL);
/* initialize the snmp variables and counters inside the struct netif
* ifSpeed: no assumption can be made!
*/
MIB2_INIT_NETIF(netif, snmp_ifType_other, 0);
netif->link_layer_type = VETH_DRIVER_IF;
netif->name[0] = 'v';
netif->name[1] = 'e';
veth_init_fullname(netif);
netif->output = netif_veth_output;
netif_set_flags(netif, NETIF_FLAG_IGMP);
NETIF_SET_CHECKSUM_CTRL(netif, NETIF_CHECKSUM_DISABLE_ALL);
return ERR_OK;
}
void veth_init(struct netif *netif, struct net_group *group)
{
netif_add_noaddr(netif, group, NULL, netif_vethif_init, tcpip_input);
netif_set_link_up(netif);
netif_set_up(netif);
}
#endif

View File

@@ -404,7 +404,11 @@ int get_unused_socket_num(void)
#include <net/route.h>
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCADDRT(struct rtentry *rmten, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCADDRT(struct rtentry *rmten)
#endif
{
struct netif *netif = NULL;
ip_addr_t rtgw_addr;
@@ -429,7 +433,11 @@ static u8_t lwip_ioctl_internal_SIOCADDRT(struct rtentry *rmten)
}
/* check if reachable */
#ifdef LOSCFG_NET_CONTAINER
for (netif = group->netif_list; netif != NULL; netif = netif->next) {
#else
for (netif = netif_list; netif != NULL; netif = netif->next) {
#endif
if (ip_addr_netcmp(&rtgw_addr, &netif->ip_addr, ip_2_ip4(&netif->netmask))) {
break;
}
@@ -450,9 +458,15 @@ static u8_t lwip_ioctl_internal_SIOCADDRT(struct rtentry *rmten)
}
/* Add validation */
#ifdef LOSCFG_NET_CONTAINER
if ((group->netif_default != NULL) && (group->netif_default != netif)) {
ip_addr_set_zero(&group->netif_default->gw);
(void)netif_set_default(netif, group);
#else
if ((netif_default != NULL) && (netif_default != netif)) {
ip_addr_set_zero(&netif_default->gw);
(void)netif_set_default(netif);
#endif
}
netif_set_gw(netif, ip_2_ip4(&rtgw_addr));
@@ -462,8 +476,11 @@ static u8_t lwip_ioctl_internal_SIOCADDRT(struct rtentry *rmten)
#endif
#if LWIP_IOCTL_IF
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCGIFCONF(struct ifreq *ifr, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCGIFCONF(struct ifreq *ifr)
#endif
{
struct ifconf *ifc = NULL;
struct netif *netif = NULL;
@@ -479,7 +496,11 @@ static u8_t lwip_ioctl_internal_SIOCGIFCONF(struct ifreq *ifr)
/* Loop over the interfaces, and write an info block for each. */
pos = 0;
#ifdef LOSCFG_NET_CONTAINER
for (netif = group->netif_list; netif != NULL; netif = netif->next) {
#else
for (netif = netif_list; netif != NULL; netif = netif->next) {
#endif
if (ifc->ifc_buf == NULL) {
pos = (pos + (int)sizeof(struct ifreq));
continue;
@@ -554,7 +575,11 @@ static u8_t lwip_ioctl_internal_SIOCSIFADDR_6(struct ifreq *ifr)
return ENOSYS;
}
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCSIFADDR(struct ifreq *ifr, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCSIFADDR(struct ifreq *ifr)
#endif
{
struct netif *netif = NULL;
@@ -591,13 +616,22 @@ static u8_t lwip_ioctl_internal_SIOCSIFADDR(struct ifreq *ifr)
/* reset gateway if new and previous ipaddr not in same net */
if (ip_addr_netcmp(&taget_addr, &netif->ip_addr, ip_2_ip4(&netif->netmask)) == 0) {
ip_addr_set_zero(&netif->gw);
#ifdef LOSCFG_NET_CONTAINER
if (netif == group->netif_default) {
(void)netif_set_default(NULL, group);
#else
if (netif == netif_default) {
(void)netif_set_default(NULL);
#endif
}
}
/* lwip disallow two netif sit in same net at the same time */
#ifdef LOSCFG_NET_CONTAINER
loc_netif = group->netif_list;
#else
loc_netif = netif_list;
#endif
while (loc_netif != NULL) {
if (loc_netif == netif) {
loc_netif = loc_netif->next;
@@ -637,7 +671,11 @@ static u8_t lwip_ioctl_internal_SIOCDIFADDR_6(struct ifreq *ifr)
return ENOSYS;
}
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCDIFADDR(struct ifreq *ifr, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCDIFADDR(struct ifreq *ifr)
#endif
{
struct netif *netif = NULL;
@@ -678,8 +716,13 @@ static u8_t lwip_ioctl_internal_SIOCDIFADDR(struct ifreq *ifr)
ip_addr_set_zero(&netif->gw);
ip_addr_set_zero(&netif->ip_addr);
ip_addr_set_zero(&netif->netmask);
#ifdef LOSCFG_NET_CONTAINER
if (netif == group->netif_default) {
(void)netif_set_default(NULL, group);
#else
if (netif == netif_default) {
(void)netif_set_default(NULL);
#endif
}
#if LWIP_IPV4 && LWIP_ARP
@@ -708,7 +751,11 @@ static u8_t lwip_ioctl_internal_SIOCGIFNETMASK(struct ifreq *ifr)
}
}
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCSIFNETMASK(struct ifreq *ifr, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCSIFNETMASK(struct ifreq *ifr)
#endif
{
struct netif *netif = NULL;
@@ -742,12 +789,20 @@ static u8_t lwip_ioctl_internal_SIOCSIFNETMASK(struct ifreq *ifr)
return 0;
}
/* check data valid */
#ifdef LOSCFG_NET_CONTAINER
if (ip_addr_netmask_valid(ip_2_ip4(&taget_addr)) == 0) {
#else
if (ip_addr_netmask_valid(ip_2_ip4(&taget_addr)) != 0) {
#endif
return EINVAL;
}
/* lwip disallow two netif sit in same net at the same time */
#ifdef LOSCFG_NET_CONTAINER
loc_netif = group->netif_list;
#else
loc_netif = netif_list;
#endif
while (loc_netif != NULL) {
if (loc_netif == netif) {
loc_netif = loc_netif->next;
@@ -773,8 +828,13 @@ static u8_t lwip_ioctl_internal_SIOCSIFNETMASK(struct ifreq *ifr)
/* check if gateway still reachable */
if (!ip_addr_netcmp(&netif->gw, &netif->ip_addr, ip_2_ip4(&taget_addr))) {
ip_addr_set_zero(&(netif->gw));
#ifdef LOSCFG_NET_CONTAINER
if (netif == group->netif_default) {
(void)netif_set_default(NULL, group);
#else
if (netif == netif_default) {
(void)netif_set_default(NULL);
#endif
}
}
return 0;
@@ -1002,12 +1062,19 @@ static u8_t lwip_ioctl_internal_SIOCGIFFLAGS(struct ifreq *ifr)
}
}
#ifdef LOSCFG_NET_CONTAINER
static u8_t lwip_ioctl_internal_SIOCGIFNAME(struct ifreq *ifr, struct net_group *group)
#else
static u8_t lwip_ioctl_internal_SIOCGIFNAME(struct ifreq *ifr)
#endif
{
struct netif *netif = NULL;
int ret;
#ifdef LOSCFG_NET_CONTAINER
for (netif = group->netif_list; netif != NULL; netif = netif->next) {
#else
for (netif = netif_list; netif != NULL; netif = netif->next) {
#endif
if (ifr->ifr_ifindex == netif_get_index(netif)) {
break;
}
@@ -1325,7 +1392,9 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
/* allow it only on IPv6 sockets... */
is_ipv6 = NETCONNTYPE_ISIPV6((unsigned int)(sock->conn->type));
#endif
#ifdef LOSCFG_NET_CONTAINER
struct net_group *group = get_net_group_from_ippcb(sock->conn->pcb.ip);
#endif
switch ((u32_t)cmd) {
#if LWIP_IPV6
#if LWIP_IPV6_DUP_DETECT_ATTEMPTS
@@ -1371,7 +1440,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
if (is_ipv6 != 0) {
err = EINVAL;
} else {
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCADDRT(rmten, group);
#else
err = lwip_ioctl_internal_SIOCADDRT(rmten);
#endif
}
break;
#endif
@@ -1381,7 +1454,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
if (is_ipv6 != 0) {
err = EINVAL;
} else {
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCGIFCONF(ifr, group);
#else
err = lwip_ioctl_internal_SIOCGIFCONF(ifr);
#endif
}
break;
case SIOCGIFADDR:
@@ -1395,7 +1472,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
if (is_ipv6 != 0) {
err = lwip_ioctl_internal_SIOCSIFADDR_6(ifr);
} else {
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCSIFADDR(ifr, group);
#else
err = lwip_ioctl_internal_SIOCSIFADDR(ifr);
#endif
}
break;
case SIOCDIFADDR:
@@ -1403,7 +1484,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
if (is_ipv6 != 0) {
err = lwip_ioctl_internal_SIOCDIFADDR_6(ifr);
} else {
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCDIFADDR(ifr, group);
#else
err = lwip_ioctl_internal_SIOCDIFADDR(ifr);
#endif
}
break;
case SIOCGIFNETMASK:
@@ -1417,7 +1502,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
if (is_ipv6 != 0) {
err = EINVAL;
} else {
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCSIFNETMASK(ifr, group);
#else
err = lwip_ioctl_internal_SIOCSIFNETMASK(ifr);
#endif
}
break;
case SIOCSIFHWADDR:
@@ -1433,7 +1522,11 @@ static u8_t lwip_ioctl_impl(const struct lwip_sock *sock, long cmd, void *argp)
err = lwip_ioctl_internal_SIOCGIFFLAGS(ifr);
break;
case SIOCGIFNAME:
#ifdef LOSCFG_NET_CONTAINER
err = lwip_ioctl_internal_SIOCGIFNAME(ifr, group);
#else
err = lwip_ioctl_internal_SIOCGIFNAME(ifr);
#endif
break;
case SIOCSIFNAME:
err = lwip_ioctl_internal_SIOCSIFNAME(ifr);

View File

@@ -156,6 +156,12 @@ int SysSchedSetScheduler(int id, int policy, int prio, int flag)
id = (int)LOS_GetCurrProcessID();
}
#ifdef LOSCFG_KERNEL_PLIMITS
if (prio < OsPidLimitGetPriorityLimit()) {
return -EINVAL;
}
#endif
ret = OsPermissionToCheck(id, LOS_GetCurrProcessID());
if (ret < 0) {
return ret;
@@ -210,6 +216,12 @@ int SysSetProcessPriority(int which, int who, unsigned int prio)
who = (int)LOS_GetCurrProcessID();
}
#ifdef LOSCFG_KERNEL_PLIMITS
if (prio < OsPidLimitGetPriorityLimit()) {
return -EINVAL;
}
#endif
ret = OsPermissionToCheck(who, LOS_GetCurrProcessID());
if (ret < 0) {
return ret;
@@ -224,6 +236,12 @@ int SysSchedSetParam(int id, unsigned int prio, int flag)
return -OsUserTaskSchedulerSet(id, LOS_SCHED_RR, prio, false);
}
#ifdef LOSCFG_KERNEL_PLIMITS
if (prio < OsPidLimitGetPriorityLimit()) {
return -EINVAL;
}
#endif
return SysSetProcessPriority(LOS_PRIO_PROCESS, id, prio);
}
@@ -529,6 +547,10 @@ long SysSetUserID(int uid)
int retval = -EPERM;
unsigned int intSave;
if (uid < 0) {
return -EINVAL;
}
UINT32 kuid = OsMakeKuid(userContainer, uid);
if (kuid == (UINT32)-1) {
return -EINVAL;
@@ -684,6 +706,10 @@ int SysSetGroupID(int gid)
unsigned int intSave;
int count;
if (gid < 0) {
return -EINVAL;
}
unsigned int kgid = OsMakeKgid(userContainer, gid);
if (kgid == (UINT32)-1) {
return -EINVAL;

View File

@@ -138,6 +138,9 @@ group("unittest") {
if (LOSCFG_USER_TEST_PROCESS_FS == true) {
deps += [ "process/fs:liteos_a_process_fs_unittest_door" ]
}
if (LOSCFG_USER_TEST_PROCESS_PLIMITS == true) {
deps += [ "process/plimits:liteos_a_process_plimits_unittest_door" ]
}
}
if (LOSCFG_USER_TEST_LEVEL >= TEST_LEVEL_MIDDLE) {
deps += [ "process/basic:liteos_a_process_basic_unittest" ]
@@ -145,6 +148,9 @@ group("unittest") {
if (LOSCFG_USER_TEST_PROCESS_FS == true) {
deps += [ "process/fs:liteos_a_process_fs_unittest" ]
}
if (LOSCFG_USER_TEST_PROCESS_PLIMITS == true) {
deps += [ "process/plimits:liteos_a_process_plimits_unittest" ]
}
}
}

View File

@@ -143,6 +143,7 @@ LOSCFG_USER_TEST_MNT_CONTAINER = false
LOSCFG_USER_TEST_IPC_CONTAINER = false
LOSCFG_USER_TEST_TIME_CONTAINER = false
LOSCFG_USER_TEST_USER_CONTAINER = false
LOSCFG_USER_TEST_NET_CONTAINER = false
if (defined(LOSCFG_KERNEL_CONTAINER) || liteos_container_test_enable == true) {
LOSCFG_USER_TEST_CONTAINER = true
if (defined(LOSCFG_PID_CONTAINER) || liteos_container_test_enable == true) {
@@ -163,6 +164,14 @@ if (defined(LOSCFG_KERNEL_CONTAINER) || liteos_container_test_enable == true) {
if (defined(LOSCFG_USER_CONTAINER) || liteos_container_test_enable == true) {
LOSCFG_USER_TEST_USER_CONTAINER = true
}
if (defined(LOSCFG_NET_CONTAINER) || liteos_container_test_enable == true) {
LOSCFG_USER_TEST_NET_CONTAINER = true
}
}
LOSCFG_USER_TEST_PROCESS_PLIMITS = false
if (defined(LOSCFG_KERNEL_PLIMITS) || liteos_container_test_enable == true) {
LOSCFG_USER_TEST_PROCESS_PLIMITS = true
}
########## fuzz test ##########

View File

@@ -50,6 +50,9 @@ config("container_config") {
if (defined(LOSCFG_USER_TEST_USER_CONTAINER)) {
cflags += [ "-DLOSCFG_USER_TEST_USER_CONTAINER" ]
}
if (defined(LOSCFG_USER_TEST_NET_CONTAINER)) {
cflags += [ "-DLOSCFG_USER_TEST_NET_CONTAINER" ]
}
cflags_cc = cflags
}

View File

@@ -30,6 +30,10 @@
#include <climits>
#include <gtest/gtest.h>
#include <cstdio>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/route.h>
#include "It_container_test.h"
const char *USERDATA_DIR_NAME = "/userdata";
@@ -41,6 +45,8 @@ const char *FS_TYPE = "vfat";
const int BIT_ON_RETURN_VALUE = 8;
const int STACK_SIZE = 1024 * 1024;
const int CHILD_FUNC_ARG = 0x2088;
static const int TRY_COUNT = 5;
static const int OFFSET = 2;
int ChildFunction(void *args)
{
@@ -88,6 +94,155 @@ int WaitChild(pid_t pid, int *status, int errNo1, int errNo2)
return 0;
}
int ReadFile(const char *filepath, char *buf)
{
FILE *fpid = nullptr;
fpid = fopen(filepath, "r");
if (fpid == nullptr) {
return -1;
}
size_t trd = fread(buf, 1, 512, fpid);
(void)fclose(fpid);
return trd;
}
int WriteFile(const char *filepath, const char *buf)
{
int fd = open(filepath, O_WRONLY);
if (fd == -1) {
return -1;
}
size_t twd = write(fd, buf, strlen(buf));
if (twd == -1) {
(void)close(fd);
return -1;
}
(void)close(fd);
return twd;
}
int GetLine(char *buf, int count, int maxLen, char **array)
{
char *head = buf;
char *tail = buf;
char index = 0;
if ((buf == NULL) || (strlen(buf) == 0)) {
return 0;
}
while (*tail != '\0') {
if (*tail != '\n') {
tail++;
continue;
}
if (index >= count) {
return index + 1;
}
array[index] = head;
index++;
*tail = '\0';
if (strlen(head) > maxLen) {
return index + 1;
}
tail++;
head = tail;
tail++;
}
return (index + 1);
}
static int TryResetNetAddr(const char *ifname, const char *ip, const char *netmask, const char *gw)
{
int ret;
struct ifreq ifr;
struct rtentry rt;
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (fd < 0) {
return -1;
}
ret = strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifname, IFNAMSIZ);
if (ret != EOK) {
(void)close(fd);
return -1;
}
ifr.ifr_addr.sa_family = AF_INET;
inet_pton(AF_INET, netmask, ifr.ifr_addr.sa_data + OFFSET);
ret = ioctl(fd, SIOCSIFNETMASK, &ifr);
if (ret != 0) {
printf("[ERR][%s:%d] ioctl SIOCSIFNETMASK failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
(void)close(fd);
return -1;
}
inet_pton(AF_INET, ip, ifr.ifr_addr.sa_data + OFFSET);
ret = ioctl(fd, SIOCSIFADDR, &ifr);
if (ret != 0) {
(void)close(fd);
printf("[ERR][%s:%d] ioctl SIOCGIFADDR failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return -1;
}
struct sockaddr_in *addr = reinterpret_cast<struct sockaddr_in *>(&rt.rt_gateway);
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = inet_addr(gw);
rt.rt_flags = RTF_GATEWAY;
ret = ioctl(fd, SIOCADDRT, &rt);
if (ret != 0) {
(void)close(fd);
printf("[ERR][%s:%d] ioctl SIOCADDRT failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return ret;
}
ret = close(fd);
if (ret != 0) {
printf("[ERR][%s:%d] close failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return ret;
}
return ret;
}
int NetContainerResetNetAddr(const char *ifname, const char *ip, const char *netmask, const char *gw)
{
int ret;
int try_count = TRY_COUNT;
while (try_count--) {
ret = TryResetNetAddr(ifname, ip, netmask, gw);
if (ret == 0) {
break;
}
sleep(1);
}
return ret;
}
int NetContainerGetLocalIP(const char *ifname, char *ip, int ipLen)
{
struct ifreq ifr = {0};
int ret = strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);
if (ret != EOK) {
return -1; /* -1: errno */
}
int inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (inet_sock < 0) {
return -2; /* -2: errno */
}
ret = ioctl(inet_sock, SIOCGIFADDR, &ifr);
if (ret != 0) {
(void)close(inet_sock);
printf("[ERR][%s:%d] ioctl SIOCGIFADDR failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return -3; /* -3: errno */
}
ret = close(inet_sock);
if (ret != 0) {
return -4; /* -4: errno */
}
ret = strcpy_s(ip, ipLen, inet_ntoa((reinterpret_cast<struct sockaddr_in *>(&ifr.ifr_addr))->sin_addr));
if (ret != EOK) {
(void)close(inet_sock);
return -5; /* -5: errno */
}
return 0;
}
std::string GenContainerLinkPath(int pid, const std::string& containerType)
{
std::ostringstream buf;
@@ -124,8 +279,237 @@ HWTEST_F(ContainerTest, ItContainer001, TestSize.Level0)
{
ItContainer001();
}
#if defined(LOSCFG_USER_TEST_NET_CONTAINER)
/**
* @tc.name: Container_NET_Test_001
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer001, TestSize.Level0)
{
ItNetContainer001();
}
/**
* @tc.name: Container_NET_Test_002
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer002, TestSize.Level0)
{
ItNetContainer002();
}
/**
* @tc.name: Container_NET_Test_003
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer003, TestSize.Level0)
{
ItNetContainer003();
}
/**
* @tc.name: Container_NET_Test_004
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer004, TestSize.Level0)
{
ItNetContainer004();
}
/**
* @tc.name: Container_NET_Test_005
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer005, TestSize.Level0)
{
ItNetContainer005();
}
/**
* @tc.name: Container_NET_Test_006
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer006, TestSize.Level0)
{
ItNetContainer006();
}
/**
* @tc.name: Container_NET_Test_007
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer007, TestSize.Level0)
{
ItNetContainer007();
}
/**
* @tc.name: Container_NET_Test_008
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer008, TestSize.Level0)
{
ItNetContainer008();
}
/**
* @tc.name: Container_NET_Test_009
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer009, TestSize.Level0)
{
ItNetContainer009();
}
/**
* @tc.name: Container_NET_Test_011
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer011, TestSize.Level0)
{
ItNetContainer011();
}
/**
* @tc.name: Container_NET_Test_012
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer012, TestSize.Level0)
{
ItNetContainer012();
}
#endif
#if defined(LOSCFG_USER_TEST_USER_CONTAINER)
/**
* @tc.name: Container_UTS_Test_001
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer001, TestSize.Level0)
{
ItUserContainer001();
}
/**
* @tc.name: Container_UTS_Test_002
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer002, TestSize.Level0)
{
ItUserContainer002();
}
/**
* @tc.name: Container_UTS_Test_003
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer003, TestSize.Level0)
{
ItUserContainer003();
}
/**
* @tc.name: Container_UTS_Test_004
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer004, TestSize.Level0)
{
ItUserContainer004();
}
/**
* @tc.name: Container_UTS_Test_006
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer006, TestSize.Level0)
{
ItUserContainer006();
}
/**
* @tc.name: Container_UTS_Test_007
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer007, TestSize.Level0)
{
ItUserContainer007();
}
#endif
#if defined(LOSCFG_USER_TEST_PID_CONTAINER)
/**
* @tc.name: Container_Pid_Test_032
* @tc.desc: pid container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItPidContainer032, TestSize.Level0)
{
ItPidContainer032();
}
/**
* @tc.name: Container_Pid_Test_033
* @tc.desc: pid container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItPidContainer033, TestSize.Level0)
{
ItPidContainer033();
}
/**
* @tc.name: Container_Pid_Test_023
* @tc.desc: pid container function test case
@@ -282,6 +666,30 @@ HWTEST_F(ContainerTest, ItUtsContainer006, TestSize.Level0)
{
ItUtsContainer006();
}
/**
* @tc.name: Container_UTS_Test_007
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUtsContainer007, TestSize.Level0)
{
ItUtsContainer007();
}
/**
* @tc.name: Container_UTS_Test_008
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUtsContainer008, TestSize.Level0)
{
ItUtsContainer008();
}
#endif
#if defined(LOSCFG_USER_TEST_MNT_CONTAINER)
@@ -381,6 +789,30 @@ HWTEST_F(ContainerTest, ItMntContainer008, TestSize.Level0)
ItMntContainer008();
}
/**
* @tc.name: Container_MNT_Test_009
* @tc.desc: mnt container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItMntContainer009, TestSize.Level0)
{
ItMntContainer009();
}
/**
* @tc.name: Container_MNT_Test_010
* @tc.desc: mnt container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItMntContainer010, TestSize.Level0)
{
ItMntContainer010();
}
/**
* @tc.name: chroot_Test_001
* @tc.desc: chroot function test case
@@ -478,6 +910,30 @@ HWTEST_F(ContainerTest, ItIpcContainer006, TestSize.Level0)
{
ItIpcContainer006();
}
/**
* @tc.name: Container_IPC_Test_007
* @tc.desc: ipc container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItIpcContainer007, TestSize.Level0)
{
ItIpcContainer007();
}
/**
* @tc.name: Container_IPC_Test_008
* @tc.desc: ipc container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItIpcContainer008, TestSize.Level0)
{
ItIpcContainer008();
}
#endif
#if defined(LOSCFG_USER_TEST_TIME_CONTAINER)
@@ -541,6 +997,18 @@ HWTEST_F(ContainerTest, ItTimeContainer005, TestSize.Level0)
ItTimeContainer005();
}
/**
* @tc.name: Container_TIME_Test_006
* @tc.desc: time container function test case
* @tc.type: FUNC
* @tc.require: issueI6HDQK
* @tc.author:
*/
HWTEST_F(ContainerTest, ItTimeContainer006, TestSize.Level0)
{
ItTimeContainer006();
}
/*
* @tc.name: Container_TIME_Test_007
* @tc.desc: time container function test case
@@ -589,55 +1057,6 @@ HWTEST_F(ContainerTest, ItTimeContainer010, TestSize.Level0)
ItTimeContainer010();
}
#endif
#if defined(LOSCFG_USER_TEST_USER_CONTAINER)
/**
* @tc.name: Container_UTS_Test_001
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer001, TestSize.Level0)
{
ItUserContainer001();
}
/**
* @tc.name: Container_UTS_Test_002
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer002, TestSize.Level0)
{
ItUserContainer002();
}
/**
* @tc.name: Container_UTS_Test_003
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer003, TestSize.Level0)
{
ItUserContainer003();
}
/**
* @tc.name: Container_UTS_Test_004
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6EC0A
* @tc.author:
*/
HWTEST_F(ContainerTest, ItUserContainer004, TestSize.Level0)
{
ItUserContainer004();
}
#endif
#endif /* LOSCFG_USER_TEST_SMOKE */
#if defined(LOSCFG_USER_TEST_FULL)
@@ -946,6 +1365,19 @@ HWTEST_F(ContainerTest, ItUserContainer005, TestSize.Level0)
ItUserContainer005();
}
#endif
#if defined(LOSCFG_USER_TEST_NET_CONTAINER)
/**
* @tc.name: Container_NET_Test_010
* @tc.desc: uts container function test case
* @tc.type: FUNC
* @tc.require: issueI6HPH2
* @tc.author:
*/
HWTEST_F(ContainerTest, ItNetContainer010, TestSize.Level0)
{
ItNetContainer010();
}
#endif
#endif
} // namespace OHOS

View File

@@ -91,12 +91,20 @@ extern "C" {
#define CLONE_NEWTIME 0x00000080
}
int WriteFile(const char *filepath, const char *buf);
int ReadFile(const char *filepath, char *buf);
int GetLine(char *buf, int count, int maxLen, char **array);
int ChildFunction(void *args);
pid_t CloneWrapper(int (*func)(void *), int flag, void *args);
int WaitChild(pid_t pid, int *status, int errNo1, int errNo2);
int NetContainerResetNetAddr(const char *ifname, const char *ip, const char *netmask, const char *gw);
int NetContainerGetLocalIP(const char *ifname, char *ip, int ipLen);
std::string GenContainerLinkPath(int pid, const std::string& containerType);
extern std::string ReadlinkContainer(int pid, const std::string& containerType);
@@ -142,11 +150,11 @@ void ItUserContainer002(void);
void ItUserContainer003(void);
void ItUserContainer004(void);
void ItUserContainer005(void);
#if defined(LOSCFG_USER_TEST_SMOKE)
void ItUserContainer006(void);
void ItUserContainer007(void);
void ItContainer001(void);
void ItContainerChroot001(void);
void ItContainerChroot002(void);
#if defined(LOSCFG_USER_TEST_PID_CONTAINER)
void ItPidContainer023(void);
void ItPidContainer025(void);
void ItPidContainer026(void);
@@ -155,15 +163,15 @@ void ItPidContainer028(void);
void ItPidContainer029(void);
void ItPidContainer030(void);
void ItPidContainer031(void);
#endif
#if defined(LOSCFG_USER_TEST_UTS_CONTAINER)
void ItPidContainer032(void);
void ItPidContainer033(void);
void ItUtsContainer001(void);
void ItUtsContainer002(void);
void ItUtsContainer004(void);
void ItUtsContainer005(void);
void ItUtsContainer006(void);
#endif
#if defined(LOSCFG_USER_TEST_MNT_CONTAINER)
void ItUtsContainer007(void);
void ItUtsContainer008(void);
void ItMntContainer001(void);
void ItMntContainer002(void);
void ItMntContainer003(void);
@@ -172,16 +180,16 @@ void ItMntContainer005(void);
void ItMntContainer006(void);
void ItMntContainer007(void);
void ItMntContainer008(void);
#endif
#if defined(LOSCFG_USER_TEST_IPC_CONTAINER)
void ItMntContainer009(void);
void ItMntContainer010(void);
void ItIpcContainer001(void);
void ItIpcContainer002(void);
void ItIpcContainer003(void);
void ItIpcContainer004(void);
void ItIpcContainer005(void);
void ItIpcContainer006(void);
#endif
#if defined(LOSCFG_USER_TEST_TIME_CONTAINER)
void ItIpcContainer007(void);
void ItIpcContainer008(void);
void ItTimeContainer001(void);
void ItTimeContainer002(void);
void ItTimeContainer003(void);
@@ -192,11 +200,6 @@ void ItTimeContainer007(void);
void ItTimeContainer008(void);
void ItTimeContainer009(void);
void ItTimeContainer010(void);
#endif
#endif
#if defined(LOSCFG_USER_TEST_FULL)
#if defined(LOSCFG_USER_TEST_PID_CONTAINER)
void ItPidContainer001(void);
void ItPidContainer002(void);
void ItPidContainer003(void);
@@ -220,10 +223,17 @@ void ItPidContainer020(void);
void ItPidContainer021(void);
void ItPidContainer022(void);
void ItPidContainer024(void);
#endif
#if defined(LOSCFG_USER_TEST_UTS_CONTAINER)
void ItUtsContainer003(void);
#endif
#endif
void ItNetContainer001(void);
void ItNetContainer002(void);
void ItNetContainer003(void);
void ItNetContainer004(void);
void ItNetContainer005(void);
void ItNetContainer006(void);
void ItNetContainer007(void);
void ItNetContainer008(void);
void ItNetContainer009(void);
void ItNetContainer010(void);
void ItNetContainer011(void);
void ItNetContainer012(void);
#endif /* _IT_CONTAINER_TEST_H */

View File

@@ -50,6 +50,8 @@ if (defined(LOSCFG_USER_TEST_PID_CONTAINER)) {
"$TEST_UNITTEST_DIR/container/smoke/It_pid_container_029.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_pid_container_030.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_pid_container_031.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_pid_container_032.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_pid_container_033.cpp",
]
sources_full += [
"$TEST_UNITTEST_DIR/container/full/It_pid_container_001.cpp",
@@ -84,6 +86,8 @@ if (defined(LOSCFG_USER_TEST_UTS_CONTAINER)) {
"$TEST_UNITTEST_DIR/container/smoke/It_uts_container_004.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_uts_container_005.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_uts_container_006.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_uts_container_007.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_uts_container_008.cpp",
]
sources_full +=
[ "$TEST_UNITTEST_DIR/container/full/It_uts_container_003.cpp" ]
@@ -100,6 +104,8 @@ if (defined(LOSCFG_USER_TEST_MNT_CONTAINER)) {
"$TEST_UNITTEST_DIR/container/smoke/It_mnt_container_006.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_mnt_container_007.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_mnt_container_008.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_mnt_container_009.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_mnt_container_010.cpp",
]
}
@@ -111,6 +117,8 @@ if (defined(LOSCFG_USER_TEST_IPC_CONTAINER)) {
"$TEST_UNITTEST_DIR/container/smoke/It_ipc_container_004.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_ipc_container_005.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_ipc_container_006.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_ipc_container_007.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_ipc_container_008.cpp",
]
}
@@ -135,7 +143,26 @@ if (defined(LOSCFG_USER_TEST_USER_CONTAINER)) {
"$TEST_UNITTEST_DIR/container/smoke/It_user_container_002.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_user_container_003.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_user_container_004.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_user_container_006.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_user_container_007.cpp",
]
sources_full +=
[ "$TEST_UNITTEST_DIR/container/full/It_user_container_005.cpp" ]
}
if (defined(LOSCFG_USER_TEST_NET_CONTAINER)) {
sources_smoke += [
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_001.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_002.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_003.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_004.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_005.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_006.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_007.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_008.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_009.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_011.cpp",
"$TEST_UNITTEST_DIR/container/smoke/It_net_container_012.cpp",
]
sources_full +=
[ "$TEST_UNITTEST_DIR/container/full/It_net_container_010.cpp" ]
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include "sys/resource.h"
#include "sys/wait.h"
#include "pthread.h"
#include "sched.h"
#include "It_container_test.h"
const int MAX_PID_RANGE = 100000;
const int SLEEP_TIME_US = 1000;
const int LOOP_NUM = 100;
static int ChildFunc(void *arg)
{
usleep(SLEEP_TIME_US);
exit(EXIT_CODE_ERRNO_5);
}
static int GroupProcess(void *arg)
{
(void)arg;
int ret;
int status = 0;
for (int i = 0; i < LOOP_NUM; i++) {
int argTmp = CHILD_FUNC_ARG;
auto pid = CloneWrapper(ChildFunc, CLONE_NEWNET, &argTmp);
if (pid == -1) {
return EXIT_CODE_ERRNO_1;
}
ret = waitpid(pid, &status, 0);
status = WEXITSTATUS(status);
if (status != EXIT_CODE_ERRNO_5) {
return EXIT_CODE_ERRNO_2;
}
}
exit(EXIT_CODE_ERRNO_5);
}
void ItNetContainer010(void)
{
int ret;
int status = 0;
int arg = CHILD_FUNC_ARG;
auto pid = CloneWrapper(GroupProcess, CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
status = WEXITSTATUS(status);
ASSERT_EQ(status, EXIT_CODE_ERRNO_5);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -99,4 +99,6 @@ void ItPidContainer003(void)
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, CONTAINER_FIRST_PID);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -46,7 +46,7 @@ static int ChildFun(void *p)
for (int i = 0; i < count; i++) {
pid = fork();
if (pid == 0) {
sleep(5); /* delay 5s */
sleep(2); /* delay 2s */
exit(0);
} else if (pid < 0) {
if (errno != EAGAIN) {
@@ -91,4 +91,6 @@ void ItPidContainer009(void)
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_255);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -112,4 +112,6 @@ void ItPidContainer020(void)
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, 0);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -33,13 +33,11 @@
#include "pthread.h"
#include "sched.h"
const int SLEEP_TIME_US = 1000;
const int LOOP_NUM = 1000;
const int LOOP_NUM = 100;
static int ChildFunc(void *arg)
{
(void)arg;
usleep(SLEEP_TIME_US);
exit(EXIT_CODE_ERRNO_5);
}
@@ -61,6 +59,7 @@ static int GroupProcess(void *arg)
if (status != EXIT_CODE_ERRNO_5) {
return EXIT_CODE_ERRNO_2;
}
usleep(10000);
}
exit(EXIT_CODE_ERRNO_5);
@@ -78,4 +77,6 @@ void ItPidContainer024(void)
ASSERT_EQ(ret, pid);
status = WEXITSTATUS(status);
ASSERT_EQ(status, EXIT_CODE_ERRNO_5);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -85,4 +85,6 @@ void ItUserContainer005(void)
status = WEXITSTATUS(status);
ASSERT_EQ(status, EXIT_TRUE_CODE);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -78,4 +78,6 @@ void ItUtsContainer003(void)
ASSERT_EQ(ret, pid);
status = WEXITSTATUS(status);
ASSERT_EQ(status, EXIT_CODE_ERRNO_5);
sleep(5); /* 5: Wait for process resources to be reclaimed */
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
sleep(2); /* 2: delay 2s */
return 0;
}
void ItIpcContainer007(void)
{
std::string path = "/proc/sys/user/max_ipc_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWIPC, NULL);
ASSERT_NE(pid1, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWIPC, NULL);
ASSERT_EQ(pid2, -1);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWIPC);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return 0;
}
void ItIpcContainer008(void)
{
std::string path = "/proc/sys/user/max_ipc_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWIPC, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
sleep(2); /* 2: delay 2s */
return 0;
}
void ItMntContainer009(void)
{
std::string path = "/proc/sys/user/max_mnt_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWNS, NULL);
ASSERT_NE(pid1, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWNS, NULL);
ASSERT_EQ(pid2, -1);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWNS);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return 0;
}
void ItMntContainer010(void)
{
std::string path = "/proc/sys/user/max_mnt_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWNS, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <arpa/inet.h>
#include <net/if.h>
#include "It_container_test.h"
using namespace std;
static const int IpLen = 16;
static const char *NETMASK = "255.255.255.0";
static const char *GW = "192.168.100.1";
static const char *IFNAME = "veth0";
static const char *PEER_IP = "192.168.100.5";
static int SetIP(char *ip)
{
struct ifreq ifr;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (fd < 0) {
return -1;
}
int ret = strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0", IFNAMSIZ);
if (ret != EOK) {
(void)close(fd);
return -1;
}
ifr.ifr_addr.sa_family = AF_INET;
inet_pton(AF_INET, ip, ifr.ifr_addr.sa_data + 2); /* 2: offset */
ret = ioctl(fd, SIOCSIFADDR, &ifr);
if (ret != 0) {
(void)close(fd);
printf("[ERR][%s:%d] ioctl SIOCSIFADDR failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return -1;
}
ret = close(fd);
if (ret != 0) {
return -1;
}
return 0;
}
static int ChildFunc(void *arg)
{
(void)arg;
int ret;
char oldIp[IpLen] = {NULL};
char newIp[IpLen] = {NULL};
ret = NetContainerGetLocalIP("eth0", oldIp, IpLen);
if (ret == 0) {
return EXIT_CODE_ERRNO_1;
}
ret = SetIP("192.168.1.233");
if (ret == 0) {
return EXIT_CODE_ERRNO_2;
}
ret = NetContainerResetNetAddr(IFNAME, PEER_IP, NETMASK, GW);
if (ret != 0) {
return EXIT_CODE_ERRNO_3;
}
(void)memset_s(newIp, IpLen, 0, IpLen);
ret = NetContainerGetLocalIP(IFNAME, newIp, IpLen);
if (ret != 0) {
return EXIT_CODE_ERRNO_4;
}
if (strcmp(PEER_IP, newIp) != 0) {
return EXIT_CODE_ERRNO_5;
}
printf("######## [%s:%d] %s: %s ########\n", __FUNCTION__, __LINE__, IFNAME, newIp);
return 0;
}
void ItNetContainer001(void)
{
int ret;
char oldIp[IpLen] = {NULL};
char newIp[IpLen] = {NULL};
char *stack = (char *)mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, NULL);
char *stackTop = stack + STACK_SIZE;
ret = NetContainerGetLocalIP("eth0", oldIp, IpLen);
ASSERT_EQ(ret, 0);
auto pid = clone(ChildFunc, stackTop, SIGCHLD | CLONE_NEWNET, NULL);
ASSERT_NE(pid, -1);
int status;
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
ret = NetContainerGetLocalIP("eth0", newIp, IpLen);
ASSERT_EQ(ret, 0);
ret = strcmp(oldIp, newIp);
ASSERT_EQ(ret, 0);
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <arpa/inet.h>
#include <net/if.h>
#include "It_container_test.h"
using namespace std;
static const int IpLen = 16;
static const char *NETMASK = "255.255.255.0";
static const char *GW = "192.168.100.1";
static const char *IFNAME = "veth0";
static const char *PEER_IP = "192.168.100.5";
static int SetIP(char *ip)
{
struct ifreq ifr;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (fd < 0) {
return -1;
}
int ret = strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0", IFNAMSIZ);
if (ret != EOK) {
(void)close(fd);
return -1;
}
ifr.ifr_addr.sa_family = AF_INET;
inet_pton(AF_INET, ip, ifr.ifr_addr.sa_data + 2); /* 2: offset */
ret = ioctl(fd, SIOCSIFADDR, &ifr);
if (ret != 0) {
printf("[ERR][%s:%d] ioctl SIOCSIFADDR failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
(void)close(fd);
return -1;
}
ret = close(fd);
if (ret != 0) {
return -1;
}
return 0;
}
static int ChildFunc(void *arg)
{
(void)arg;
int ret;
char oldIp[IpLen] = {NULL};
char newIp[IpLen] = {NULL};
ret = NetContainerGetLocalIP("eth0", oldIp, IpLen);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
ret = unshare(CLONE_NEWNET);
if (ret < 0) {
return EXIT_CODE_ERRNO_2;
}
ret = NetContainerGetLocalIP("eth0", newIp, IpLen);
if (ret == 0) {
return EXIT_CODE_ERRNO_3;
}
ret = SetIP("192.168.1.234");
if (ret == 0) {
return EXIT_CODE_ERRNO_4;
}
ret = NetContainerResetNetAddr(IFNAME, PEER_IP, NETMASK, GW);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
(void)memset_s(newIp, IpLen, 0, IpLen);
ret = NetContainerGetLocalIP(IFNAME, newIp, IpLen);
if (ret != 0) {
return EXIT_CODE_ERRNO_6;
}
if (strcmp(PEER_IP, newIp) != 0) {
return EXIT_CODE_ERRNO_7;
}
printf("######## [%s:%d] %s: %s ########\n", __FUNCTION__, __LINE__, IFNAME, newIp);
return 0;
}
void ItNetContainer002(void)
{
int ret;
char oldIp[IpLen] = {NULL};
char newIp[IpLen] = {NULL};
char *stack = (char *)mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, NULL);
char *stackTop = stack + STACK_SIZE;
ret = NetContainerGetLocalIP("eth0", oldIp, IpLen);
ASSERT_EQ(ret, 0);
auto pid = clone(ChildFunc, stackTop, SIGCHLD, NULL);
ASSERT_NE(pid, -1);
int status;
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
ret = NetContainerGetLocalIP("eth0", newIp, IpLen);
ASSERT_EQ(ret, 0);
ret = strcmp(oldIp, newIp);
ASSERT_EQ(ret, 0);
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <string>
#include <iostream>
#include <regex>
#include "It_container_test.h"
static std::string GenNetLinkPath(int pid)
{
std::ostringstream buf;
buf << "/proc/" << pid << "/container/net";
return buf.str();
}
static std::string ReadlinkNet(int pid)
{
auto path = GenNetLinkPath(pid);
struct stat sb;
int ret = lstat(path.data(), &sb);
if (ret == -1) {
perror("lstat");
return std::string();
}
auto bufsiz = sb.st_size + 1;
if (sb.st_size == 0) {
bufsiz = PATH_MAX;
}
std::vector<char> buf(bufsiz);
auto nbytes = readlink(path.c_str(), buf.data(), bufsiz);
if (nbytes == -1) {
perror("readlink");
return std::string();
}
return buf.data();
}
void ItNetContainer003(void)
{
std::string zerolink("'net:[0]'");
auto netlink = ReadlinkNet(getpid());
int ret = zerolink.compare(netlink);
ASSERT_NE(ret, 0);
std::regex reg("'net:\\[[0-9]+\\]'");
ret = std::regex_match(netlink, reg);
ASSERT_EQ(ret, 1);
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <sys/stat.h>
#include <iostream>
#include <regex>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "It_container_test.h"
static const char *CONTAINER_TYPE = "net";
static const int SLEEP_SECONDS = 2;
static const int TEST_PATH_MAX = 100;
static int NewnetChildFun(void *)
{
sleep(SLEEP_SECONDS);
return 0;
}
static int ChildFun(void *p)
{
(void)p;
int ret;
int status;
char path[TEST_PATH_MAX];
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
auto childPid = clone(NewnetChildFun, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
if (childPid == -1) {
return EXIT_CODE_ERRNO_1;
}
auto oldReadLink = ReadlinkContainer(getpid(), CONTAINER_TYPE);
if (sprintf_s(path, TEST_PATH_MAX, "/proc/%d/container/net", childPid) < 0) {
(void)waitpid(childPid, &status, 0);
return EXIT_CODE_ERRNO_8;
}
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return EXIT_CODE_ERRNO_2;
}
ret = setns(fd, CLONE_NEWNET);
if (ret != 0) {
(void)close(fd);
return EXIT_CODE_ERRNO_3;
}
ret = close(fd);
if (ret != 0) {
return EXIT_CODE_ERRNO_4;
}
auto newReadLink = ReadlinkContainer(getpid(), CONTAINER_TYPE);
ret = strcmp(oldReadLink.c_str(), newReadLink.c_str());
if (ret == 0) {
return EXIT_CODE_ERRNO_5;
}
ret = waitpid(childPid, &status, 0);
if (ret != childPid) {
return EXIT_CODE_ERRNO_6;
}
int exitCode = WEXITSTATUS(status);
if (exitCode != 0) {
return EXIT_CODE_ERRNO_7;
}
return 0;
}
void ItNetContainer004(void)
{
int status;
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
auto childPid = clone(ChildFun, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(childPid, -1);
int ret = waitpid(childPid, &status, 0);
ASSERT_EQ(ret, childPid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/route.h>
#include "It_container_test.h"
static const char *NETMASK = "255.255.255.0";
static const char *GW = "192.168.100.1";
static const char *IFNAME = "veth0";
static const char *SERVER_IP = "192.168.100.6";
static const int SERVER_PORT = 8000;
static const char *PEER_IP = "192.168.100.5";
static const int PEER_PORT = 8001;
static const int DATA_LEN = 128;
static const char *SERVER_MSG = "===Hi, I'm Server.===";
static const char *PEER_MSG = "===Hi, I'm Peer.===";
static const int TRY_COUNT = 5;
static int UdpClient(void)
{
int ret = 0;
int peer;
int try_count = TRY_COUNT;
char recv_data[DATA_LEN];
struct sockaddr_in server_addr;
struct sockaddr_in peer_addr;
peer = socket(AF_INET, SOCK_DGRAM, 0);
if (peer < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(SERVER_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
peer_addr.sin_family = AF_INET;
peer_addr.sin_addr.s_addr = inet_addr(PEER_IP);
peer_addr.sin_port = htons(PEER_PORT);
(void)memset_s(&(peer_addr.sin_zero), sizeof(peer_addr.sin_zero), 0, sizeof(peer_addr.sin_zero));
ret = bind(peer, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&peer_addr)),
sizeof(struct sockaddr));
if (ret != 0) {
return EXIT_CODE_ERRNO_2;
}
timeval tv = {1, 0};
ret = setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, const_cast<void *>(reinterpret_cast<void *>(&tv)), sizeof(timeval));
/* loop try util server is ready */
while (try_count--) {
ret = sendto(peer, PEER_MSG, strlen(PEER_MSG) + 1, 0,
const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
(socklen_t)sizeof(server_addr));
if (ret == -1) {
continue;
}
ret = recvfrom(peer, recv_data, DATA_LEN, 0, nullptr, nullptr);
if (ret != -1) {
break;
}
}
if (ret < 0) {
return EXIT_CODE_ERRNO_3;
}
(void)close(peer);
ret = strcmp(recv_data, SERVER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_4;
}
return 0;
}
static int ChildFunc(void *arg)
{
int ret = NetContainerResetNetAddr(IFNAME, PEER_IP, NETMASK, GW);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return UdpClient();
}
static int UdpServer(void)
{
int ret = 0;
int server;
int try_count = TRY_COUNT;
char recv_data[DATA_LEN];
struct sockaddr_in server_addr;
struct sockaddr_in peer_addr;
socklen_t peer_addr_len = sizeof(struct sockaddr);
server = socket(AF_INET, SOCK_DGRAM, 0);
if (server < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(SERVER_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
ret = bind(server, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
sizeof(struct sockaddr));
if (ret != 0) {
return EXIT_CODE_ERRNO_2;
}
ret = recvfrom(server, recv_data, DATA_LEN, 0, reinterpret_cast<struct sockaddr *>(&peer_addr), &peer_addr_len);
if (ret < 0) {
return EXIT_CODE_ERRNO_3;
}
ret = sendto(server, SERVER_MSG, strlen(SERVER_MSG) + 1, 0,
const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&peer_addr)), peer_addr_len);
if (ret < 0) {
return EXIT_CODE_ERRNO_4;
}
(void)close(server);
ret = strcmp(recv_data, PEER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
return ret;
}
static void *UdpServerThread(void *arg)
{
int ret = NetContainerResetNetAddr(IFNAME, SERVER_IP, NETMASK, GW);
if (ret != 0) {
return (void *)(intptr_t)ret;
}
ret = UdpServer();
return (void *)(intptr_t)ret;
}
void ItNetContainer005(void)
{
int ret = 0;
int status;
void *tret = nullptr;
pthread_t srv;
pthread_attr_t attr;
ret = pthread_attr_init(&attr);
ASSERT_EQ(ret, 0);
ret = pthread_create(&srv, &attr, UdpServerThread, nullptr);
ASSERT_EQ(ret, 0);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
auto pid = clone(ChildFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
ret = pthread_join(srv, &tret);
ASSERT_EQ(ret, 0);
ret = pthread_attr_destroy(&attr);
ASSERT_EQ(ret, 0);
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <semaphore.h>
#include <sys/socket.h>
#include <poll.h>
#include "It_container_test.h"
static const char *SERVER_IP = "127.0.0.1";
static const int SERV_PORT = 8002;
static const char *SERVER_MSG = "Hi, I'm Tcp Server!";
static const char *PEER_MSG = "Hi, I'm Tcp Client!";
static const int DATA_LEN = 128;
static int TcpClient(void *arg)
{
int ret;
int client;
char buffer[DATA_LEN];
struct sockaddr_in server_addr;
client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
server_addr.sin_port = htons(SERV_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
ret = connect(client, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
sizeof(server_addr));
if (ret < 0) {
return EXIT_CODE_ERRNO_2;
}
ret = send(client, PEER_MSG, strlen(PEER_MSG) + 1, 0);
if (ret < 0) {
return EXIT_CODE_ERRNO_3;
}
ret = recv(client, buffer, sizeof(buffer), 0);
if (ret < 0) {
return EXIT_CODE_ERRNO_4;
}
ret = strcmp(buffer, SERVER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
(void)close(client);
return 0;
}
static int ChildFunc(void *)
{
int ret;
int server;
int status;
char *stack = nullptr;
char *stackTop = nullptr;
char buffer[DATA_LEN];
struct sockaddr_in server_addr;
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
server_addr.sin_port = htons(SERV_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
ret = bind(server, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
sizeof(server_addr));
if (ret < 0) {
return EXIT_CODE_ERRNO_2;
}
ret = listen(server, 1);
if (ret < 0) {
return EXIT_CODE_ERRNO_3;
}
stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
int pid = clone(TcpClient, stackTop, SIGCHLD, &arg);
if (pid == -1) {
return EXIT_CODE_ERRNO_4;
}
int client = accept(server, nullptr, nullptr);
if (ret < 0) {
return EXIT_CODE_ERRNO_5;
}
ret = recv(client, buffer, sizeof(buffer), 0);
if (ret < 0) {
return EXIT_CODE_ERRNO_6;
}
ret = strcmp(buffer, PEER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_7;
}
ret = send(client, SERVER_MSG, strlen(SERVER_MSG) + 1, 0);
if (ret < 0) {
return EXIT_CODE_ERRNO_8;
}
(void)close(client);
(void)close(server);
ret = waitpid(pid, &status, 0);
if (ret != pid) {
return EXIT_CODE_ERRNO_9;
}
int exitCode = WEXITSTATUS(status);
if (exitCode != 0) {
return EXIT_CODE_ERRNO_10;
}
return 0;
}
void ItNetContainer006(void)
{
int ret = 0;
int status;
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
int pid = clone(ChildFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include "It_container_test.h"
static const char *LOCALHOST = "127.0.0.1";
static const int LOCALPORT = 8003;
static const char *MSG = "Tis is UDP Test!";
static const int DATA_LEN = 128;
static int ChildFunc(void *arg)
{
int ret;
int sock;
int recv_data_len;
char recv_data[DATA_LEN];
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
return EXIT_CODE_ERRNO_1;
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(LOCALHOST);
addr.sin_port = htons(LOCALPORT);
(void)memset_s(&(addr.sin_zero), sizeof(addr.sin_zero), 0, sizeof(addr.sin_zero));
ret = bind(sock, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&addr)),
sizeof(struct sockaddr));
if (ret < 0) {
return EXIT_CODE_ERRNO_2;
}
ret = sendto(sock, MSG, DATA_LEN, 0, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&addr)),
(socklen_t)sizeof(addr));
if (ret < 0) {
return EXIT_CODE_ERRNO_3;
}
ret = recvfrom(sock, recv_data, DATA_LEN, 0, nullptr, nullptr);
if (ret < 0) {
return EXIT_CODE_ERRNO_4;
}
ret = strcmp(recv_data, MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
(void)close(sock);
return 0;
}
void ItNetContainer007(void)
{
int ret = 0;
int status;
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
auto pid = clone(ChildFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <poll.h>
#include "It_container_test.h"
static const int PORT = 8004;
static const char *LOCALHOST = "127.0.0.1";
static int UdpTcpBind(int *sock1, int *sock2)
{
int ret;
int udp_sock;
int tcp_sock;
udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udp_sock < 0) {
return EXIT_CODE_ERRNO_1;
}
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr(LOCALHOST);
sa.sin_port = htons(PORT);
ret = bind(udp_sock, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&sa)), sizeof(sa));
if (ret != 0) {
return EXIT_CODE_ERRNO_2;
}
tcp_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (tcp_sock < 0) {
return EXIT_CODE_ERRNO_3;
}
ret = bind(tcp_sock, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&sa)), sizeof(sa));
if (ret != 0) {
return EXIT_CODE_ERRNO_4;
}
(*sock1) = udp_sock;
(*sock2) = tcp_sock;
return 0;
}
static int ClientFunc(void *param)
{
(void)param;
int ret;
int udp_sock;
int tcp_sock;
ret = UdpTcpBind(&udp_sock, &tcp_sock);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
(void)close(udp_sock);
(void)close(tcp_sock);
return ret;
}
void ItNetContainer008(void)
{
int ret;
int status;
int udp_sock;
int tcp_sock;
ret = UdpTcpBind(&udp_sock, &tcp_sock);
ASSERT_EQ(ret, 0);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
int pid = clone(ClientFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
(void)close(udp_sock);
(void)close(tcp_sock);
}

View File

@@ -0,0 +1,239 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/route.h>
#include "It_container_test.h"
static const char *NETMASK = "255.255.255.0";
static const char *GW = "192.168.100.1";
static const char *IFNAME = "veth0";
static const char *SERVER_IP = "192.168.100.6";
static const int SERVER_PORT = 8005;
static const char *PEER_IP = "192.168.100.5";
static const char *SERVER_MSG = "===Hi, I'm Server.===";
static const char *PEER_MSG = "===Hi, I'm Peer.===";
static const int TRY_COUNT = 5;
static const int DATA_LEN = 128;
static const int IpLen = 16;
static int TcpClient(void)
{
int ret = 0;
int peer;
int try_count = TRY_COUNT;
char recv_data[DATA_LEN];
struct sockaddr_in server_addr;
peer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (peer < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(SERVER_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
do {
sleep(1);
ret = connect(peer, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
sizeof(struct sockaddr));
} while (ret !=0 && (try_count--));
if (ret < 0) {
(void)close(peer);
printf("[ERR][%s:%d] connect failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_2;
}
ret = send(peer, PEER_MSG, strlen(PEER_MSG) + 1, 0);
if (ret < 0) {
(void)close(peer);
printf("[ERR][%s:%d] send failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_3;
}
ret = recv(peer, recv_data, sizeof(recv_data), 0);
if (ret < 0) {
(void)close(peer);
printf("[ERR][%s:%d] recv failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_4;
}
(void)close(peer);
ret = strcmp(recv_data, SERVER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
return 0;
}
static int TcpServer(void)
{
int ret = 0;
int server;
int peer;
char recv_data[DATA_LEN];
struct sockaddr_in server_addr;
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server < 0) {
return EXIT_CODE_ERRNO_1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(SERVER_PORT);
(void)memset_s(&(server_addr.sin_zero), sizeof(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
ret = bind(server, const_cast<struct sockaddr *>(reinterpret_cast<struct sockaddr *>(&server_addr)),
sizeof(struct sockaddr));
if (ret != 0) {
printf("[ERR][%s:%d] bind failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_2;
}
ret = listen(server, 1);
if (ret < 0) {
printf("[ERR][%s:%d] listen failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_3;
}
peer = accept(server, nullptr, nullptr);
if (peer < 0) {
printf("[ERR][%s:%d] accept failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_4;
}
(void)close(server);
ret = recv(peer, recv_data, sizeof(recv_data), 0);
if (ret < 0) {
printf("[ERR][%s:%d] recv failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_5;
}
ret = strcmp(recv_data, PEER_MSG);
if (ret != 0) {
return EXIT_CODE_ERRNO_6;
}
ret = send(peer, SERVER_MSG, strlen(SERVER_MSG) + 1, 0);
if (ret < 0) {
printf("[ERR][%s:%d] send failed, %s!\n", __FUNCTION__, __LINE__, strerror(errno));
return EXIT_CODE_ERRNO_7;
}
(void)close(peer);
return 0;
}
static void *TcpClientThread(void *arg)
{
char newIp[IpLen] = {NULL};
int ret = NetContainerResetNetAddr(IFNAME, PEER_IP, NETMASK, GW);
if (ret != 0) {
return (void *)(intptr_t)EXIT_CODE_ERRNO_1;
}
ret = NetContainerGetLocalIP(IFNAME, newIp, IpLen);
if (ret != 0) {
return (void *)(intptr_t)EXIT_CODE_ERRNO_2;
}
if (strncmp(PEER_IP, newIp, strlen(PEER_IP)) != 0) {
return (void *)(intptr_t)EXIT_CODE_ERRNO_3;
}
printf("######## [%s:%d] %s: %s ########\n", __FUNCTION__, __LINE__, IFNAME, newIp);
ret = TcpClient();
return (void *)(intptr_t)ret;
}
static int ChildFunc(void *arg)
{
char newIp[IpLen] = {NULL};
int ret = NetContainerResetNetAddr(IFNAME, SERVER_IP, NETMASK, GW);
if (ret != 0) {
return EXIT_CODE_ERRNO_8;
}
ret = NetContainerGetLocalIP(IFNAME, newIp, IpLen);
if (ret != 0) {
return EXIT_CODE_ERRNO_9;
}
if (strncmp(SERVER_IP, newIp, strlen(SERVER_IP)) != 0) {
return EXIT_CODE_ERRNO_10;
}
printf("######## [%s:%d] %s: %s ########\n", __FUNCTION__, __LINE__, IFNAME, newIp);
return TcpServer();
}
VOID ItNetContainer009(void)
{
int ret = 0;
int status;
void *tret = nullptr;
pthread_t srv;
pthread_attr_t attr;
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, CLONE_STACK_MMAP_FLAG, -1, 0);
EXPECT_STRNE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
int arg = CHILD_FUNC_ARG;
int pid = clone(ChildFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);
ASSERT_NE(pid, -1);
ret = pthread_attr_init(&attr);
ASSERT_EQ(ret, 0);
ret = pthread_create(&srv, &attr, TcpClientThread, nullptr);
ASSERT_EQ(ret, 0);
ret = pthread_join(srv, &tret);
ASSERT_EQ(ret, 0);
ret = (uintptr_t)tret;
ASSERT_EQ(ret, 0);
ret = pthread_attr_destroy(&attr);
ASSERT_EQ(ret, 0);
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
sleep(2); /* 2: delay 2s */
return 0;
}
void ItNetContainer011(void)
{
std::string path = "/proc/sys/user/max_net_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWNET, NULL);
ASSERT_NE(pid1, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWNET, NULL);
ASSERT_EQ(pid2, -1);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWNET);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return 0;
}
void ItNetContainer012(void)
{
std::string path = "/proc/sys/user/max_net_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWNET, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
sleep(2); /* 2: delay 2s */
return 0;
}
void ItPidContainer032(void)
{
std::string path = "/proc/sys/user/max_pid_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
sleep(2); /* 2: Wait for cache resource reclamation */
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWPID, NULL);
ASSERT_NE(pid1, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWPID, NULL);
ASSERT_EQ(pid2, -1);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWPID);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return 0;
}
void ItPidContainer033(void)
{
std::string path = "/proc/sys/user/max_pid_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
sleep(2); /* 2: Wait for cache resource reclamation */
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWPID, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -27,26 +27,85 @@
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include "It_container_test.h"
const int MAX_TIME_CONTAINER = 64;
const int STR_LEN = 100;
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWTIME);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
ret = unshare(CLONE_NEWTIME);
if (ret != 0) {
return EXIT_CODE_ERRNO_2;
}
return 0;
}
void ItTimeContainer006(void)
{
int ret;
char *fileName = "/proc/sys/user/max_time_container";
FILE *fp = nullptr;
char strBuf[STR_LEN] = {0};
std::string path = "/proc/sys/user/max_time_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
fp = fopen(fileName, "rb");
ASSERT_TRUE(fp != 0);
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
ret = fread(strBuf, 1, STR_LEN, fp);
ASSERT_TRUE(ret != -1);
GetLine(buf, g_arryLen, g_readLen, array);
ret = atoi(strBuf);
ASSERT_EQ(ret, MAX_TIME_CONTAINER);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
(void)fclose(fp);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWTIME, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_2);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -29,12 +29,13 @@
*/
#include <cstdio>
#include "It_process_fs_test.h"
#include "It_container_test.h"
static int const configLen = 16;
static int const invalidNum = 2;
static const int CHILD_FUNC_ARG = 0x2088;
const int STACK_SIZE = (1024 * 1024);
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
@@ -44,32 +45,56 @@ static int childFunc(void *arg)
return 0;
}
void ItProcessFs017(void)
void ItUserContainer006(void)
{
std::string path = "/proc/sys/user/max_user_container";
int fd = open(path.c_str(), O_WRONLY);
ASSERT_NE(fd, -1);
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
char buf[configLen];
size_t ret = sprintf_s(buf, configLen, "%d", invalidNum);
ASSERT_GT(ret, 0);
ret = write(fd, buf, (strlen(buf) + 1));
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
int arg = CHILD_FUNC_ARG;
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid = clone(childFunc, stackTop, CLONE_NEWUSER, &arg);
ASSERT_NE(pid, -1);
pid = clone(childFunc, stackTop, CLONE_NEWUSER, &arg);
ASSERT_NE(pid, -1);
auto pid1 = clone(childFunc, stackTop, CLONE_NEWUSER, NULL);
ASSERT_NE(pid1, -1);
pid = clone(childFunc, stackTop, CLONE_NEWUSER, &arg);
ASSERT_EQ(pid, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWUSER, NULL);
ASSERT_EQ(pid2, -1);
(void)close(fd);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
int ret = unshare(CLONE_NEWUSER);
if (ret != 0) {
return EXIT_CODE_ERRNO_1;
}
return 0;
}
void ItUserContainer007(void)
{
std::string path = "/proc/sys/user/max_user_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int status = 0;
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWUSER, NULL);
ASSERT_NE(pid1, -1);
ret = waitpid(pid1, &status, 0);
ASSERT_EQ(ret, pid1);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
ret = WEXITSTATUS(status);
ASSERT_EQ(ret, EXIT_CODE_ERRNO_1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

View File

@@ -38,54 +38,83 @@ static int ChildFun(void *p)
return EXIT_CODE_ERRNO_3;
}
void ItUtsContainer005(void)
static int UtsContainerTest(void *arg)
{
(void)arg;
pid_t callerPid;
int childPid;
int fd = -1;
int ret;
int status;
int setFlag;
int ret, status, setFlag;
char targetpath[100];
char old_uts_link[100];
char new_uts_link[100];
const char *containerType = "uts";
callerPid = getpid();
childPid = clone(ChildFun, NULL, CLONE_NEWUTS | SIGCHLD, NULL);
ASSERT_NE(childPid, -1);
if (childPid == -1) {
return EXIT_CODE_ERRNO_1;
}
auto linkBuffer = ReadlinkContainer(callerPid, containerType);
ASSERT_TRUE(linkBuffer.c_str() != NULL);
ret = sprintf_s(old_uts_link, sizeof(old_uts_link), "%s", linkBuffer.c_str());
ASSERT_NE(ret, -1);
auto linkBuffer1 = ReadlinkContainer(callerPid, containerType);
if (linkBuffer1.c_str() == NULL) {
return EXIT_CODE_ERRNO_2;
}
ret = sprintf_s(targetpath, sizeof(targetpath), "/proc/%d/container/uts", childPid);
ASSERT_NE(ret, -1);
if (ret == -1) {
return EXIT_CODE_ERRNO_4;
}
fd = open(targetpath, O_RDONLY | O_CLOEXEC);
ASSERT_NE(fd, -1);
if (fd == -1) {
return EXIT_CODE_ERRNO_5;
}
setFlag = CLONE_NEWUTS;
ret = setns(fd, setFlag);
ASSERT_NE(ret, -1);
(void)close(fd);
if (ret == -1) {
return EXIT_CODE_ERRNO_6;
}
/* NOTE: close fd, otherwise test fail */
ret = close(fd);
fd = -1;
ASSERT_NE(ret, -1);
auto linkBuffer2 = ReadlinkContainer(callerPid, containerType);
linkBuffer = ReadlinkContainer(callerPid, containerType);
ret = sprintf_s(new_uts_link, sizeof(new_uts_link), "%s", linkBuffer.c_str());
ASSERT_NE(ret, -1);
ASSERT_STRNE(old_uts_link, new_uts_link);
ret = linkBuffer2.compare(linkBuffer1);
if (ret == 0) {
return EXIT_CODE_ERRNO_7;
}
ret = waitpid(childPid, &status, 0);
ASSERT_EQ(ret, childPid);
if (ret != childPid) {
return EXIT_CODE_ERRNO_8;
}
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, EXIT_CODE_ERRNO_3);
if (exitCode != EXIT_CODE_ERRNO_3) {
return EXIT_CODE_ERRNO_9;
}
ret = setns(fd, setFlag);
ASSERT_EQ(ret, -1);
if (ret != -1) {
return EXIT_CODE_ERRNO_10;
}
return 0;
}
void ItUtsContainer005(void)
{
int ret;
int arg = CHILD_FUNC_ARG;
auto pid = CloneWrapper(UtsContainerTest, CLONE_NEWUTS, &arg);
ASSERT_NE(pid, -1);
int status;
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);
}

View File

@@ -29,35 +29,70 @@
*/
#include "It_container_test.h"
void ItUtsContainer006(void)
static int UtsContainerTest(void *arg)
{
(void)arg;
std::string containerType = "uts";
int parentPid = getpid();
auto parentlink = ReadlinkContainer(parentPid, containerType);
int childsPid = CloneWrapper(ChildFunction, CLONE_NEWUTS, NULL);
ASSERT_NE(childsPid, -1);
if (childsPid == -1) {
return EXIT_CODE_ERRNO_1;
}
auto childlink = ReadlinkContainer(childsPid, containerType);
std::string filePath = GenContainerLinkPath(childsPid, containerType);
int fd = open(filePath.c_str(), O_RDONLY);
ASSERT_NE(fd, -1);
if (fd == -1) {
return EXIT_CODE_ERRNO_2;
}
int ret = setns(fd, CLONE_NEWUTS);
ASSERT_NE(ret, -1);
(void)close(fd);
if (ret == -1) {
return EXIT_CODE_ERRNO_3;
}
auto parentlink1 = ReadlinkContainer(parentPid, containerType);
ret = parentlink.compare(parentlink1);
ASSERT_NE(ret, 0);
if (ret == 0) {
return EXIT_CODE_ERRNO_4;
}
ret = parentlink1.compare(childlink);
ASSERT_EQ(ret, 0);
if (ret != 0) {
return EXIT_CODE_ERRNO_5;
}
int status;
ret = waitpid(childsPid, &status, 0);
ASSERT_EQ(ret, childsPid);
if (ret != childsPid) {
return EXIT_CODE_ERRNO_6;
}
int exitCode = WEXITSTATUS(status);
if (exitCode != 0) {
return EXIT_CODE_ERRNO_7;
}
return 0;
}
void ItUtsContainer006(void)
{
int ret;
int arg = CHILD_FUNC_ARG;
auto pid = CloneWrapper(UtsContainerTest, CLONE_NEWUTS, &arg);
ASSERT_NE(pid, -1);
int status;
ret = waitpid(pid, &status, 0);
ASSERT_EQ(ret, pid);
ret = WIFEXITED(status);
ASSERT_NE(ret, 0);
int exitCode = WEXITSTATUS(status);
ASSERT_EQ(exitCode, 0);

View File

@@ -0,0 +1,100 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. 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 HOLDER 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.
*/
#include <cstdio>
#include "It_container_test.h"
static int const configLen = 16;
static const int MAX_CONTAINER = 10;
static const int g_buffSize = 512;
static const int g_arryLen = 4;
static const int g_readLen = 254;
static int childFunc(void *arg)
{
(void)arg;
sleep(2); /* 2: delay 2s */
return 0;
}
void ItUtsContainer007(void)
{
std::string path = "/proc/sys/user/max_uts_container";
char *array[g_arryLen] = { nullptr };
char buf[g_buffSize] = { 0 };
int ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
int value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
int usedCount = atoi(array[2] + strlen("count: "));
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", usedCount + 1);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
char *stack = (char *)mmap(nullptr, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
-1, 0);
ASSERT_NE(stack, nullptr);
char *stackTop = stack + STACK_SIZE;
auto pid1 = clone(childFunc, stackTop, CLONE_NEWUTS, NULL);
ASSERT_NE(pid1, -1);
auto pid2 = clone(childFunc, stackTop, CLONE_NEWUTS, NULL);
ASSERT_EQ(pid2, -1);
ret = waitpid(pid1, NULL, 0);
ASSERT_EQ(ret, pid1);
(void)memset_s(buf, configLen, 0, configLen);
ret = sprintf_s(buf, configLen, "%d", value);
ASSERT_GT(ret, 0);
ret = WriteFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
(void)memset_s(buf, configLen, 0, configLen);
ret = ReadFile(path.c_str(), buf);
ASSERT_NE(ret, -1);
GetLine(buf, g_arryLen, g_readLen, array);
value = atoi(array[1] + strlen("limit: "));
ASSERT_EQ(value, MAX_CONTAINER);
}

Some files were not shown because too many files have changed in this diff Show More