未验证 提交 d3ad34c1 编写于 作者: O openharmony_ci 提交者: Gitee

!1508 增加ut用例

Merge pull request !1508 from Mupceet/monthly_cc_add_init_ut
...@@ -35,6 +35,12 @@ extern "C" { ...@@ -35,6 +35,12 @@ extern "C" {
#define PTY_BUF_SIZE 4096 #define PTY_BUF_SIZE 4096
#define PTY_PATH_SIZE 128 #define PTY_PATH_SIZE 128
#ifdef STARTUP_INIT_TEST
#define CONTROL_FD_STATIC
#else
#define CONTROL_FD_STATIC static
#endif
typedef struct CmdService_ { typedef struct CmdService_ {
TaskHandle serverTask; TaskHandle serverTask;
struct ListNode head; struct ListNode head;
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
#include "control_fd.h" #include "control_fd.h"
#include "securec.h" #include "securec.h"
static void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context) CONTROL_FD_STATIC void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{ {
if ((fd < 0) || (events == NULL) || (context == NULL)) { if ((fd < 0) || (events == NULL) || (context == NULL)) {
BEGET_LOGE("[control_fd] Invalid fifo write parameter"); BEGET_LOGE("[control_fd] Invalid fifo write parameter");
...@@ -43,7 +43,7 @@ static void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *ev ...@@ -43,7 +43,7 @@ static void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *ev
*events = Event_Read; *events = Event_Read;
} }
static void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context) CONTROL_FD_STATIC void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{ {
if ((fd < 0) || (events == NULL) || (context == NULL)) { if ((fd < 0) || (events == NULL) || (context == NULL)) {
BEGET_LOGE("[control_fd] Invalid fifo read parameter"); BEGET_LOGE("[control_fd] Invalid fifo read parameter");
...@@ -63,17 +63,17 @@ static void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *eve ...@@ -63,17 +63,17 @@ static void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *eve
*events = Event_Read; *events = Event_Read;
} }
static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen) CONTROL_FD_STATIC void CmdClientOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen)
{ {
BEGET_LOGI("[control_fd] CmdOnRecvMessage %s len %d.", (char *)buffer, buffLen); BEGET_LOGI("[control_fd] CmdOnRecvMessage %s len %d.", (char *)buffer, buffLen);
} }
static void CmdOnConnectComplete(const TaskHandle client) CONTROL_FD_STATIC void CmdOnConnectComplete(const TaskHandle client)
{ {
BEGET_LOGI("[control_fd] CmdOnConnectComplete"); BEGET_LOGI("[control_fd] CmdOnConnectComplete");
} }
static void CmdOnClose(const TaskHandle task) CONTROL_FD_STATIC void CmdOnClose(const TaskHandle task)
{ {
BEGET_LOGI("[control_fd] CmdOnClose"); BEGET_LOGI("[control_fd] CmdOnClose");
CmdAgent *agent = (CmdAgent *)LE_GetUserData(task); CmdAgent *agent = (CmdAgent *)LE_GetUserData(task);
...@@ -83,17 +83,17 @@ static void CmdOnClose(const TaskHandle task) ...@@ -83,17 +83,17 @@ static void CmdOnClose(const TaskHandle task)
LE_StopLoop(LE_GetDefaultLoop()); LE_StopLoop(LE_GetDefaultLoop());
} }
static void CmdDisConnectComplete(const TaskHandle client) CONTROL_FD_STATIC void CmdDisConnectComplete(const TaskHandle client)
{ {
BEGET_LOGI("[control_fd] CmdDisConnectComplete"); BEGET_LOGI("[control_fd] CmdDisConnectComplete");
} }
static void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle handle) CONTROL_FD_STATIC void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle handle)
{ {
BEGET_LOGI("[control_fd] CmdOnSendMessageComplete"); BEGET_LOGI("[control_fd] CmdOnSendMessageComplete");
} }
static CmdAgent *CmdAgentCreate(const char *server) CONTROL_FD_STATIC CmdAgent *CmdAgentCreate(const char *server)
{ {
if (server == NULL) { if (server == NULL) {
BEGET_LOGE("[control_fd] Invalid parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
...@@ -108,7 +108,7 @@ static CmdAgent *CmdAgentCreate(const char *server) ...@@ -108,7 +108,7 @@ static CmdAgent *CmdAgentCreate(const char *server)
info.disConnectComplete = CmdDisConnectComplete; info.disConnectComplete = CmdDisConnectComplete;
info.connectComplete = CmdOnConnectComplete; info.connectComplete = CmdOnConnectComplete;
info.sendMessageComplete = CmdOnSendMessageComplete; info.sendMessageComplete = CmdOnSendMessageComplete;
info.recvMessage = CmdOnRecvMessage; info.recvMessage = CmdClientOnRecvMessage;
LE_STATUS status = LE_CreateStreamClient(LE_GetDefaultLoop(), &task, &info); LE_STATUS status = LE_CreateStreamClient(LE_GetDefaultLoop(), &task, &info);
BEGET_ERROR_CHECK(status == 0, return NULL, "[control_fd] Failed create client"); BEGET_ERROR_CHECK(status == 0, return NULL, "[control_fd] Failed create client");
CmdAgent *agent = (CmdAgent *)LE_GetUserData(task); CmdAgent *agent = (CmdAgent *)LE_GetUserData(task);
...@@ -117,7 +117,7 @@ static CmdAgent *CmdAgentCreate(const char *server) ...@@ -117,7 +117,7 @@ static CmdAgent *CmdAgentCreate(const char *server)
return agent; return agent;
} }
static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *ptyName) CONTROL_FD_STATIC int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *ptyName)
{ {
if ((agent == NULL) || (cmd == NULL) || (ptyName == NULL)) { if ((agent == NULL) || (cmd == NULL) || (ptyName == NULL)) {
BEGET_LOGE("[control_fd] Invalid parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
...@@ -143,11 +143,12 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, ...@@ -143,11 +143,12 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd,
return 0; return 0;
} }
static int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd) CONTROL_FD_STATIC int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd)
{ {
if ((cmd == NULL) || (agent == NULL)) { if ((cmd == NULL) || (agent == NULL)) {
return -1; return -1;
} }
#ifndef STARTUP_INIT_TEST
// initialize terminal // initialize terminal
struct termios term; struct termios term;
int ret = tcgetattr(STDIN_FILENO, &term); int ret = tcgetattr(STDIN_FILENO, &term);
...@@ -181,6 +182,7 @@ static int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd) ...@@ -181,6 +182,7 @@ static int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd)
close(pfd); return -1, "[control_fd] Failed le_loop start watcher stdin read and write ptmx"); close(pfd); return -1, "[control_fd] Failed le_loop start watcher stdin read and write ptmx");
ret = SendCmdMessage(agent, type, cmd, ptsbuffer); ret = SendCmdMessage(agent, type, cmd, ptsbuffer);
BEGET_ERROR_CHECK(ret == 0, close(pfd); return -1, "[control_fd] Failed send message"); BEGET_ERROR_CHECK(ret == 0, close(pfd); return -1, "[control_fd] Failed send message");
#endif
return 0; return 0;
} }
...@@ -192,11 +194,13 @@ void CmdClientInit(const char *socketPath, uint16_t type, const char *cmd) ...@@ -192,11 +194,13 @@ void CmdClientInit(const char *socketPath, uint16_t type, const char *cmd)
BEGET_LOGI("[control_fd] CmdAgentInit"); BEGET_LOGI("[control_fd] CmdAgentInit");
CmdAgent *agent = CmdAgentCreate(socketPath); CmdAgent *agent = CmdAgentCreate(socketPath);
BEGET_ERROR_CHECK(agent != NULL, return, "[control_fd] Failed to create agent"); BEGET_ERROR_CHECK(agent != NULL, return, "[control_fd] Failed to create agent");
#ifndef STARTUP_INIT_TEST
int ret = InitPtyInterface(agent, type, cmd); int ret = InitPtyInterface(agent, type, cmd);
if (ret != 0) { if (ret != 0) {
return; return;
} }
LE_RunLoop(LE_GetDefaultLoop()); LE_RunLoop(LE_GetDefaultLoop());
LE_CloseLoop(LE_GetDefaultLoop()); LE_CloseLoop(LE_GetDefaultLoop());
#endif
BEGET_LOGI("Cmd Client exit "); BEGET_LOGI("Cmd Client exit ");
} }
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <fcntl.h> #include <fcntl.h>
#include <unistd.h> #include <unistd.h>
...@@ -32,7 +33,7 @@ static void OnClose(const TaskHandle task) ...@@ -32,7 +33,7 @@ static void OnClose(const TaskHandle task)
OH_ListInit(&agent->item); OH_ListInit(&agent->item);
} }
static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen) CONTROL_FD_STATIC void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen)
{ {
if (buffer == NULL) { if (buffer == NULL) {
return; return;
...@@ -46,7 +47,7 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3 ...@@ -46,7 +47,7 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3
BEGET_LOGE("[control_fd] Received msg is invaild"); BEGET_LOGE("[control_fd] Received msg is invaild");
return; return;
} }
#ifndef STARTUP_INIT_TEST
agent->pid = fork(); agent->pid = fork();
if (agent->pid == 0) { if (agent->pid == 0) {
OpenConsole(); OpenConsole();
...@@ -68,10 +69,11 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3 ...@@ -68,10 +69,11 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3
} else if (agent->pid < 0) { } else if (agent->pid < 0) {
BEGET_LOGE("[control_fd] Failed fork service"); BEGET_LOGE("[control_fd] Failed fork service");
} }
#endif
return; return;
} }
static int SendMessage(LoopHandle loop, TaskHandle task, const char *message) CONTROL_FD_STATIC int SendMessage(LoopHandle loop, TaskHandle task, const char *message)
{ {
if (message == NULL) { if (message == NULL) {
BEGET_LOGE("[control_fd] Invalid parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
...@@ -90,11 +92,15 @@ static int SendMessage(LoopHandle loop, TaskHandle task, const char *message) ...@@ -90,11 +92,15 @@ static int SendMessage(LoopHandle loop, TaskHandle task, const char *message)
return 0; return 0;
} }
static int CmdOnIncommingConnect(const LoopHandle loop, const TaskHandle server) CONTROL_FD_STATIC int CmdOnIncommingConnect(const LoopHandle loop, const TaskHandle server)
{ {
TaskHandle client = NULL; TaskHandle client = NULL;
LE_StreamInfo info = {}; LE_StreamInfo info = {};
#ifndef STARTUP_INIT_TEST
info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT; info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT;
#else
info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT | TASK_TEST;
#endif
info.baseInfo.close = OnClose; info.baseInfo.close = OnClose;
info.baseInfo.userDataSize = sizeof(CmdTask); info.baseInfo.userDataSize = sizeof(CmdTask);
info.disConnectComplete = NULL; info.disConnectComplete = NULL;
......
...@@ -49,7 +49,7 @@ static int BuildClientSocket(void) ...@@ -49,7 +49,7 @@ static int BuildClientSocket(void)
return sockFd; return sockFd;
} }
static int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll) STATIC int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll)
{ {
if (buffer == NULL || size == 0 || serviceName == 0) { if (buffer == NULL || size == 0 || serviceName == 0) {
return -1; return -1;
......
...@@ -81,30 +81,8 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send ...@@ -81,30 +81,8 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send
return 0; return 0;
} }
// This function will allocate memory to store FDs STATIC int *GetFdsFromMsg(size_t *outFdCount, pid_t *requestPid, struct msghdr msghdr)
// Remember to delete when not used anymore.
int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, pid_t *requestPid)
{ {
CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
CMSG_SPACE(sizeof(int) * MAX_HOLD_FDS)) control;
BEGET_ERROR_CHECK(sizeof(control) <= PAGE_SIZE, return NULL, "Too many fds, out of memory");
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
};
int flags = MSG_CMSG_CLOEXEC | MSG_TRUNC;
if (nonblock) {
flags |= MSG_DONTWAIT;
}
ssize_t rc = TEMP_FAILURE_RETRY(recvmsg(sock, &msghdr, flags));
BEGET_ERROR_CHECK(rc >= 0, return NULL, "Failed to get fds from remote, err = %d", errno);
if ((msghdr.msg_flags) & MSG_TRUNC) { if ((msghdr.msg_flags) & MSG_TRUNC) {
BEGET_LOGE("Message was truncated when receiving fds"); BEGET_LOGE("Message was truncated when receiving fds");
return NULL; return NULL;
...@@ -115,7 +93,7 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, ...@@ -115,7 +93,7 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock,
size_t fdCount = 0; size_t fdCount = 0;
for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) { for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
fds = (int*) CMSG_DATA(cmsg); fds = (int*)CMSG_DATA(cmsg);
fdCount = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int); fdCount = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
BEGET_ERROR_CHECK(fdCount <= MAX_HOLD_FDS, return NULL, "Too many fds returned."); BEGET_ERROR_CHECK(fdCount <= MAX_HOLD_FDS, return NULL, "Too many fds returned.");
} }
...@@ -139,3 +117,29 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, ...@@ -139,3 +117,29 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock,
*outFdCount = fdCount; *outFdCount = fdCount;
return outFds; return outFds;
} }
// This function will allocate memory to store FDs
// Remember to delete when not used anymore.
int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, pid_t *requestPid)
{
CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
CMSG_SPACE(sizeof(int) * MAX_HOLD_FDS)) control;
BEGET_ERROR_CHECK(sizeof(control) <= PAGE_SIZE, return NULL, "Too many fds, out of memory");
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
};
int flags = MSG_CMSG_CLOEXEC | MSG_TRUNC;
if (nonblock) {
flags |= MSG_DONTWAIT;
}
ssize_t rc = TEMP_FAILURE_RETRY(recvmsg(sock, &msghdr, flags));
BEGET_ERROR_CHECK(rc >= 0, return NULL, "Failed to get fds from remote, err = %d", errno);
return GetFdsFromMsg(outFdCount, requestPid, msghdr);
}
\ No newline at end of file
...@@ -26,7 +26,7 @@ extern "C" { ...@@ -26,7 +26,7 @@ extern "C" {
#endif #endif
#ifndef INIT_LOG_PATH #ifndef INIT_LOG_PATH
#define INIT_LOG_PATH "/data/init_agent/" #define INIT_LOG_PATH STARTUP_INIT_UT_PATH"/data/init_agent/"
#endif #endif
#if defined(__GNUC__) && (__GNUC__ >= 4) #if defined(__GNUC__) && (__GNUC__ >= 4)
...@@ -47,7 +47,13 @@ typedef enum InitLogLevel { ...@@ -47,7 +47,13 @@ typedef enum InitLogLevel {
INIT_FATAL INIT_FATAL
} InitLogLevel; } InitLogLevel;
#if (defined(STARTUP_INIT_TEST) || defined(APPSPAWN_TEST))
#define FILE_NAME (strrchr((__FILE__), '/') + 1)
#define STATIC
#else
#define FILE_NAME (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__)) #define FILE_NAME (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__))
#define STATIC static
#endif
INIT_PUBLIC_API void StartupLog(InitLogLevel logLevel, uint32_t domain, const char *tag, const char *fmt, ...); INIT_PUBLIC_API void StartupLog(InitLogLevel logLevel, uint32_t domain, const char *tag, const char *fmt, ...);
INIT_PUBLIC_API void SetInitLogLevel(InitLogLevel level); INIT_PUBLIC_API void SetInitLogLevel(InitLogLevel level);
......
...@@ -46,5 +46,4 @@ int32_t BShellCmdRegister(BShellHandle shell, int execMode); ...@@ -46,5 +46,4 @@ int32_t BShellCmdRegister(BShellHandle shell, int execMode);
} }
#endif #endif
#endif #endif
#endif // INIT_UTILS_H #endif // INIT_UTILS_H
\ No newline at end of file
...@@ -21,30 +21,18 @@ ...@@ -21,30 +21,18 @@
static int bootchartCmdEnable(BShellHandle shell, int argc, char **argv) static int bootchartCmdEnable(BShellHandle shell, int argc, char **argv)
{ {
if (argc < 1) {
char *helpArgs[] = {"bootchart", NULL};
BShellCmdHelp(shell, 1, helpArgs);
}
SystemSetParameter("persist.init.bootchart.enabled", "1"); SystemSetParameter("persist.init.bootchart.enabled", "1");
return 0; return 0;
} }
static int bootchartCmdDisable(BShellHandle shell, int argc, char **argv) static int bootchartCmdDisable(BShellHandle shell, int argc, char **argv)
{ {
if (argc < 1) {
char *helpArgs[] = {"bootchart", NULL};
BShellCmdHelp(shell, 1, helpArgs);
}
SystemSetParameter("persist.init.bootchart.enabled", "0"); SystemSetParameter("persist.init.bootchart.enabled", "0");
return 0; return 0;
} }
static int bootchartCmdStart(BShellHandle shell, int argc, char **argv) static int bootchartCmdStart(BShellHandle shell, int argc, char **argv)
{ {
if (argc < 1) {
char *helpArgs[] = {"bootchart", NULL};
BShellCmdHelp(shell, 1, helpArgs);
}
char enable[4] = {}; // 4 enable size char enable[4] = {}; // 4 enable size
uint32_t size = sizeof(enable); uint32_t size = sizeof(enable);
int ret = SystemGetParameter("persist.init.bootchart.enabled", enable, &size); int ret = SystemGetParameter("persist.init.bootchart.enabled", enable, &size);
...@@ -58,13 +46,10 @@ static int bootchartCmdStart(BShellHandle shell, int argc, char **argv) ...@@ -58,13 +46,10 @@ static int bootchartCmdStart(BShellHandle shell, int argc, char **argv)
static int bootchartCmdStop(BShellHandle shell, int argc, char **argv) static int bootchartCmdStop(BShellHandle shell, int argc, char **argv)
{ {
if (argc < 1) {
char *helpArgs[] = {"bootchart", NULL};
BShellCmdHelp(shell, 1, helpArgs);
}
SystemSetParameter("ohos.servicectrl.bootchart", "stop"); SystemSetParameter("ohos.servicectrl.bootchart", "stop");
return 0; return 0;
} }
MODULE_CONSTRUCTOR(void) MODULE_CONSTRUCTOR(void)
{ {
const CmdInfo infos[] = { const CmdInfo infos[] = {
......
...@@ -26,22 +26,6 @@ static int main_cmd(BShellHandle shell, int argc, char* argv[]) ...@@ -26,22 +26,6 @@ static int main_cmd(BShellHandle shell, int argc, char* argv[])
BShellCmdHelp(shell, argc, argv); BShellCmdHelp(shell, argc, argv);
return 0; return 0;
} }
if (argc == REBOOT_CMD_NUMBER && strcmp(argv[1], "shutdown") != 0 &&
strcmp(argv[1], "updater") != 0 &&
strcmp(argv[1], "suspend") != 0 &&
strcmp(argv[1], "flashd") != 0 &&
#ifdef INIT_TEST
strcmp(argv[1], "charge") != 0 &&
#endif
#ifdef PRODUCT_RK
strcmp(argv[1], "loader") != 0 &&
#endif
strncmp(argv[1], "updater:", strlen("updater:")) != 0 &&
strncmp(argv[1], "flashd:", strlen("flashd:")) != 0) {
BShellCmdHelp(shell, argc, argv);
return 0;
}
int ret; int ret;
if (argc == REBOOT_CMD_NUMBER) { if (argc == REBOOT_CMD_NUMBER) {
ret = DoReboot(argv[1]); ret = DoReboot(argv[1]);
...@@ -53,9 +37,11 @@ static int main_cmd(BShellHandle shell, int argc, char* argv[]) ...@@ -53,9 +37,11 @@ static int main_cmd(BShellHandle shell, int argc, char* argv[])
} else { } else {
printf("[reboot command] DoReboot Api return ok\n"); printf("[reboot command] DoReboot Api return ok\n");
} }
#ifndef STARTUP_INIT_TEST
while (1) { while (1) {
pause(); pause();
} }
#endif
return 0; return 0;
} }
...@@ -69,12 +55,7 @@ MODULE_CONSTRUCTOR(void) ...@@ -69,12 +55,7 @@ MODULE_CONSTRUCTOR(void)
{"reboot", main_cmd, "reboot and boot into updater", "reboot updater[:options]", ""}, {"reboot", main_cmd, "reboot and boot into updater", "reboot updater[:options]", ""},
{"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd", ""}, {"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd", ""},
{"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd[:options]", ""}, {"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd[:options]", ""},
#ifdef INIT_TEST
{"reboot", main_cmd, "reboot and boot into charge", "reboot charge", ""}, {"reboot", main_cmd, "reboot and boot into charge", "reboot charge", ""},
#endif
#ifdef PRODUCT_RK
{"reboot", main_cmd, "reboot loader", "reboot loader", ""}
#endif
}; };
for (size_t i = sizeof(infos) / sizeof(infos[0]); i > 0; i--) { for (size_t i = sizeof(infos) / sizeof(infos[0]); i > 0; i--) {
BShellEnvRegisterCmd(GetShellHandle(), &infos[i - 1]); BShellEnvRegisterCmd(GetShellHandle(), &infos[i - 1]);
......
...@@ -35,15 +35,7 @@ constexpr int PARTITION_INFO_MAX_LENGTH = 256; ...@@ -35,15 +35,7 @@ constexpr int PARTITION_INFO_MAX_LENGTH = 256;
constexpr int BLOCK_SZIE_1 = 512; constexpr int BLOCK_SZIE_1 = 512;
constexpr uint64_t LOGO_MAGIC = 0XABCABCAB; constexpr uint64_t LOGO_MAGIC = 0XABCABCAB;
static std::string GetMiscDevicePath() #define MISC_DEVICE_NODE "/dev/block/by-name/misc"
{
char miscDevice[PATH_MAX] = {0};
int ret = GetBlockDevicePath("/misc", miscDevice, PATH_MAX);
if (ret != 0) {
return std::string("");
}
return std::string(miscDevice);
}
static void ClearLogo(int fd) static void ClearLogo(int fd)
{ {
...@@ -64,10 +56,6 @@ static void ClearLogo(int fd) ...@@ -64,10 +56,6 @@ static void ClearLogo(int fd)
static void WriteLogoContent(int fd, const std::string &logoPath, uint32_t size) static void WriteLogoContent(int fd, const std::string &logoPath, uint32_t size)
{ {
if (fd < 0 || logoPath.empty() || size == 0) {
std::cout << "path is null or size illegal\n";
return;
}
FILE *rgbFile = fopen(logoPath.c_str(), "rb"); FILE *rgbFile = fopen(logoPath.c_str(), "rb");
if (rgbFile == nullptr) { if (rgbFile == nullptr) {
std::cout << "cannot find pic file\n"; std::cout << "cannot find pic file\n";
...@@ -91,20 +79,12 @@ static void WriteLogoContent(int fd, const std::string &logoPath, uint32_t size) ...@@ -91,20 +79,12 @@ static void WriteLogoContent(int fd, const std::string &logoPath, uint32_t size)
free(buffer); free(buffer);
return; return;
} }
free(buffer);
if (buffer != nullptr) {
free(buffer);
buffer = nullptr;
}
(void)fclose(rgbFile); (void)fclose(rgbFile);
} }
static int WriteLogo(int fd, const std::string &logoPath) static int WriteLogo(int fd, const std::string &logoPath)
{ {
if (fd < 0 || logoPath.empty()) {
std::cout << "Invalid arguments\n";
return -1;
}
int addrOffset = (PARTITION_INFO_POS + PARTITION_INFO_MAX_LENGTH + BLOCK_SZIE_1 - 1) / BLOCK_SZIE_1; int addrOffset = (PARTITION_INFO_POS + PARTITION_INFO_MAX_LENGTH + BLOCK_SZIE_1 - 1) / BLOCK_SZIE_1;
if (lseek(fd, addrOffset * BLOCK_SZIE_1, SEEK_SET) < 0) { if (lseek(fd, addrOffset * BLOCK_SZIE_1, SEEK_SET) < 0) {
BSH_LOGI("Failed lseek logoPath %s errno %d ", logoPath.c_str(), errno); BSH_LOGI("Failed lseek logoPath %s errno %d ", logoPath.c_str(), errno);
...@@ -116,11 +96,12 @@ static int WriteLogo(int fd, const std::string &logoPath) ...@@ -116,11 +96,12 @@ static int WriteLogo(int fd, const std::string &logoPath)
BSH_LOGI("Failed magic logoPath %s errno %d ", logoPath.c_str(), errno); BSH_LOGI("Failed magic logoPath %s errno %d ", logoPath.c_str(), errno);
return -1; return -1;
} }
#ifndef STARTUP_INIT_TEST
if (magic == LOGO_MAGIC) { if (magic == LOGO_MAGIC) {
BSH_LOGI("Get matched magic number, logo already written\n"); BSH_LOGI("Get matched magic number, logo already written\n");
return 0; return 0;
} }
#endif
struct stat st {}; struct stat st {};
magic = LOGO_MAGIC; magic = LOGO_MAGIC;
lseek(fd, addrOffset * BLOCK_SZIE_1, SEEK_SET); lseek(fd, addrOffset * BLOCK_SZIE_1, SEEK_SET);
...@@ -162,28 +143,23 @@ static void WriteLogoToMisc(const std::string &logoPath) ...@@ -162,28 +143,23 @@ static void WriteLogoToMisc(const std::string &logoPath)
std::cout << "logo path is empty\n"; std::cout << "logo path is empty\n";
return; return;
} }
std::string miscDev = GetMiscDevicePath(); int fd = open(MISC_DEVICE_NODE, O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (miscDev.empty()) {
return;
}
BSH_LOGI("WriteLogoToMisc miscDev %s ", miscDev.c_str());
int fd = open(miscDev.c_str(), O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) { if (fd < 0) {
BSH_LOGI("Failed to writeLogoToMisc miscDev %s errno %d ", miscDev.c_str(), errno); BSH_LOGI("Failed to writeLogoToMisc errno %d ", errno);
return; return;
} }
if (WriteLogo(fd, logoPath) < 0) { if (WriteLogo(fd, logoPath) < 0) {
BSH_LOGI("Failed WriteLogo miscDev %s errno %d ", miscDev.c_str(), errno); BSH_LOGI("Failed WriteLogo errno %d ", errno);
} }
close(fd); close(fd);
int addrOffset = (PARTITION_INFO_POS + PARTITION_INFO_MAX_LENGTH + BLOCK_SZIE_1 - 1) / BLOCK_SZIE_1; int addrOffset = (PARTITION_INFO_POS + PARTITION_INFO_MAX_LENGTH + BLOCK_SZIE_1 - 1) / BLOCK_SZIE_1;
int fd1 = open(miscDev.c_str(), O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); int fd1 = open(MISC_DEVICE_NODE, O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd1 < 0) { if (fd1 < 0) {
return; return;
} }
if (lseek(fd1, addrOffset * BLOCK_SZIE_1, SEEK_SET) < 0) { if (lseek(fd1, addrOffset * BLOCK_SZIE_1, SEEK_SET) < 0) {
BSH_LOGI("Failed lseek miscDev %s errno %d ", miscDev.c_str(), errno); BSH_LOGI("Failed lseek errno %d ", errno);
close(fd1); close(fd1);
return; return;
} }
...@@ -191,12 +167,12 @@ static void WriteLogoToMisc(const std::string &logoPath) ...@@ -191,12 +167,12 @@ static void WriteLogoToMisc(const std::string &logoPath)
uint32_t magic = 0; uint32_t magic = 0;
uint32_t size = 0; uint32_t size = 0;
if (read(fd1, &magic, sizeof(uint32_t)) != sizeof(uint32_t)) { if (read(fd1, &magic, sizeof(uint32_t)) != sizeof(uint32_t)) {
BSH_LOGI("Failed read miscDev %s errno %d ", miscDev.c_str(), errno); BSH_LOGI("Failed read errno %d ", errno);
close(fd1); close(fd1);
return; return;
} }
if (read(fd1, &size, sizeof(uint32_t)) != sizeof(uint32_t)) { if (read(fd1, &size, sizeof(uint32_t)) != sizeof(uint32_t)) {
BSH_LOGI("Failed read migic miscDev %s errno %d ", miscDev.c_str(), errno); BSH_LOGI("Failed read migic errno %d ", errno);
close(fd1); close(fd1);
return; return;
} }
......
...@@ -29,7 +29,7 @@ static int LoadDevice() ...@@ -29,7 +29,7 @@ static int LoadDevice()
if (devmgr != nullptr) { if (devmgr != nullptr) {
return devmgr->LoadDevice("partition_slot_service"); return devmgr->LoadDevice("partition_slot_service");
} else { } else {
std::cout << "Get devmgr failed" << std::endl; std::cout << "Load devmgr failed" << std::endl;
return -1; return -1;
} }
} }
...@@ -39,27 +39,22 @@ static void UnloadDevice() ...@@ -39,27 +39,22 @@ static void UnloadDevice()
auto devmgr = IDeviceManager::Get(); auto devmgr = IDeviceManager::Get();
if (devmgr != nullptr) { if (devmgr != nullptr) {
devmgr->UnloadDevice("partition_slot_service"); devmgr->UnloadDevice("partition_slot_service");
} else {
std::cout << "Get devmgr failed" << std::endl;
} }
} }
static int GetSlot(BShellHandle handle, int32_t argc, char *argv[]) static int GetSlot(BShellHandle handle, int32_t argc, char *argv[])
{ {
if (LoadDevice() != 0) { if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1; return -1;
} }
std::cout << "Command: partitionslot getslot" << std::endl; std::cout << "Command: partitionslot getslot" << std::endl;
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get(); sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
int bootSlots = 0; int bootSlots = 0;
int currentSlot = 0; int currentSlot = 0;
if (partitionslot == nullptr) { if (partitionslot != nullptr) {
std::cout << "Get partitionslot failed" << std::endl; partitionslot->GetCurrentSlot(currentSlot, bootSlots);
return -1; std::cout << "The number of slots: " << bootSlots << "," << "current slot: " << currentSlot << std::endl;
} }
partitionslot->GetCurrentSlot(currentSlot, bootSlots);
std::cout << "The number of slots: " << bootSlots << "," << "current slot: " << currentSlot << std::endl;
UnloadDevice(); UnloadDevice();
return 0; return 0;
} }
...@@ -71,19 +66,16 @@ static int GetSuffix(BShellHandle handle, int32_t argc, char *argv[]) ...@@ -71,19 +66,16 @@ static int GetSuffix(BShellHandle handle, int32_t argc, char *argv[])
return -1; return -1;
} }
if (LoadDevice() != 0) { if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1; return -1;
} }
std::cout << "Command: partitionslot getsuffix" << std::endl; std::cout << "Command: partitionslot getsuffix" << std::endl;
int slot = atoi(argv[1]); int slot = atoi(argv[1]);
std::string suffix = ""; std::string suffix = "";
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get(); sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) { if (partitionslot != nullptr) {
std::cout << "Get partitionslot failed" << std::endl; partitionslot->GetSlotSuffix(slot, suffix);
return -1; std::cout << "The slot " << slot << " matches with suffix: " << suffix << std::endl;
} }
partitionslot->GetSlotSuffix(slot, suffix);
std::cout << "The slot " << slot << " matches with suffix: " << suffix << std::endl;
UnloadDevice(); UnloadDevice();
return 0; return 0;
} }
...@@ -95,18 +87,15 @@ static int SetActiveSlot(BShellHandle handle, int32_t argc, char *argv[]) ...@@ -95,18 +87,15 @@ static int SetActiveSlot(BShellHandle handle, int32_t argc, char *argv[])
return -1; return -1;
} }
if (LoadDevice() != 0) { if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1; return -1;
} }
std::cout << "Command: partitionslot setactive" << std::endl; std::cout << "Command: partitionslot setactive" << std::endl;
int slot = atoi(argv[1]); int slot = atoi(argv[1]);
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get(); sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) { if (partitionslot != nullptr) {
std::cout << "Get partitionslot failed" << std::endl; partitionslot->SetActiveSlot(slot);
return -1; std::cout << "Set active slot: " << slot << std::endl;
} }
partitionslot->SetActiveSlot(slot);
std::cout << "Set active slot: " << slot << std::endl;
UnloadDevice(); UnloadDevice();
return 0; return 0;
} }
...@@ -118,18 +107,15 @@ static int SetUnbootSlot(BShellHandle handle, int32_t argc, char *argv[]) ...@@ -118,18 +107,15 @@ static int SetUnbootSlot(BShellHandle handle, int32_t argc, char *argv[])
return -1; return -1;
} }
if (LoadDevice() != 0) { if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1; return -1;
} }
std::cout << "Command: partitionslot setunboot" << std::endl; std::cout << "Command: partitionslot setunboot" << std::endl;
int slot = atoi(argv[1]); int slot = atoi(argv[1]);
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get(); sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) { if (partitionslot != nullptr) {
std::cout << "Get partitionslot failed" << std::endl; partitionslot->SetSlotUnbootable(slot);
return -1; std::cout << "Set unboot slot: " << slot << std::endl;
} }
partitionslot->SetSlotUnbootable(slot);
std::cout << "Set unboot slot: " << slot << std::endl;
UnloadDevice(); UnloadDevice();
return 0; return 0;
} }
......
...@@ -47,14 +47,13 @@ static void Usage() ...@@ -47,14 +47,13 @@ static void Usage()
std::cout << "sandbox -n, --namespace_name=namespace name \"namespace name, system, chipset etc.\"" << std::endl; std::cout << "sandbox -n, --namespace_name=namespace name \"namespace name, system, chipset etc.\"" << std::endl;
std::cout << "sandbox -p, --process=process name \"sh, hdcd, hdf_devhost, etc.\"" << std::endl; std::cout << "sandbox -p, --process=process name \"sh, hdcd, hdf_devhost, etc.\"" << std::endl;
std::cout << "sandbox -h, --help \"Show help\"" << std::endl; std::cout << "sandbox -h, --help \"Show help\"" << std::endl;
#ifndef STARTUP_INIT_TEST
exit(0); exit(0);
#endif
} }
static void RunSandbox(const std::string &sandboxName) static void RunSandbox(const std::string &sandboxName)
{ {
if (sandboxName.empty()) {
return;
}
InitDefaultNamespace(); InitDefaultNamespace();
if (!InitSandboxWithName(sandboxName.c_str())) { if (!InitSandboxWithName(sandboxName.c_str())) {
std::cout << "Init sandbox failed." << std::endl; std::cout << "Init sandbox failed." << std::endl;
...@@ -85,10 +84,6 @@ static void EnterShell() ...@@ -85,10 +84,6 @@ static void EnterShell()
static const int MAX_PROCESS_ARGC = 8; static const int MAX_PROCESS_ARGC = 8;
static void EnterExec(const std::string &processName) static void EnterExec(const std::string &processName)
{ {
if (processName.empty()) {
std::cout << "process name is nullptr." << std::endl;
return;
}
std::string tmpName = processName; std::string tmpName = processName;
std::vector<std::string> vtr; std::vector<std::string> vtr;
const std::string sep = " "; const std::string sep = " ";
......
...@@ -47,8 +47,9 @@ static int main_cmd(BShellHandle shell, int argc, char **argv) ...@@ -47,8 +47,9 @@ static int main_cmd(BShellHandle shell, int argc, char **argv)
} else if (strcmp(argv[0], "stop") == 0) { } else if (strcmp(argv[0], "stop") == 0) {
ServiceControlWithExtra(argv[1], 1, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER); ServiceControlWithExtra(argv[1], 1, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER);
} else if (strcmp(argv[0], "timer_start") == 0) { } else if (strcmp(argv[0], "timer_start") == 0) {
if (argc < SERVICE_START_NUMBER) { if (argc <= SERVICE_START_NUMBER) {
return -1; ServiceControlUsage(shell, argc, argv);
return 0;
} }
char *timeBuffer = argv[SERVICE_START_NUMBER]; char *timeBuffer = argv[SERVICE_START_NUMBER];
errno = 0; errno = 0;
......
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
static BootchartCtrl *g_bootchartCtrl = NULL; static BootchartCtrl *g_bootchartCtrl = NULL;
static long long GetJiffies(void) BOOTCHART_STATIC long long GetJiffies(void)
{ {
struct timespec time1 = {0}; struct timespec time1 = {0};
clock_gettime(CLOCK_MONOTONIC, &time1); clock_gettime(CLOCK_MONOTONIC, &time1);
...@@ -63,7 +63,7 @@ char *ReadFileToBuffer(const char *fileName, char *buffer, uint32_t bufferSize) ...@@ -63,7 +63,7 @@ char *ReadFileToBuffer(const char *fileName, char *buffer, uint32_t bufferSize)
return (readLen > 0) ? buffer : NULL; return (readLen > 0) ? buffer : NULL;
} }
static void BootchartLogHeader(void) BOOTCHART_STATIC void BootchartLogHeader(void)
{ {
char date[32]; // 32 data size char date[32]; // 32 data size
time_t tm = time(NULL); time_t tm = time(NULL);
...@@ -97,7 +97,7 @@ static void BootchartLogHeader(void) ...@@ -97,7 +97,7 @@ static void BootchartLogHeader(void)
(void)fclose(file); (void)fclose(file);
} }
static void BootchartLogFile(FILE *log, const char *procfile) BOOTCHART_STATIC void BootchartLogFile(FILE *log, const char *procfile)
{ {
(void)fprintf(log, "%lld\n", GetJiffies()); (void)fprintf(log, "%lld\n", GetJiffies());
char *data = ReadFileToBuffer(procfile, g_bootchartCtrl->buffer, g_bootchartCtrl->bufferSize); char *data = ReadFileToBuffer(procfile, g_bootchartCtrl->buffer, g_bootchartCtrl->bufferSize);
...@@ -106,7 +106,7 @@ static void BootchartLogFile(FILE *log, const char *procfile) ...@@ -106,7 +106,7 @@ static void BootchartLogFile(FILE *log, const char *procfile)
} }
} }
static void BootchartLogProcessStat(FILE *log, pid_t pid) BOOTCHART_STATIC void BootchartLogProcessStat(FILE *log, pid_t pid)
{ {
static char path[255] = { }; // 255 path length static char path[255] = { }; // 255 path length
static char nameBuffer[255] = { }; // 255 path length static char nameBuffer[255] = { }; // 255 path length
...@@ -143,7 +143,7 @@ static void BootchartLogProcessStat(FILE *log, pid_t pid) ...@@ -143,7 +143,7 @@ static void BootchartLogProcessStat(FILE *log, pid_t pid)
} }
} }
static void bootchartLogProcess(FILE *log) BOOTCHART_STATIC void bootchartLogProcess(FILE *log)
{ {
(void)fprintf(log, "%lld\n", GetJiffies()); (void)fprintf(log, "%lld\n", GetJiffies());
DIR *pDir = opendir("/proc"); DIR *pDir = opendir("/proc");
...@@ -160,7 +160,7 @@ static void bootchartLogProcess(FILE *log) ...@@ -160,7 +160,7 @@ static void bootchartLogProcess(FILE *log)
(void)fputc('\n', log); (void)fputc('\n', log);
} }
static void *BootchartThreadMain(void *data) BOOTCHART_STATIC void *BootchartThreadMain(void *data)
{ {
PLUGIN_LOGI("bootcharting start"); PLUGIN_LOGI("bootcharting start");
FILE *statFile = fopen(BOOTCHART_OUTPUT_PATH"proc_stat.log", "w"); FILE *statFile = fopen(BOOTCHART_OUTPUT_PATH"proc_stat.log", "w");
...@@ -210,7 +210,7 @@ static void *BootchartThreadMain(void *data) ...@@ -210,7 +210,7 @@ static void *BootchartThreadMain(void *data)
return NULL; return NULL;
} }
static void BootchartDestory(void) BOOTCHART_STATIC void BootchartDestory(void)
{ {
pthread_mutex_destroy(&(g_bootchartCtrl->mutex)); pthread_mutex_destroy(&(g_bootchartCtrl->mutex));
pthread_cond_destroy(&(g_bootchartCtrl->cond)); pthread_cond_destroy(&(g_bootchartCtrl->cond));
...@@ -218,7 +218,7 @@ static void BootchartDestory(void) ...@@ -218,7 +218,7 @@ static void BootchartDestory(void)
g_bootchartCtrl = NULL; g_bootchartCtrl = NULL;
} }
static int DoBootchartStart(void) BOOTCHART_STATIC int DoBootchartStart(void)
{ {
if (g_bootchartCtrl != NULL) { if (g_bootchartCtrl != NULL) {
PLUGIN_LOGI("bootcharting has been start"); PLUGIN_LOGI("bootcharting has been start");
...@@ -247,7 +247,7 @@ static int DoBootchartStart(void) ...@@ -247,7 +247,7 @@ static int DoBootchartStart(void)
return 0; return 0;
} }
static int DoBootchartStop(void) BOOTCHART_STATIC int DoBootchartStop(void)
{ {
if (g_bootchartCtrl == NULL || !g_bootchartCtrl->start) { if (g_bootchartCtrl == NULL || !g_bootchartCtrl->start) {
PLUGIN_LOGI("bootcharting not start"); PLUGIN_LOGI("bootcharting not start");
...@@ -263,7 +263,7 @@ static int DoBootchartStop(void) ...@@ -263,7 +263,7 @@ static int DoBootchartStop(void)
return 0; return 0;
} }
static int DoBootchartCmd(int id, const char *name, int argc, const char **argv) BOOTCHART_STATIC int DoBootchartCmd(int id, const char *name, int argc, const char **argv)
{ {
PLUGIN_LOGI("DoBootchartCmd argc %d %s", argc, name); PLUGIN_LOGI("DoBootchartCmd argc %d %s", argc, name);
PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter"); PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter");
...@@ -276,7 +276,7 @@ static int DoBootchartCmd(int id, const char *name, int argc, const char **argv) ...@@ -276,7 +276,7 @@ static int DoBootchartCmd(int id, const char *name, int argc, const char **argv)
} }
static int32_t g_executorId = -1; static int32_t g_executorId = -1;
static int BootchartInit(void) BOOTCHART_STATIC int BootchartInit(void)
{ {
if (g_executorId == -1) { if (g_executorId == -1) {
g_executorId = AddCmdExecutor("bootchart", DoBootchartCmd); g_executorId = AddCmdExecutor("bootchart", DoBootchartCmd);
...@@ -285,7 +285,7 @@ static int BootchartInit(void) ...@@ -285,7 +285,7 @@ static int BootchartInit(void)
return 0; return 0;
} }
static void BootchartExit(void) BOOTCHART_STATIC void BootchartExit(void)
{ {
PLUGIN_LOGI("BootchartExit executorId %d", g_executorId); PLUGIN_LOGI("BootchartExit executorId %d", g_executorId);
if (g_executorId != -1) { if (g_executorId != -1) {
......
...@@ -29,4 +29,10 @@ typedef struct { ...@@ -29,4 +29,10 @@ typedef struct {
char buffer[DEFAULT_BUFFER]; char buffer[DEFAULT_BUFFER];
} BootchartCtrl; } BootchartCtrl;
#ifdef STARTUP_INIT_TEST
#define BOOTCHART_STATIC
#else
#define BOOTCHART_STATIC static
#endif
#endif /* _PLUGIN_BOOTCHART_H */ #endif /* _PLUGIN_BOOTCHART_H */
...@@ -17,6 +17,8 @@ config("utest_config") { ...@@ -17,6 +17,8 @@ config("utest_config") {
visibility = [ ":*" ] visibility = [ ":*" ]
cflags = [ cflags = [
"-fprofile-arcs",
"-ftest-coverage",
"-Wno-implicit-fallthrough", "-Wno-implicit-fallthrough",
"-Wno-unused-function", "-Wno-unused-function",
] ]
...@@ -24,6 +26,7 @@ config("utest_config") { ...@@ -24,6 +26,7 @@ config("utest_config") {
"-Wno-implicit-fallthrough", "-Wno-implicit-fallthrough",
"-fexceptions", "-fexceptions",
] ]
ldflags = [ "--coverage" ]
} }
FSCRYPT_PATH = FSCRYPT_PATH =
...@@ -34,6 +37,10 @@ ohos_unittest("init_unittest") { ...@@ -34,6 +37,10 @@ ohos_unittest("init_unittest") {
sources = [ sources = [
"//base/startup/init/device_info/device_info.cpp", "//base/startup/init/device_info/device_info.cpp",
"//base/startup/init/device_info/device_info_stub.cpp", "//base/startup/init/device_info/device_info_stub.cpp",
"//base/startup/init/interfaces/innerkits/control_fd/control_fd_client.c",
"//base/startup/init/interfaces/innerkits/control_fd/control_fd_service.c",
"//base/startup/init/interfaces/innerkits/fd_holder/fd_holder.c",
"//base/startup/init/interfaces/innerkits/fd_holder/fd_holder_internal.c",
"//base/startup/init/interfaces/innerkits/file/init_file.c", "//base/startup/init/interfaces/innerkits/file/init_file.c",
"//base/startup/init/interfaces/innerkits/fs_manager/fstab.c", "//base/startup/init/interfaces/innerkits/fs_manager/fstab.c",
"//base/startup/init/interfaces/innerkits/fs_manager/fstab_mount.c", "//base/startup/init/interfaces/innerkits/fs_manager/fstab_mount.c",
...@@ -44,7 +51,15 @@ ohos_unittest("init_unittest") { ...@@ -44,7 +51,15 @@ ohos_unittest("init_unittest") {
"//base/startup/init/interfaces/innerkits/syspara/param_comm.c", "//base/startup/init/interfaces/innerkits/syspara/param_comm.c",
"//base/startup/init/interfaces/innerkits/syspara/parameter.c", "//base/startup/init/interfaces/innerkits/syspara/parameter.c",
"//base/startup/init/interfaces/innerkits/syspara/sysversion.c", "//base/startup/init/interfaces/innerkits/syspara/sysversion.c",
"//base/startup/init/services/begetctl/bootchart_cmd.c",
"//base/startup/init/services/begetctl/dump_service.c",
"//base/startup/init/services/begetctl/init_cmd_reboot.c",
"//base/startup/init/services/begetctl/misc_daemon.cpp",
"//base/startup/init/services/begetctl/modulectl.c",
"//base/startup/init/services/begetctl/param_cmd.c", "//base/startup/init/services/begetctl/param_cmd.c",
"//base/startup/init/services/begetctl/sandbox.cpp",
"//base/startup/init/services/begetctl/service_control.c",
"//base/startup/init/services/begetctl/setloglevel.c",
"//base/startup/init/services/begetctl/shell/shell_bas.c", "//base/startup/init/services/begetctl/shell/shell_bas.c",
"//base/startup/init/services/begetctl/shell/shell_main.c", "//base/startup/init/services/begetctl/shell/shell_main.c",
"//base/startup/init/services/init/adapter/init_adapter.c", "//base/startup/init/services/init/adapter/init_adapter.c",
...@@ -78,6 +93,8 @@ ohos_unittest("init_unittest") { ...@@ -78,6 +93,8 @@ ohos_unittest("init_unittest") {
"//base/startup/init/services/loopevent/task/le_watchtask.c", "//base/startup/init/services/loopevent/task/le_watchtask.c",
"//base/startup/init/services/loopevent/timer/le_timer.c", "//base/startup/init/services/loopevent/timer/le_timer.c",
"//base/startup/init/services/loopevent/utils/le_utils.c", "//base/startup/init/services/loopevent/utils/le_utils.c",
"//base/startup/init/services/modules/bootchart/bootchart.c",
"//base/startup/init/services/modules/bootchart/bootchart_static.c",
"//base/startup/init/services/modules/bootevent/bootevent.c", "//base/startup/init/services/modules/bootevent/bootevent.c",
"//base/startup/init/services/modules/init_hook/init_hook.c", "//base/startup/init/services/modules/init_hook/init_hook.c",
"//base/startup/init/services/modules/init_hook/param_hook.c", "//base/startup/init/services/modules/init_hook/param_hook.c",
...@@ -147,6 +164,7 @@ ohos_unittest("init_unittest") { ...@@ -147,6 +164,7 @@ ohos_unittest("init_unittest") {
"init/service_socket_unittest.cpp", "init/service_socket_unittest.cpp",
"init/utils_unittest.cpp", "init/utils_unittest.cpp",
"innerkits/innerkits_unittest.cpp", "innerkits/innerkits_unittest.cpp",
"modules/modules_unittest.cpp",
"param/client_unittest.cpp", "param/client_unittest.cpp",
"param/dac_unittest.cpp", "param/dac_unittest.cpp",
"param/param_shell_unittest.cpp", "param/param_shell_unittest.cpp",
...@@ -156,6 +174,7 @@ ohos_unittest("init_unittest") { ...@@ -156,6 +174,7 @@ ohos_unittest("init_unittest") {
"param/trigger_unittest.cpp", "param/trigger_unittest.cpp",
"syspara/syspara_unittest.cpp", "syspara/syspara_unittest.cpp",
"ueventd/ueventd_config_unittest.cpp", "ueventd/ueventd_config_unittest.cpp",
"ueventd/ueventd_event_unittest.cpp",
] ]
sources += [ sources += [
...@@ -195,6 +214,7 @@ ohos_unittest("init_unittest") { ...@@ -195,6 +214,7 @@ ohos_unittest("init_unittest") {
"//base/startup/init/services/loopevent/timer", "//base/startup/init/services/loopevent/timer",
"//base/startup/init/services/loopevent/utils", "//base/startup/init/services/loopevent/utils",
"//base/startup/init/services/modules", "//base/startup/init/services/modules",
"//base/startup/init/services/modules/bootchart",
"//base/startup/init/services/modules/init_hook", "//base/startup/init/services/modules/init_hook",
"//base/startup/init/services/modules/selinux", "//base/startup/init/services/modules/selinux",
"//base/startup/init/services/modules/reboot", "//base/startup/init/services/modules/reboot",
...@@ -260,6 +280,15 @@ ohos_unittest("init_unittest") { ...@@ -260,6 +280,15 @@ ohos_unittest("init_unittest") {
"init:libinit_module_engine", "init:libinit_module_engine",
] ]
if (enable_ohos_startup_init_feature_ab_partition) {
include_dirs += [ "//drivers/hdf_core/adapter/uhdf2/include" ]
sources += [ "//base/startup/init/services/begetctl/partitionslot.cpp" ]
external_deps += [
"drivers_interface_partitionslot:libpartitionslot_proxy_1.0",
"hdf_core:libhdi",
]
}
if (!defined(ohos_lite) && enable_ohos_startup_init_feature_watcher) { if (!defined(ohos_lite) && enable_ohos_startup_init_feature_watcher) {
sources += [ sources += [
"param/watcher_agent_unittest.cpp", "param/watcher_agent_unittest.cpp",
......
...@@ -137,4 +137,456 @@ HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1) ...@@ -137,4 +137,456 @@ HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1)
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args)); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
} }
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_1, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getslot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_2, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getsuffix", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_3, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setactive", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_4, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setunboot", "2"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_5, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setactive"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_6, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setunboot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_7, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getsuffix"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_1, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_2, TestSize.Level1)
{
const char *args[] = {
"get", "log", "level"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_3, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_4, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "1000"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_5, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "a"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_1, TestSize.Level1)
{
const char *args[] = {
"bootchart", "enable"
};
SystemWriteParam("persist.init.bootchart.enabled", "1");
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_2, TestSize.Level1)
{
const char *args[] = {
"bootchart", "start"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_3, TestSize.Level1)
{
const char *args[] = {
"bootchart", "stop"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_4, TestSize.Level1)
{
const char *args[] = {
"bootchart", "disable"
};
SystemWriteParam("persist.init.bootchart.enabled", "0");
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_5, TestSize.Level1)
{
const char *args[] = {
"bootchart"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_1, TestSize.Level1)
{
const char *args[] = {
"bootevent", "enable"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_2, TestSize.Level1)
{
const char *args[] = {
"bootevent", "disable"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_3, TestSize.Level1)
{
const char *args[] = {
"dump_service", "all"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_4, TestSize.Level1)
{
const char *args[] = {
"dump_service", "param_watcher"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_5, TestSize.Level1)
{
const char *args[] = {
"dump_service", "parameter-service", "trigger"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo", BOOT_CMD_LINE
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_1, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo1111", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_2, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo", ""
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_3, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_4, TestSize.Level1)
{
// clear misc logo
const char *args[] = {
"misc_daemon", "--write_logo", "sssssssss"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_1, TestSize.Level1)
{
const char *args[] = {
"modulectl", "install", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_2, TestSize.Level1)
{
const char *args[] = {
"modulectl", "uninstall", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_3, TestSize.Level1)
{
const char *args[] = {
"modulectl", "list", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_4, TestSize.Level1)
{
const char *args[] = {
"modulectl", "install"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_5, TestSize.Level1)
{
const char *args[] = {
"modulectl", "list"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_1, TestSize.Level1)
{
const char *args[] = {
"service_control", "stop", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_2, TestSize.Level1)
{
const char *args[] = {
"service_control", "start", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_3, TestSize.Level1)
{
const char *args[] = {
"stop_service", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_4, TestSize.Level1)
{
const char *args[] = {
"start_service", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_5, TestSize.Level1)
{
const char *args[] = {
"timer_stop", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_6, TestSize.Level1)
{
const char *args[] = {
"timer_stop"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_7, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service", "10"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_8, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service",
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_9, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service", "ww"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_10, TestSize.Level1)
{
const char *args[] = {
"xxxxxxxxxxxxxx", "test-service", "ww"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_1, TestSize.Level1)
{
const char *args[] = {
"setloglevel", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_2, TestSize.Level1)
{
const char *args[] = {
"getloglevel"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_3, TestSize.Level1)
{
const char *args[] = {
"setloglevel", "a"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_4, TestSize.Level1)
{
const char *args[] = {
"setloglevel"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSandbox, TestSize.Level1)
{
const char *args[] = {
"sandbox", "-s", "test", "-n", "test2", "-p", "test3", "-h", "?"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_1, TestSize.Level1)
{
const char *args[] = {
"reboot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_2, TestSize.Level1)
{
const char *args[] = {
"reboot", "shutdown"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_3, TestSize.Level1)
{
const char *args[] = {
"reboot", "charge"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_4, TestSize.Level1)
{
const char *args[] = {
"reboot", "updater"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_5, TestSize.Level1)
{
const char *args[] = {
"reboot", "updater:aaaaaaa"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_6, TestSize.Level1)
{
const char *args[] = {
"reboot", "flashd:aaaaaaa"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_7, TestSize.Level1)
{
const char *args[] = {
"reboot", "flashd"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_8, TestSize.Level1)
{
const char *args[] = {
"reboot", "suspend"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_9, TestSize.Level1)
{
const char *args[] = {
"reboot", "222222222"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
} // namespace init_ut } // namespace init_ut
...@@ -326,6 +326,7 @@ HWTEST_F(ServiceUnitTest, TestServiceBootEventHook, TestSize.Level1) ...@@ -326,6 +326,7 @@ HWTEST_F(ServiceUnitTest, TestServiceBootEventHook, TestSize.Level1)
SystemWriteParam("bootevent.bootevent2", "true"); SystemWriteParam("bootevent.bootevent2", "true");
SystemWriteParam("persist.init.bootevent.enable", "false"); SystemWriteParam("persist.init.bootevent.enable", "false");
HookMgrExecute(GetBootStageHookMgr(), INIT_POST_PERSIST_PARAM_LOAD, NULL, NULL); HookMgrExecute(GetBootStageHookMgr(), INIT_POST_PERSIST_PARAM_LOAD, NULL, NULL);
CloseTriggerWorkSpace();
cJSON_Delete(fileRoot); cJSON_Delete(fileRoot);
} }
......
...@@ -17,15 +17,39 @@ ...@@ -17,15 +17,39 @@
#include <sys/mount.h> #include <sys/mount.h>
#include "fs_manager/fs_manager.h" #include "fs_manager/fs_manager.h"
#include "init_log.h" #include "init_log.h"
#include "init_param.h"
#include "param_stub.h" #include "param_stub.h"
#include "securec.h" #include "securec.h"
#include "systemcapability.h" #include "systemcapability.h"
#include "service_control.h" #include "service_control.h"
#include "control_fd.h"
#include "loop_event.h"
#include "fd_holder.h"
#include "fd_holder_internal.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
namespace init_ut { namespace init_ut {
extern "C" {
void CmdDisConnectComplete(const TaskHandle client);
void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle handle);
void CmdOnClose(const TaskHandle task);
void CmdOnConnectComplete(const TaskHandle client);
void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen);
int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd);
void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context);
void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context);
int CmdOnIncommingConnect(const LoopHandle loop, const TaskHandle server);
CmdAgent *CmdAgentCreate(const char *server);
void CmdClientOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen);
int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *ptyName);
int SendMessage(LoopHandle loop, TaskHandle task, const char *message);
int *GetFdsFromMsg(size_t *outFdCount, pid_t *requestPid, struct msghdr msghdr);
int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll);
}
class InnerkitsUnitTest : public testing::Test { class InnerkitsUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
...@@ -47,7 +71,7 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1) ...@@ -47,7 +71,7 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1)
const std::string fstabFile1 = "/data/fstab.updater1"; const std::string fstabFile1 = "/data/fstab.updater1";
fstab = ReadFstabFromFile(fstabFile1.c_str(), false); fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
EXPECT_EQ(fstab, nullptr); EXPECT_EQ(fstab, nullptr);
const std::string fstabFile2 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; const std::string fstabFile2 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
fstab = ReadFstabFromFile(fstabFile2.c_str(), false); fstab = ReadFstabFromFile(fstabFile2.c_str(), false);
EXPECT_NE(fstab, nullptr); EXPECT_NE(fstab, nullptr);
ParseFstabPerLine(const_cast<char *>("test"), fstab, true, nullptr); ParseFstabPerLine(const_cast<char *>("test"), fstab, true, nullptr);
...@@ -63,7 +87,7 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1) ...@@ -63,7 +87,7 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1)
*/ */
HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1)
{ {
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr; Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false); fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr); ASSERT_NE(fstab, nullptr);
...@@ -101,7 +125,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1) ...@@ -101,7 +125,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1)
*/ */
HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1)
{ {
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr; Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false); fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr); ASSERT_NE(fstab, nullptr);
...@@ -130,7 +154,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1) ...@@ -130,7 +154,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1)
*/ */
HWTEST_F(InnerkitsUnitTest, GetMountFlags_unitest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, GetMountFlags_unitest, TestSize.Level1)
{ {
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr; Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), true); fstab = ReadFstabFromFile(fstabFile1.c_str(), true);
ASSERT_NE(fstab, nullptr); ASSERT_NE(fstab, nullptr);
...@@ -186,6 +210,9 @@ HWTEST_F(InnerkitsUnitTest, GetBlockDevicePath_unittest, TestSize.Level1) ...@@ -186,6 +210,9 @@ HWTEST_F(InnerkitsUnitTest, GetBlockDevicePath_unittest, TestSize.Level1)
EXPECT_EQ(GetBlockDevicePath("/vendor", devicePath, MAX_BUFFER_LEN), 0); EXPECT_EQ(GetBlockDevicePath("/vendor", devicePath, MAX_BUFFER_LEN), 0);
EXPECT_EQ(GetBlockDevicePath("/misc", devicePath, MAX_BUFFER_LEN), 0); EXPECT_EQ(GetBlockDevicePath("/misc", devicePath, MAX_BUFFER_LEN), 0);
EXPECT_EQ(GetBlockDevicePath("/invalid", devicePath, MAX_BUFFER_LEN), -1); EXPECT_EQ(GetBlockDevicePath("/invalid", devicePath, MAX_BUFFER_LEN), -1);
unlink(BOOT_CMD_LINE);
EXPECT_EQ(GetBlockDevicePath("/invalid", devicePath, MAX_BUFFER_LEN), -1);
EXPECT_NE(GetCurrentSlot(), 0);
} }
/** /**
...@@ -199,6 +226,8 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1) ...@@ -199,6 +226,8 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1)
{ {
EXPECT_NE(DoFormat("/testpath", "ext4"), -1); EXPECT_NE(DoFormat("/testpath", "ext4"), -1);
EXPECT_NE(DoFormat("/testpath", "f2fs"), -1); EXPECT_NE(DoFormat("/testpath", "f2fs"), -1);
EXPECT_EQ(DoFormat("/testpath", "notFs"), -1);
EXPECT_EQ(DoFormat(nullptr, nullptr), -1);
} }
/** /**
...@@ -210,9 +239,23 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1) ...@@ -210,9 +239,23 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1)
*/ */
HWTEST_F(InnerkitsUnitTest, MountAllWithFstabFile_unittest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, MountAllWithFstabFile_unittest, TestSize.Level1)
{ {
EXPECT_NE(MountAllWithFstabFile("/data/init_ut/etc/fstab.required", 0), 1); EXPECT_NE(MountAllWithFstabFile(STARTUP_INIT_UT_PATH"/etc/fstab.required", 0), 1);
EXPECT_NE(UmountAllWithFstabFile(STARTUP_INIT_UT_PATH"/etc/fstab.required"), 1);
EXPECT_EQ(MountAllWithFstabFile("/testErrorFile", 0), -1);
EXPECT_EQ(MountAllWithFstabFile(nullptr, 0), -1);
EXPECT_EQ(GetMountStatusForMountPoint(nullptr), -1);
FstabItem fstabItem;
fstabItem.fsType = strdup("notSupport");
EXPECT_EQ(MountOneItem(nullptr), -1);
EXPECT_EQ(MountOneItem(&fstabItem), 0);
if (fstabItem.fsType != nullptr) {
free(fstabItem.fsType);
fstabItem.fsType = nullptr;
}
} }
#define SYSCAP_MAX_SIZE 100
// TestSysCap // TestSysCap
HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1)
{ {
...@@ -224,14 +267,22 @@ HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1) ...@@ -224,14 +267,22 @@ HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1)
EXPECT_EQ(ret, true); EXPECT_EQ(ret, true);
ret = HasSystemCapability("SystemCapability.ArkUI.ArkUI.Napi"); ret = HasSystemCapability("SystemCapability.ArkUI.ArkUI.Napi");
EXPECT_EQ(ret, true); EXPECT_EQ(ret, true);
char *wrongName = (char *)malloc(SYSCAP_MAX_SIZE);
ASSERT_NE(wrongName, nullptr);
EXPECT_EQ(memset_s(wrongName, SYSCAP_MAX_SIZE, 1, SYSCAP_MAX_SIZE), 0);
HasSystemCapability(wrongName);
free(wrongName);
} }
// TestControlService // TestControlService
HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
{ {
TestSetParamCheckResult("startup.service.ctl.", 0777, 0);
ServiceControl("deviceinfoservice", START); ServiceControl("deviceinfoservice", START);
ServiceControl("deviceinfoservice", STOP); SystemWriteParam("startup.service.ctl.deviceinfoservice", "2");
ServiceControl("deviceinfoservice", RESTART); ServiceControl("deviceinfoservice", RESTART);
ServiceControl("deviceinfoservice", STOP);
SystemWriteParam("startup.service.ctl.deviceinfoservice", "0");
ServiceControl("param_watcher", RESTART); ServiceControl("param_watcher", RESTART);
EXPECT_EQ(ServiceControl(nullptr, RESTART), -1); EXPECT_EQ(ServiceControl(nullptr, RESTART), -1);
const char *argv[] = {"testArg"}; const char *argv[] = {"testArg"};
...@@ -239,6 +290,7 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1) ...@@ -239,6 +290,7 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
ServiceControlWithExtra(nullptr, RESTART, argv, 1); ServiceControlWithExtra(nullptr, RESTART, argv, 1);
ServiceControlWithExtra(nullptr, 3, argv, 1); // 3 is action ServiceControlWithExtra(nullptr, 3, argv, 1); // 3 is action
ServiceControlWithExtra("notservie", RESTART, argv, 1); ServiceControlWithExtra("notservie", RESTART, argv, 1);
ServiceControlWithExtra("deviceinfoservice", 3, argv, 1); // 3 is action
ServiceSetReady("deviceinfoservice"); ServiceSetReady("deviceinfoservice");
ServiceSetReady(nullptr); ServiceSetReady(nullptr);
ServiceWaitForStatus("deviceinfoservice", SERVICE_READY, 1); ServiceWaitForStatus("deviceinfoservice", SERVICE_READY, 1);
...@@ -250,4 +302,168 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1) ...@@ -250,4 +302,168 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
StopServiceTimer("deviceinfoservice"); StopServiceTimer("deviceinfoservice");
} }
static int TestIncommingConnect(const LoopHandle loop, const TaskHandle server)
{
UNUSED(loop);
UNUSED(server);
return 0;
}
// TestControlFd
HWTEST_F(InnerkitsUnitTest, TestControlFd, TestSize.Level1)
{
CmdClientInit("/data/testSock1", ACTION_DUMP, "cmd");
CmdClientInit("/data/testSock1", ACTION_DUMP, "cmd");
CmdClientInit(INIT_CONTROL_FD_SOCKET_PATH, ACTION_DUMP, nullptr);
CmdClientInit(nullptr, ACTION_DUMP, "cmd");
CmdDisConnectComplete(nullptr);
CmdOnSendMessageComplete(nullptr, nullptr);
CmdOnConnectComplete(nullptr);
CmdClientOnRecvMessage(nullptr, nullptr, 0);
CmdAgentCreate(nullptr);
CmdAgent *agent = CmdAgentCreate(INIT_CONTROL_FD_SOCKET_PATH);
EXPECT_NE(agent, nullptr);
SendCmdMessage(agent, ACTION_DUMP, "cmd", "test");
SendCmdMessage(agent, ACTION_DUMP, "cmd", nullptr);
SendMessage(nullptr, nullptr, nullptr);
uint32_t events = 0;
InitPtyInterface(agent, 0, "cmd");
InitPtyInterface(agent, 0, nullptr);
InitPtyInterface(nullptr, 0, nullptr);
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
CheckAndCreatFile("/data/init_ut/testInput", mode);
int fd = open("/data/init_ut/testInput", O_RDWR);
perror("write failed");
EXPECT_GT(fd, 0);
EXPECT_GT(write(fd, "test", strlen("test")), 0);
perror("write failed");
lseek(fd, 0, SEEK_SET);
ProcessPtyRead(nullptr, fd, &events, (void *)agent);
ProcessPtyRead(nullptr, fd, &events, (void *)agent);
ProcessPtyRead(nullptr, STDERR_FILENO, &events, nullptr);
lseek(fd, 0, SEEK_SET);
ProcessPtyWrite(nullptr, fd, &events, (void *)agent);
ProcessPtyWrite(nullptr, fd, &events, (void *)agent);
ProcessPtyWrite(nullptr, STDERR_FILENO, &events, nullptr);
close(fd);
CmdOnClose(agent->task);
}
HWTEST_F(InnerkitsUnitTest, TestControlFdServer, TestSize.Level1)
{
CmdServiceInit(nullptr, nullptr);
CmdServiceInit("/data/testSock1", [](uint16_t type, const char *serviceCmd, const void *context) {
UNUSED(type);
UNUSED(serviceCmd);
UNUSED(context);
});
TaskHandle testServer;
LE_StreamServerInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_SERVER | TASK_PIPE | TASK_TEST;
info.server = (char *)"/data/testSock1";
info.socketId = -1;
info.baseInfo.close = NULL;
info.disConnectComplete = NULL;
info.incommingConnect = TestIncommingConnect;
info.sendMessageComplete = NULL;
info.recvMessage = NULL;
(void)LE_CreateStreamServer(LE_GetDefaultLoop(), &testServer, &info);
CmdOnIncommingConnect(LE_GetDefaultLoop(), testServer);
CmdOnRecvMessage(testServer, nullptr, 0);
CmdMessage *cmdMsg = (CmdMessage *)malloc(sizeof(CmdMessage) + strlen("test"));
cmdMsg->type = ACTION_DUMP;
cmdMsg->ptyName[0] = '\0';;
CmdOnRecvMessage(testServer, (uint8_t *)(&cmdMsg), 0);
cmdMsg->type = ACTION_DUMP;
cmdMsg->cmd[0] = 'a';
cmdMsg->ptyName[0] = 'a';
CmdOnRecvMessage(testServer, (uint8_t *)(&cmdMsg), 0);
CmdServiceProcessDelClient(0);
CmdServiceProcessDelClient(0);
free(cmdMsg);
}
HWTEST_F(InnerkitsUnitTest, TestHoldFd, TestSize.Level1)
{
int fds1[] = {1, 0};
ServiceSaveFd("testServiceName", fds1, ARRAY_LENGTH(fds1));
ServiceSaveFd(nullptr, fds1, ARRAY_LENGTH(fds1));
ServiceSaveFdWithPoll("testServiceName", fds1, 0);
ServiceSaveFdWithPoll(nullptr, fds1, 0);
ServiceSaveFdWithPoll("testServiceName", fds1, ARRAY_LENGTH(fds1));
EXPECT_EQ(setenv("OHOS_FD_HOLD_testServiceName", "1 0", 0), 0);
size_t fdCount = 0;
int *fds = nullptr;
ServiceGetFd("testService", nullptr);
ServiceGetFd("testService", &fdCount);
char *wrongName = (char *)malloc(MAX_FD_HOLDER_BUFFER + 1);
ASSERT_NE(wrongName, nullptr);
EXPECT_EQ(memset_s(wrongName, MAX_FD_HOLDER_BUFFER + 1, 1, MAX_FD_HOLDER_BUFFER + 1), 0);
ServiceGetFd(wrongName, &fdCount);
BuildSendData(wrongName, 1, "testService", 0, 1);
BuildSendData(wrongName, 1, "testService", 0, 0);
BuildSendData(nullptr, 1, "testService", 0, 0);
free(wrongName);
fds = ServiceGetFd("testServiceName", &fdCount);
EXPECT_NE(fds, nullptr);
struct msghdr msghdr;
BuildControlMessage(nullptr, nullptr, 1, 0);
BuildControlMessage(&msghdr, nullptr, 1, 0);
BuildControlMessage(&msghdr, fds, -1, 0);
BuildControlMessage(&msghdr, fds, -1, 1);
if (fds != nullptr)
{
free(fds);
fds = nullptr;
}
}
HWTEST_F(InnerkitsUnitTest, TestHoldFd2, TestSize.Level1)
{
size_t fdCount = 0;
int *fds = nullptr;
char buffer[MAX_FD_HOLDER_BUFFER + 1] = {};
pid_t requestPid = -1;
struct msghdr msghdr;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
msghdr.msg_flags = MSG_TRUNC;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
msghdr.msg_flags = 0;
msghdr.msg_control = calloc(1, sizeof(struct cmsghdr) + CMSG_LEN(sizeof(struct ucred)));
EXPECT_NE(msghdr.msg_control, nullptr);
msghdr.msg_controllen = sizeof(struct cmsghdr);
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
struct iovec iovec = {
.iov_base = buffer,
.iov_len = MAX_FD_HOLDER_BUFFER,
};
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 0;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
((struct cmsghdr *)msghdr.msg_control)->cmsg_type = 1;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
((struct cmsghdr *)msghdr.msg_control)->cmsg_type = SCM_CREDENTIALS;
((struct cmsghdr *)msghdr.msg_control)->cmsg_len = CMSG_LEN(sizeof(struct ucred));
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
ReceiveFds(0, iovec, &fdCount, false, &requestPid);
fds = ReceiveFds(0, iovec, &fdCount, true, &requestPid);
if (fds != nullptr)
{
free(fds);
fds = nullptr;
}
if (msghdr.msg_control != nullptr) {
free(msghdr.msg_control);
}
}
} // namespace init_ut } // namespace init_ut
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "bootstage.h"
#include "init_cmds.h" #include "init_cmds.h"
#include "init_group_manager.h" #include "init_group_manager.h"
#include "init_hashmap.h" #include "init_hashmap.h"
...@@ -62,6 +63,7 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1) ...@@ -62,6 +63,7 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex); const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex);
ASSERT_EQ(strcmp(cmdName, testName), 0); ASSERT_EQ(strcmp(cmdName, testName), 0);
printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName); printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName);
ASSERT_NE(GetPluginCmdNameByIndex(cmdIndex), nullptr);
// exec // exec
g_cmdExecId = -1; g_cmdExecId = -1;
...@@ -72,9 +74,10 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1) ...@@ -72,9 +74,10 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
g_cmdExecId = -1; g_cmdExecId = -1;
PluginExecCmdByCmdIndex(cmdIndex, cmdContent); PluginExecCmdByCmdIndex(cmdIndex, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId); ASSERT_EQ(cmdExecId1, g_cmdExecId);
const char *argv[] = {"test"}; const char *argv[] = {"test.value"};
PluginExecCmd("install", 1, argv); PluginExecCmd("install", 1, argv);
PluginExecCmd("uninstall", 1, argv); PluginExecCmd("uninstall", 1, argv);
PluginExecCmd("setloglevel", 1, argv);
// del // del
RemoveCmdExecutor("testCmd4", cmdExecId4); RemoveCmdExecutor("testCmd4", cmdExecId4);
...@@ -86,19 +89,26 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1) ...@@ -86,19 +89,26 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
int cnt; int cnt;
// Create module manager // Create module manager
ASSERT_EQ(ModuleMgrCreate(nullptr), nullptr);
ModuleMgrDestroy(nullptr);
MODULE_MGR *moduleMgr = ModuleMgrCreate("init"); MODULE_MGR *moduleMgr = ModuleMgrCreate("init");
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
// Install one module // Install one module
#ifdef SUPPORT_64BIT
ret = ModuleMgrInstall(moduleMgr, "/system/lib64/init/libbootchart", 0, NULL);
#else
ret = ModuleMgrInstall(moduleMgr, "/system/lib/init/libbootchart", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "/system/lib/init/libbootchart", 0, NULL);
#endif
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
// Uninstall the module // Uninstall the module
ModuleMgrUninstall(moduleMgr, "bootchart"); ModuleMgrUninstall(moduleMgr, "bootchart");
InitModuleMgrUnInstall("bootchart");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
...@@ -122,17 +132,12 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1) ...@@ -122,17 +132,12 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
// Scan all modules // test updater mode
moduleMgr = ModuleMgrScan("init/autorun"); int fd = open("/bin/updater", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU);
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(fd, 0);
cnt = ModuleMgrGetCnt(moduleMgr); ModuleMgrScan("init/autorun");
ASSERT_GE(cnt, 0); unlink("/bin/updater");
close(fd);
ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0);
ModuleMgrGetArgs();
ModuleMgrDestroy(moduleMgr);
} }
static void TestModuleDump(const MODULE_INFO *moduleInfo) static void TestModuleDump(const MODULE_INFO *moduleInfo)
...@@ -152,7 +157,23 @@ HWTEST_F(ModuleMgrUnitTest, ModuleTraversalTest, TestSize.Level1) ...@@ -152,7 +157,23 @@ HWTEST_F(ModuleMgrUnitTest, ModuleTraversalTest, TestSize.Level1)
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
ModuleMgrTraversal(nullptr, nullptr, nullptr);
ModuleMgrTraversal(moduleMgr, NULL, TestModuleDump); ModuleMgrTraversal(moduleMgr, NULL, TestModuleDump);
InitModuleMgrDump();
// Scan all modules
ModuleMgrScan(nullptr);
moduleMgr = ModuleMgrScan("init/autorun");
ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_GE(cnt, 0);
ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0);
ModuleMgrGetArgs();
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
} }
...@@ -164,16 +185,23 @@ HWTEST_F(ModuleMgrUnitTest, ModuleScanTest, TestSize.Level1) ...@@ -164,16 +185,23 @@ HWTEST_F(ModuleMgrUnitTest, ModuleScanTest, TestSize.Level1)
int cnt = ModuleMgrGetCnt(moduleMgr); int cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_GE(cnt, 1); ASSERT_GE(cnt, 1);
ModuleMgrUninstall(nullptr, nullptr);
ModuleMgrUninstall(moduleMgr, NULL); ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
// scan /lib/init/ // scan /lib/init/
#ifdef SUPPORT_64BIT
moduleMgr = ModuleMgrScan("/lib64/init");
#else
moduleMgr = ModuleMgrScan("/lib/init"); moduleMgr = ModuleMgrScan("/lib/init");
#endif
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
ModuleMgrGetCnt(nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_GE(cnt, 1); ASSERT_GE(cnt, 1);
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
EXPECT_EQ(InitModuleMgrInstall(nullptr), -1);
} }
} // namespace init_ut } // namespace init_ut
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bootchart.h"
#include "bootstage.h"
#include "init_utils.h"
#include "param_stub.h"
#include "securec.h"
using namespace std;
using namespace testing::ext;
namespace init_ut {
extern "C" {
long long GetJiffies(void);
char *ReadFileToBuffer(const char *fileName, char *buffer, uint32_t bufferSize);
void BootchartLogHeader(void);
void BootchartLogFile(FILE *log, const char *procfile);
void BootchartLogProcessStat(FILE *log, pid_t pid);
void bootchartLogProcess(FILE *log);
void *BootchartThreadMain(void *data);
void BootchartDestory(void);
int DoBootchartStart(void);
int DoBootchartStop(void);
int DoBootchartCmd(int id, const char *name, int argc, const char **argv);
int BootchartInit(void);
void BootchartExit(void);
}
class ModulesUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
};
HWTEST_F(ModulesUnitTest, TestBootchartInit, TestSize.Level1)
{
EXPECT_EQ(BootchartInit(), 0);
EXPECT_NE(GetJiffies(), -1);
EXPECT_NE(DoBootchartStart(), 1);
EXPECT_EQ(DoBootchartStop(), 0);
BootchartExit();
}
HWTEST_F(ModulesUnitTest, TestReadFileToBuffer, TestSize.Level1)
{
const char *fileName = "ModulesTest";
char buffer[MAX_BUFFER_LEN] = {0};
EXPECT_EQ(ReadFileToBuffer(fileName, buffer, MAX_BUFFER_LEN), nullptr);
}
HWTEST_F(ModulesUnitTest, TestBootchartLogFile, TestSize.Level1)
{
DoBootchartStart();
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
BootchartLogFile(log, "/proc/stat");
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestBootchartLogProcessStat, TestSize.Level1)
{
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
pid_t selfPid = getpid();
BootchartLogProcessStat(log, selfPid);
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestbootchartLogProcess, TestSize.Level1)
{
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
bootchartLogProcess(log);
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestDoBootchartCmd, TestSize.Level1)
{
const char *argv1[] = { "start" };
const char *argv2[] = { "stop" };
EXPECT_NE(DoBootchartCmd(0, "bootchart", 1, argv1), 1);
EXPECT_NE(DoBootchartCmd(0, "bootchart", 1, argv2), 1);
}
HWTEST_F(ModulesUnitTest, TestDoBootchartInsall, TestSize.Level1)
{
TestSetParamCheckResult("ohos.servicectrl.", 0777, 0);
SystemWriteParam("persist.init.bootchart.enabled", "1");
SystemWriteParam("persist.init.debug.dump.trigger", "1");
SystemWriteParam("persist.init.debug.loglevel", "6");
SystemWriteParam("ohos.servicectrl.cmd", "setloglevel 10");
HookMgrExecute(GetBootStageHookMgr(), INIT_POST_PERSIST_PARAM_LOAD, NULL, NULL);
}
} // namespace init_ut
...@@ -186,7 +186,7 @@ static void PrepareUeventdcfg(void) ...@@ -186,7 +186,7 @@ static void PrepareUeventdcfg(void)
"[device]\n" "[device]\n"
"/dev/testbinder3 0666 1000 1000 const.dev.binder\n"; "/dev/testbinder3 0666 1000 1000 const.dev.binder\n";
mkdir("/data/ueventd_ut", S_IRWXU | S_IRWXG | S_IRWXO); mkdir("/data/ueventd_ut", S_IRWXU | S_IRWXG | S_IRWXO);
CreateTestFile("/data/ueventd_ut/valid.config", ueventdcfg); CreateTestFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config", ueventdcfg);
} }
static void PrepareModCfg(void) static void PrepareModCfg(void)
{ {
......
...@@ -601,5 +601,4 @@ HWTEST_F(TriggerUnitTest, TestExecuteParamTrigger6, TestSize.Level0) ...@@ -601,5 +601,4 @@ HWTEST_F(TriggerUnitTest, TestExecuteParamTrigger6, TestSize.Level0)
{ {
TriggerUnitTest test; TriggerUnitTest test;
test.TestDumpTrigger(); test.TestDumpTrigger();
CloseTriggerWorkSpace();
} }
...@@ -31,7 +31,7 @@ bool IsMatch(const char *target, const char *pattern); ...@@ -31,7 +31,7 @@ bool IsMatch(const char *target, const char *pattern);
using namespace std; using namespace std;
using namespace testing::ext; using namespace testing::ext;
namespace ueventd_ut { namespace UeventdUt {
class UeventdConfigUnitTest : public testing::Test { class UeventdConfigUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
...@@ -42,7 +42,7 @@ void TearDown() {}; ...@@ -42,7 +42,7 @@ void TearDown() {};
HWTEST_F(UeventdConfigUnitTest, TestSectionConfigParse, TestSize.Level0) HWTEST_F(UeventdConfigUnitTest, TestSectionConfigParse, TestSize.Level0)
{ {
ParseUeventdConfigFile("/data/ueventd_ut/valid.config"); ParseUeventdConfigFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config");
uid_t uid = 0; uid_t uid = 0;
gid_t gid = 0; gid_t gid = 0;
mode_t mode = 0; mode_t mode = 0;
...@@ -84,7 +84,7 @@ HWTEST_F(UeventdConfigUnitTest, TestConfigEntry, TestSize.Level0) ...@@ -84,7 +84,7 @@ HWTEST_F(UeventdConfigUnitTest, TestConfigEntry, TestSize.Level0)
HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0) HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0)
{ {
ParseUeventdConfigFile("/data/ueventd_ut/valid.config"); ParseUeventdConfigFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config");
SetUeventDeviceParameter("/dev/testbinder1", 0); SetUeventDeviceParameter("/dev/testbinder1", 0);
SetUeventDeviceParameter("/dev/testbinder2", 0); SetUeventDeviceParameter("/dev/testbinder2", 0);
SetUeventDeviceParameter("/dev/testbinder3", 0); SetUeventDeviceParameter("/dev/testbinder3", 0);
...@@ -96,4 +96,4 @@ HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0) ...@@ -96,4 +96,4 @@ HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0)
ret = IsMatch("test", "t****"); ret = IsMatch("test", "t****");
EXPECT_EQ(ret, true); EXPECT_EQ(ret, true);
} }
} // namespace ueventd_ut } // namespace UeventdUt
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cerrno>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include <gtest/gtest.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include "ueventd.h"
#include "ueventd_device_handler.h"
#include "ueventd_socket.h"
using namespace testing::ext;
namespace UeventdUt {
namespace {
std::string g_testRoot{"/data/ueventd"};
int g_oldRootFd = -1;
}
class UeventdEventUnitTest : public testing::Test {
public:
static void SetUpTestCase(void)
{
struct stat st{};
bool isExist = true;
if (stat(g_testRoot.c_str(), &st) < 0) {
if (errno != ENOENT) {
std::cout << "Cannot get stat of " << g_testRoot << std::endl;
// If we cannot get root for ueventd tests
// There is no reason to continue.
ASSERT_TRUE(false);
}
isExist = false;
}
if (isExist) {
RemoveDir(g_testRoot);
}
int ret = mkdir(g_testRoot.c_str(), S_IRWXU | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (ret < 0) {
std::cout << "Cannot create directory " << g_testRoot << " err = " << errno << std::endl;
ASSERT_TRUE(0);
}
if (SwitchRoot() < 0) {
// If we cannot do this, there is not reason to continue
ASSERT_TRUE(0);
}
}
static void TearDownTestCase(void)
{
// Switch back to old root
if (g_oldRootFd < 0) {
std::cout << "Old root directory is not valid\n";
return;
}
if (fchdir(g_oldRootFd) < 0) {
std::cout << "Failed to change working directory to '/', err = " << errno << std::endl;
}
if (chroot(".") < 0) {
std::cout << "Failed to change root directory to '/', err = " << errno << std::endl;
}
close(g_oldRootFd);
g_oldRootFd = -1;
std::cout << "Change root back done\n";
// Remove test data
if (RemoveDir(g_testRoot) < 0) {
std::cout << "Failed to remove " << g_testRoot << ", err = " << errno << std::endl;
}
}
static int RemoveDir(const std::string &path)
{
if (path.empty()) {
// Treat it as OK
return 0;
}
auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
if (dir == nullptr) {
std::cout << "Cannot open dir " << path << ", err = " << errno << std::endl;
return -1;
}
struct dirent *dp = nullptr;
while ((dp = readdir(dir.get())) != nullptr) {
// Skip hidden files
if (dp->d_name[0] == '.') {
continue;
}
bool endsWithSlash = (path.find_last_of("/") == path.size() - 1);
std::string fullPath {};
if (endsWithSlash) {
fullPath = path + dp->d_name;
} else {
fullPath = path + "/" + dp->d_name;
}
struct stat st {};
if (stat(fullPath.c_str(), &st) < 0) {
std::cout << "Failed to get stat of " << fullPath << std::endl;
continue; // Should we continue?
}
if (S_ISDIR(st.st_mode)) {
if (RemoveDir(fullPath) < 0) {
std::cout << "Failed to remove directory " << fullPath << std::endl;
return -1;
}
} else {
if (unlink(fullPath.c_str()) < 0) {
std::cout << "Failed to unlink file " << fullPath << std::endl;
return -1;
}
}
}
return rmdir(path.c_str());
}
static int SwitchRoot()
{
if (g_oldRootFd >= 0) {
close(g_oldRootFd);
g_oldRootFd = -1;
}
// Save old root
DIR *dir = opendir("/");
if (dir == nullptr) {
std::cout << "Failed to open root directory\n";
return -1;
}
g_oldRootFd = dirfd(dir);
if (g_oldRootFd < 0) {
std::cout << "Failed to pen root directory, err = " << errno << std::endl;
return -1;
}
// Changing working directory to "/data/ueventd"
if (chdir(g_testRoot.c_str()) < 0) {
std::cout << "Failed to change working directory to " << g_testRoot << ", err = " << errno << std::endl;
close(g_oldRootFd);
g_oldRootFd = -1;
}
if (chroot(g_testRoot.c_str()) < 0) {
std::cout << "Failed to change root directory to " << g_testRoot << ", err = " << errno << std::endl;
close(g_oldRootFd);
g_oldRootFd = -1;
}
std::cout << "Change root to " << g_testRoot << " done\n";
return 0;
}
void SetUp() {};
void TearDown() {};
};
// Generate uevent buffer from struct uevent.
// extra data used to break uevent buffer to check
// if ueventd will handle this situation correctly
std::string GenerateUeventBuffer(struct Uevent &uevent, std::vector<std::string> &extraData)
{
std::string ueventdBuffer{};
if (uevent.syspath != nullptr) {
ueventdBuffer.append(std::string("DEVPATH=") + uevent.syspath + '\000');
}
if (uevent.subsystem != nullptr) {
ueventdBuffer.append(std::string("SUBSYSTEM=") + uevent.subsystem + '\000');
}
ueventdBuffer.append(std::string("ACTION=") + ActionString(uevent.action) + '\000');
if (uevent.deviceName != nullptr) {
ueventdBuffer.append(std::string("DEVNAME=") + uevent.deviceName + '\000');
}
if (uevent.partitionName != nullptr) {
ueventdBuffer.append(std::string("PARTNAME=") + uevent.partitionName + '\000');
}
ueventdBuffer.append(std::string("PARTN=") + std::to_string(uevent.partitionNum) + '\000');
ueventdBuffer.append(std::string("MAJOR=") + std::to_string(uevent.major) + '\000');
ueventdBuffer.append(std::string("MINOR=") + std::to_string(uevent.minor) + '\000');
ueventdBuffer.append(std::string("DEVUID=") + std::to_string(uevent.ug.uid) + '\000');
ueventdBuffer.append(std::string("DEVGID=") + std::to_string(uevent.ug.gid) + '\000');
if (uevent.firmware != nullptr) {
ueventdBuffer.append(std::string("FIRMWARE=") + uevent.firmware + '\000');
}
ueventdBuffer.append(std::string("BUSNUM=") + std::to_string(uevent.busNum) + '\000');
ueventdBuffer.append(std::string("DEVNUM=") + std::to_string(uevent.devNum) + '\000');
if (!extraData.empty()) {
for (const auto &data : extraData) {
ueventdBuffer.append(data);
}
}
return ueventdBuffer;
}
bool IsFileExist(const std::string &file)
{
struct stat st{};
if (file.empty()) {
return false;
}
if (stat(file.c_str(), &st) < 0) {
if (errno == ENOENT) {
std::cout << "File " << file << " is not exist\n";
}
return false;
}
return true;
}
HWTEST_F(UeventdEventUnitTest, TestParseUeventdEvent, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/test",
.deviceName = "test",
.partitionName = "userdata",
.firmware = "",
.action = ACTION_ADD,
.partitionNum = 3,
.major = 1,
.minor = 2,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
std::vector<std::string> extraData{};
auto ueventBuffer = GenerateUeventBuffer(uevent, extraData);
std::cout << "ueventBuffer = [" << ueventBuffer << "]. size = " << ueventBuffer.length() << std::endl;
struct Uevent outEvent;
ParseUeventMessage(ueventBuffer.data(), ueventBuffer.length(), &outEvent);
EXPECT_EQ(outEvent.action, ACTION_ADD);
EXPECT_EQ(outEvent.busNum, 1);
EXPECT_STREQ(outEvent.subsystem, "block");
EXPECT_STREQ(outEvent.deviceName, "test");
EXPECT_EQ(outEvent.devNum, 2);
EXPECT_EQ(outEvent.major, 1);
EXPECT_EQ(outEvent.minor, 2);
EXPECT_EQ(outEvent.partitionNum, 3);
EXPECT_STREQ(outEvent.partitionName, "userdata");
EXPECT_STREQ(outEvent.syspath, "/block/mmc/test");
EXPECT_EQ(outEvent.ug.gid, 0);
EXPECT_EQ(outEvent.ug.uid, 0);
}
HWTEST_F(UeventdEventUnitTest, TestUeventActions, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/test",
.deviceName = "test",
.partitionName = "userdata",
.action = ACTION_UNKNOWN,
};
std::vector<std::string> extraData {};
auto ueventBuffer = GenerateUeventBuffer(uevent, extraData);
std::cout << "ueventBuffer = [" << ueventBuffer << "]. size = " << ueventBuffer.length() << std::endl;
struct Uevent outEvent;
ParseUeventMessage(ueventBuffer.data(), ueventBuffer.length(), &outEvent);
EXPECT_EQ(outEvent.action, ACTION_UNKNOWN);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesInvalidParameters, TestSize.Level1)
{
HandleBlockDeviceEvent(nullptr);
// Not block device
struct Uevent noBlockUevent = {
.subsystem = "char",
};
HandleBlockDeviceEvent(&noBlockUevent);
struct Uevent invalidDevNoUevent = {
.subsystem = "block",
.major = -1,
.minor = -1,
};
HandleBlockDeviceEvent(&invalidDevNoUevent);
struct Uevent invalidSysPathUevent = {
.subsystem = "block",
.syspath = nullptr,
.major = 1,
.minor = 1,
};
HandleBlockDeviceEvent(&invalidSysPathUevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesValidParameters, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_ADD,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
HandleBlockDeviceEvent(&uevent);
// Check results
std::string blockDevice = "/dev/block/block_device_test";
struct stat st{};
int ret = stat(blockDevice.c_str(), &st);
EXPECT_EQ(ret, 0);
bool isBlock = S_ISBLK(st.st_mode);
EXPECT_TRUE(isBlock);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesRemoved, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_REMOVE,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
std::string blockDevice = "/dev/block/block_device_test";
struct stat st{};
int ret = stat(blockDevice.c_str(), &st);
if (ret < 0) {
// This should not happen actually, because we've created the device node before.
std::cout << "Warning. Block device " << blockDevice << " is not exist.\n";
}
HandleBlockDeviceEvent(&uevent);
ret = stat(blockDevice.c_str(), &st);
EXPECT_EQ(ret, -1);
EXPECT_EQ(errno, ENOENT);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesChanged, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_REMOVE,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
HandleBlockDeviceEvent(&uevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleOtherDevicesInvalidParameters, TestSize.Level1)
{
HandleOtherDeviceEvent(nullptr);
// Not Character device
struct Uevent invalidDevNoUevent = {
.subsystem = "test",
.major = -1,
.minor = -1,
};
HandleOtherDeviceEvent(&invalidDevNoUevent);
struct Uevent invalidSysPathUevent = {
.subsystem = "test",
.syspath = nullptr,
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&invalidSysPathUevent);
struct Uevent invalidSubsystemUevent = {
.subsystem = "",
.syspath = "/devices/test/char",
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&invalidSubsystemUevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleOtherDevicesValidParameters, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "extcon3",
.syspath = "/devices/platform/headset/extcon/extcon3",
.deviceName = "extcon3-1",
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/extcon3-1");
EXPECT_TRUE(exist);
exist = IsFileExist("/dev/extcon3");
EXPECT_FALSE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleUsbDevicesWithDeviceName, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev",
.deviceName = "usb-dev",
.major = 8,
.minor = 9,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/usb-dev");
EXPECT_TRUE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleInvalidUsbDevices, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev-1",
.major = 8,
.minor = 10,
.busNum = -1,
.devNum = -1,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/usb-dev-1");
EXPECT_FALSE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleUsbDevicesWithBusNo, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev",
.major = 8,
.minor = 9,
.busNum = 3,
.devNum = 4,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/bus/usb/003/004");
EXPECT_TRUE(exist);
}
} // UeventdUt
\ No newline at end of file
...@@ -16,6 +16,11 @@ ...@@ -16,6 +16,11 @@
#ifndef BASE_STARTUP_INITLITE_UEVENTD_H #ifndef BASE_STARTUP_INITLITE_UEVENTD_H
#define BASE_STARTUP_INITLITE_UEVENTD_H #define BASE_STARTUP_INITLITE_UEVENTD_H
#include <unistd.h> #include <unistd.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
// Refer to linux kernel kobject.h // Refer to linux kernel kobject.h
typedef enum ACTION { typedef enum ACTION {
...@@ -71,4 +76,9 @@ void ParseUeventMessage(const char *buffer, ssize_t length, struct Uevent *ueven ...@@ -71,4 +76,9 @@ void ParseUeventMessage(const char *buffer, ssize_t length, struct Uevent *ueven
void RetriggerUevent(int sockFd, char **devices, int num); void RetriggerUevent(int sockFd, char **devices, int num);
void ProcessUevent(int sockFd, char **devices, int num); void ProcessUevent(int sockFd, char **devices, int num);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // BASE_STARTUP_INITLITE_UEVENTD_H #endif // BASE_STARTUP_INITLITE_UEVENTD_H
...@@ -16,7 +16,18 @@ ...@@ -16,7 +16,18 @@
#ifndef BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H #ifndef BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H
#define BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H #define BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H
#include "ueventd.h" #include "ueventd.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
void HandleBlockDeviceEvent(const struct Uevent *uevent); void HandleBlockDeviceEvent(const struct Uevent *uevent);
void HandleOtherDeviceEvent(const struct Uevent *uevent); void HandleOtherDeviceEvent(const struct Uevent *uevent);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H #endif // BASE_STARTUP_INITLITE_UEVENTD_DEVICE_HANDLER_H
...@@ -16,6 +16,18 @@ ...@@ -16,6 +16,18 @@
#ifndef BASE_STARTUP_INITLITE_UEVENTD_SOCKET_H #ifndef BASE_STARTUP_INITLITE_UEVENTD_SOCKET_H
#define BASE_STARTUP_INITLITE_UEVENTD_SOCKET_H #define BASE_STARTUP_INITLITE_UEVENTD_SOCKET_H
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
int UeventdSocketInit(void); int UeventdSocketInit(void);
ssize_t ReadUeventMessage(int sockFd, char *buffer, size_t length); ssize_t ReadUeventMessage(int sockFd, char *buffer, size_t length);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // BASE_STARTUP_INITLITE_LIST_H #endif // BASE_STARTUP_INITLITE_LIST_H
...@@ -243,7 +243,7 @@ void ParseUeventMessage(const char *buffer, ssize_t length, struct Uevent *ueven ...@@ -243,7 +243,7 @@ void ParseUeventMessage(const char *buffer, ssize_t length, struct Uevent *ueven
return; return;
} }
// reset partititon number, major and minor. // reset partition number, major and minor.
uevent->partitionNum = -1; uevent->partitionNum = -1;
uevent->major = -1; uevent->major = -1;
uevent->minor = -1; uevent->minor = -1;
......
...@@ -428,7 +428,7 @@ void HandleBlockDeviceEvent(const struct Uevent *uevent) ...@@ -428,7 +428,7 @@ void HandleBlockDeviceEvent(const struct Uevent *uevent)
} }
if (strcmp(uevent->subsystem, "block") != 0) { if (strcmp(uevent->subsystem, "block") != 0) {
INIT_LOGE("Unexpceted uevent subsystem \" %s \" received in block device handler", uevent->subsystem); INIT_LOGE("Unexpected uevent subsystem \" %s \" received in block device handler", uevent->subsystem);
return; return;
} }
...@@ -475,7 +475,8 @@ void HandleOtherDeviceEvent(const struct Uevent *uevent) ...@@ -475,7 +475,8 @@ void HandleOtherDeviceEvent(const struct Uevent *uevent)
char deviceNode[DEVICE_FILE_SIZE] = {}; char deviceNode[DEVICE_FILE_SIZE] = {};
char sysPath[SYSPATH_SIZE] = {}; char sysPath[SYSPATH_SIZE] = {};
if (strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath) != EOK)) { if ((uevent->syspath == NULL) ||
strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath)) != EOK) {
INIT_LOGE("Failed to copy sys path"); INIT_LOGE("Failed to copy sys path");
return; return;
} }
......
...@@ -50,8 +50,10 @@ int UeventdSocketInit(void) ...@@ -50,8 +50,10 @@ int UeventdSocketInit(void)
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
INIT_LOGE("Bind socket failed, err = %d", errno); INIT_LOGE("Bind socket failed, err = %d", errno);
#ifndef STARTUP_INIT_TEST
close(sockfd); close(sockfd);
return -1; return -1;
#endif
} }
return sockfd; return sockfd;
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册