From 81c9f8257c710db4f3dbf162b6d83593a4428ccb Mon Sep 17 00:00:00 2001 From: Kyungwook Tak Date: Fri, 29 Apr 2016 10:45:04 +0900 Subject: [PATCH] Add custom exception derived from std::exception Change-Id: I9cd2b806e8fd842c18f85480d173ff80d0c8280e Signed-off-by: Kyungwook Tak --- src/framework/CMakeLists.txt | 1 + src/framework/client/handle-ext.cpp | 9 +- src/framework/client/handle.cpp | 5 +- src/framework/client/utils.cpp | 4 + src/framework/common/binary-queue.cpp | 10 +- src/framework/common/cs-context.cpp | 33 ++-- src/framework/common/exception.cpp | 44 ++++++ src/framework/common/exception.h | 89 +++++++++++ src/framework/common/kvp-container.cpp | 23 ++- src/framework/common/mainloop.cpp | 23 ++- src/framework/common/service.cpp | 13 +- src/framework/common/socket.cpp | 44 ++---- src/framework/common/wp-context.cpp | 29 ++-- src/framework/common/wp-result.cpp | 4 - src/framework/db/connection.cpp | 6 +- src/framework/db/manager.cpp | 261 +++++++++++-------------------- src/framework/db/manager.h | 31 ++-- src/framework/db/statement.cpp | 48 +++--- src/framework/service/app-deleter.cpp | 4 +- src/framework/service/core-usage.cpp | 9 +- src/framework/service/cs-loader.cpp | 60 ++++--- src/framework/service/file-system.cpp | 5 +- src/framework/service/logic.cpp | 46 +++--- src/framework/service/thread-pool.cpp | 4 +- src/framework/service/type-converter.cpp | 9 +- src/framework/service/wp-loader.cpp | 48 +++--- src/framework/ui/popup/logic.cpp | 8 +- src/include/csr/error.h | 1 + test/test-common.cpp | 4 +- test/test-internal-database.cpp | 30 ++-- 30 files changed, 466 insertions(+), 439 deletions(-) create mode 100644 src/framework/common/exception.cpp create mode 100644 src/framework/common/exception.h diff --git a/src/framework/CMakeLists.txt b/src/framework/CMakeLists.txt index e2c3766..0b8f44b 100644 --- a/src/framework/CMakeLists.txt +++ b/src/framework/CMakeLists.txt @@ -30,6 +30,7 @@ SET(${TARGET_CSR_COMMON}_SRCS common/connection.cpp common/cs-context.cpp common/cs-detected.cpp + common/exception.cpp common/wp-context.cpp common/wp-result.cpp common/kvp-container.cpp diff --git a/src/framework/client/handle-ext.cpp b/src/framework/client/handle-ext.cpp index 7852520..9b02ebe 100644 --- a/src/framework/client/handle-ext.cpp +++ b/src/framework/client/handle-ext.cpp @@ -26,6 +26,7 @@ #include "client/utils.h" #include "common/dispatcher.h" #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { namespace Client { @@ -65,8 +66,8 @@ void HandleExt::eraseJoinableIf(std::function pred) DEBUG("Worker map traversing to erase! current iter tid: " << it->first); if (!it->second.t.joinable()) - throw std::logic_error(FORMAT("All workers should be joinable " - "but it isn't. tid: " << it->first)); + ThrowExc(InternalError, "All workers should be joinable but it isn't. " + "tid: " << it->first); if (!pred(*it)) { ++it; @@ -88,8 +89,8 @@ void HandleExt::done() auto it = m_workerMap.find(std::this_thread::get_id()); if (it == m_workerMap.end()) - throw std::logic_error(FORMAT("worker done but it's not registered in map. " - "tid: " << std::this_thread::get_id())); + ThrowExc(InternalError, "worker done but it's not registered in map. " + "tid: " << std::this_thread::get_id()); it->second.isDone = true; } diff --git a/src/framework/client/handle.cpp b/src/framework/client/handle.cpp index 52d11e6..1449e4c 100644 --- a/src/framework/client/handle.cpp +++ b/src/framework/client/handle.cpp @@ -21,9 +21,10 @@ */ #include "client/handle.h" -#include #include +#include "common/exception.h" + namespace Csr { namespace Client { @@ -31,7 +32,7 @@ Handle::Handle(ContextShPtr &&context) : m_ctx(std::forward(context)) { if (!m_ctx) - throw std::logic_error("context shouldn't be null"); + ThrowExc(InvalidParam, "context shouldn't be null"); } Handle::~Handle() diff --git a/src/framework/client/utils.cpp b/src/framework/client/utils.cpp index 3c3e11e..7b79d69 100644 --- a/src/framework/client/utils.cpp +++ b/src/framework/client/utils.cpp @@ -24,6 +24,7 @@ #include #include "common/audit/logger.h" +#include "common/exception.h" #include "csr/error.h" __attribute__((constructor)) @@ -39,6 +40,9 @@ int exceptionGuard(const std::function &func) { try { return func(); + } catch (const Exception &e) { + ERROR("Exception caught. code: " << e.error() << " message: " << e.what()); + return e.error(); } catch (const std::bad_alloc &e) { ERROR("memory allocation failed."); return CSR_ERROR_OUT_OF_MEMORY; diff --git a/src/framework/common/binary-queue.cpp b/src/framework/common/binary-queue.cpp index 319d138..d4b30f8 100644 --- a/src/framework/common/binary-queue.cpp +++ b/src/framework/common/binary-queue.cpp @@ -26,6 +26,8 @@ #include #include +#include "common/exception.h" + namespace Csr { BinaryQueue::BinaryQueue() : m_size(0) @@ -68,13 +70,13 @@ void BinaryQueue::read(size_t size, void *bytes) return; if (size > m_size) - throw std::logic_error("protocol broken. no more binary to flatten in queue"); + ThrowExc(SocketError, "protocol broken. no more binary to flatten in queue"); void *cur = bytes; while (size > 0) { if (m_buckets.empty()) - throw std::logic_error("protocol broken. no more buckets to extract"); + ThrowExc(SocketError, "protocol broken. no more buckets to extract"); size_t count = std::min(size, m_buckets.front()->left); cur = m_buckets.front()->extractTo(cur, count); @@ -93,7 +95,7 @@ BinaryQueue::Bucket::Bucket(unsigned char *_data, size_t _size) : left(_size) { if (_data == nullptr || _size == 0) - throw std::invalid_argument("Bucket construct failed."); + ThrowExc(InternalError, "Bucket construct failed."); } BinaryQueue::Bucket::~Bucket() @@ -104,7 +106,7 @@ BinaryQueue::Bucket::~Bucket() void *BinaryQueue::Bucket::extractTo(void *dest, size_t size) { if (dest == nullptr || size == 0) - throw std::logic_error("logic error. invalid input to Bucket::extractTo."); + ThrowExc(InternalError, "logic error. invalid input to Bucket::extractTo."); memcpy(dest, cur, size); diff --git a/src/framework/common/cs-context.cpp b/src/framework/common/cs-context.cpp index 64c57af..a132709 100644 --- a/src/framework/common/cs-context.cpp +++ b/src/framework/common/cs-context.cpp @@ -21,9 +21,8 @@ */ #include "common/cs-context.h" -#include - #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -70,8 +69,7 @@ void CsContext::set(int key, int value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as int.")); + ThrowExc(InternalError, "Invalid key[" << key << "] comes in to set as int."); } } @@ -83,8 +81,8 @@ void CsContext::set(int key, const std::string &value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as string.")); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as string."); } } @@ -96,8 +94,8 @@ void CsContext::set(int key, const char *value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as string.")); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as string."); } } @@ -109,8 +107,7 @@ void CsContext::set(int key, bool value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as bool.")); + ThrowExc(InternalError, "Invalid key[" << key << "] comes in to set as bool."); } } @@ -126,8 +123,7 @@ void CsContext::get(int key, int &value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to get as int.")); + ThrowExc(InternalError, "Invalid key[" << key << "] comes in to get as int."); } } @@ -139,15 +135,15 @@ void CsContext::get(int key, std::string &value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to get as string.")); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to get as string."); } } void CsContext::get(int key, const char **value) const { if (value == nullptr) - throw std::logic_error("invalud argument. output storage pointer is null."); + ThrowExc(InvalidParam, "output storage pointer is null."); switch (static_cast(key)) { case Key::PopupMessage: @@ -155,8 +151,8 @@ void CsContext::get(int key, const char **value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to get as string.")); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to get as string."); } } @@ -168,8 +164,7 @@ void CsContext::get(int key, bool &value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to get as bool.")); + ThrowExc(InternalError, "Invalid key[" << key << "] comes in to get as bool."); } } diff --git a/src/framework/common/exception.cpp b/src/framework/common/exception.cpp new file mode 100644 index 0000000..2f1e24d --- /dev/null +++ b/src/framework/common/exception.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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 + */ +/* + * @file exception.h + * @author Kyungwook Tak (k.tak@samsung.com) + * @version 1.0 + * @brief custom exception derived from std + */ +#include "common/exception.h" + +#include "common/audit/logger.h" + +namespace Csr { + +Exception::Exception(const char *file, const char *function, unsigned int line, + const std::string &message) : + m_message(FORMAT("[" << file << ":" << line << " " << function << "()]" << + message)) +{ +} + +Exception::~Exception() noexcept +{ +} + +const char *Exception::what() const noexcept +{ + return m_message.c_str(); +} + +} diff --git a/src/framework/common/exception.h b/src/framework/common/exception.h new file mode 100644 index 0000000..83e7d42 --- /dev/null +++ b/src/framework/common/exception.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved + * + * 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 + */ +/* + * @file exception.h + * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) + * Kyungwook Tak (k.tak@samsung.com) + * @version 1.0 + * @brief custom exception derived from std + */ +#pragma once + +#include +#include + +#include "common/audit/logger.h" +#include "csr/error.h" + +namespace Csr { + +class Exception : public std::exception { +public: + Exception(const char *file, const char *function, unsigned int line, + const std::string &message); + virtual ~Exception() noexcept; + virtual const char *what() const noexcept override; + + virtual int error(void) const = 0; + +protected: + std::string m_message; +}; + +template +class DerivedException : public Exception { +public: + DerivedException(const char *file, const char *function, unsigned int line, + const std::string &message) : + Exception(file, function, line, message) + { + switch (level) { + case Audit::LogLevel::Error: + ERROR(message); + break; + + case Audit::LogLevel::Warning: + WARN(message); + break; + + case Audit::LogLevel::Info: + INFO(message); + break; + + default: + DEBUG(message); + break; + } + } + + virtual ~DerivedException() noexcept {} + + virtual int error(void) const + { + return Error; + } +}; + +using DbFailed = DerivedException; +using InvalidParam = DerivedException; +using InternalError = DerivedException; +using EngineError = DerivedException; +using SocketError = DerivedException; + +} // namespace Csr + +#define ThrowExc(name, MESSAGE) \ + throw name(__FILE__, __FUNCTION__, __LINE__, FORMAT(MESSAGE)) diff --git a/src/framework/common/kvp-container.cpp b/src/framework/common/kvp-container.cpp index f93a3cf..8bc7bfc 100644 --- a/src/framework/common/kvp-container.cpp +++ b/src/framework/common/kvp-container.cpp @@ -21,7 +21,7 @@ */ #include "common/kvp-container.h" -#include +#include "common/exception.h" namespace Csr { @@ -31,53 +31,52 @@ KvpContainer::~KvpContainer() void KvpContainer::set(int, int) { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::set(int, bool) { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::set(int, const std::string &) { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::set(int, const char *) { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::set(int, time_t) { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::get(int, int &) const { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::get(int, bool &) const { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::get(int, std::string &) const { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::get(int, const char **) const { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } void KvpContainer::get(int, time_t &) const { - throw std::logic_error("Not implemented key-value pair interface used!"); + ThrowExc(InternalError, "Not implemented key-value pair interface used!"); } - } diff --git a/src/framework/common/mainloop.cpp b/src/framework/common/mainloop.cpp index a186150..03acaa0 100644 --- a/src/framework/common/mainloop.cpp +++ b/src/framework/common/mainloop.cpp @@ -21,13 +21,12 @@ */ #include "common/mainloop.h" -#include -#include #include #include #include #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -44,8 +43,8 @@ Mainloop::Mainloop() : Mainloop::~Mainloop() { if (!m_isTimedOut && !m_callbacks.empty()) - throw std::logic_error("mainloop registered callbacks should be empty " - "except timed out case"); + ThrowExc(InternalError, "mainloop registered callbacks should be empty " + "except timed out case"); ::close(m_pollfd); } @@ -65,8 +64,7 @@ void Mainloop::addEventSource(int fd, uint32_t event, Callback &&callback) { /* TODO: use scoped-lock to thread safe on member variables */ if (m_callbacks.count(fd) != 0) - throw std::logic_error(FORMAT("event source on fd[" << fd << - "] already added!")); + ThrowExc(InternalError, "event source on fd[" << fd << "] already added!"); DEBUG("Add event[" << event << "] source on fd[" << fd << "]"); @@ -87,23 +85,22 @@ void Mainloop::removeEventSource(int fd) { /* TODO: use scoped-lock to thread safe on member variables */ if (m_callbacks.count(fd) == 0) - throw std::logic_error(FORMAT("event source on fd[" << fd << - "] isn't added at all")); + ThrowExc(InternalError, "event source on fd[" << fd << "] isn't added at all"); DEBUG("Remove event source on fd[" << fd << "]"); - do { + { m_callbacks.erase(fd); if (::epoll_ctl(m_pollfd, EPOLL_CTL_DEL, fd, nullptr) == -1) { if (errno == ENOENT) - throw std::logic_error("Tried to delete epoll item which wasn't added"); + ThrowExc(InternalError, "Tried to delete epoll item which wasn't added"); else throw std::system_error( std::error_code(errno, std::generic_category()), "epoll_ctl failed to EPOLL_CTL_DEL."); } - } while (false); + } } void Mainloop::dispatch(int timeout) @@ -133,8 +130,8 @@ void Mainloop::dispatch(int timeout) int fd = event[i].data.fd; if (m_callbacks.count(fd) == 0) - throw std::logic_error(FORMAT( - "event in on fd[" << fd << "] but associated callback isn't exist!")); + ThrowExc(InternalError, "event in on fd[" << fd << + "] but associated callback isn't exist!"); if (event[i].events & (EPOLLHUP | EPOLLRDHUP)) { INFO("peer connection closed on fd[" << fd << "]"); diff --git a/src/framework/common/service.cpp b/src/framework/common/service.cpp index aed7889..d359487 100644 --- a/src/framework/common/service.cpp +++ b/src/framework/common/service.cpp @@ -25,6 +25,7 @@ #include #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -70,7 +71,7 @@ void Service::setNewConnectionCallback(const ConnCallback &/*callback*/) /* TODO: scoped-lock */ m_onNewConnection = [&](const ConnShPtr & connection) { if (!connection) - throw std::logic_error("onNewConnection called but ConnShPtr is nullptr."); + ThrowExc(InternalError, "onNewConnection called but ConnShPtr is nullptr."); int fd = connection->getFd(); @@ -87,8 +88,8 @@ void Service::setNewConnectionCallback(const ConnCallback &/*callback*/) DEBUG("read event comes in to fd[" << fd << "]"); if (m_connectionRegistry.count(fd) == 0) - throw std::logic_error(FORMAT("get event on fd[" << fd - << "] but no associated connection exist")); + ThrowExc(InternalError, "get event on fd[" << fd << + "] but no associated connection exist"); auto &conn = m_connectionRegistry[fd]; @@ -112,13 +113,13 @@ void Service::setCloseConnectionCallback(const ConnCallback &/*callback*/) /* TODO: scoped-lock */ m_onCloseConnection = [&](const ConnShPtr & connection) { if (!connection) - throw std::logic_error("no connection to close"); + ThrowExc(InternalError, "no connection to close"); int fd = connection->getFd(); if (m_connectionRegistry.count(fd) == 0) - throw std::logic_error(FORMAT("no connection in registry to remove " - "associated to fd[" << fd << "]")); + ThrowExc(InternalError, "no connection in registry to remove " + "associated to fd[" << fd << "]"); INFO("good-bye! close socket fd[" << fd << "]"); diff --git a/src/framework/common/socket.cpp b/src/framework/common/socket.cpp index 38460a1..3ac49c5 100644 --- a/src/framework/common/socket.cpp +++ b/src/framework/common/socket.cpp @@ -21,9 +21,6 @@ */ #include "common/socket.h" -#include -#include - #include #include #include @@ -32,6 +29,9 @@ #include #include "common/audit/logger.h" +#include "common/exception.h" + +namespace Csr { namespace { @@ -40,7 +40,7 @@ int createSystemdSocket(const std::string &path) int n = ::sd_listen_fds(-1); if (n < 0) - throw std::system_error(std::error_code(), "failed to sd_listen_fds"); + ThrowExc(SocketError, "failed to sd_listen_fds"); for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) { if (::sd_is_socket_unix(fd, SOCK_STREAM, 1, path.c_str(), 0) > 0) { @@ -49,17 +49,15 @@ int createSystemdSocket(const std::string &path) } } - throw std::system_error(std::error_code(), "get systemd socket failed!"); -} - + ThrowExc(SocketError, "get systemd socket failed!"); } -namespace Csr { +} // namespace anonymous Socket::Socket(int fd) : m_fd(fd) { if (m_fd < 0) - throw std::logic_error("Socket fd from constructor is invalid!!"); + ThrowExc(SocketError, "Socket fd from constructor is invalid!!"); } Socket::Socket(const std::string &path) : m_fd(createSystemdSocket(path)) @@ -68,9 +66,6 @@ Socket::Socket(const std::string &path) : m_fd(createSystemdSocket(path)) Socket::Socket(Socket &&other) { - if (other.m_fd < 0) - throw std::logic_error("Socket fd from move constructor is invalid!!"); - m_fd = other.m_fd; other.m_fd = 0; } @@ -80,9 +75,6 @@ Socket &Socket::operator=(Socket &&other) if (this == &other) return *this; - if (other.m_fd < 0) - throw std::logic_error("Socket fd from move assignment is invalid!!"); - m_fd = other.m_fd; other.m_fd = 0; @@ -103,9 +95,7 @@ Socket Socket::accept() const int fd = ::accept(m_fd, nullptr, nullptr); if (fd < 0) - throw std::system_error( - std::error_code(errno, std::generic_category()), - "socket accept failed!"); + ThrowExc(SocketError, "socket accept failed with errno: " << errno); INFO("Accept client success with fd: " << fd); @@ -115,14 +105,12 @@ Socket Socket::accept() const Socket Socket::connect(const std::string &path) { if (path.size() >= sizeof(sockaddr_un::sun_path)) - throw std::invalid_argument("socket path size too long!"); + ThrowExc(InternalError, "socket path size too long!"); int fd = ::socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) - throw std::system_error( - std::error_code(errno, std::generic_category()), - "socket create failed!"); + ThrowExc(SocketError, "Socket create failed with errno: " << errno); sockaddr_un addr; addr.sun_family = AF_UNIX; @@ -131,9 +119,7 @@ Socket Socket::connect(const std::string &path) if (::connect(fd, reinterpret_cast(&addr), sizeof(sockaddr_un)) == -1) - throw std::system_error( - std::error_code(errno, std::generic_category()), - "socket connect failed!"); + ThrowExc(SocketError, "Socket connect failed with errno: " << errno); INFO("Connect to CSR server success with fd:" << fd); @@ -162,9 +148,7 @@ RawBuffer Socket::read(void) const if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; else - throw std::system_error( - std::error_code(errno, std::generic_category()), - "socket read failed!"); + ThrowExc(SocketError, "Socket read failed with errno: " << errno); } /* TODO: handle the case of more bytes in stream to read than buffer size */ @@ -196,9 +180,7 @@ void Socket::write(const RawBuffer &data) const if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; else - throw std::system_error( - std::error_code(errno, std::generic_category()), - "socket write failed!"); + ThrowExc(SocketError, "Socket write failed with errno: " << errno); } total += bytes; diff --git a/src/framework/common/wp-context.cpp b/src/framework/common/wp-context.cpp index d759248..3a53fd0 100644 --- a/src/framework/common/wp-context.cpp +++ b/src/framework/common/wp-context.cpp @@ -21,9 +21,8 @@ */ #include "common/wp-context.h" -#include - #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -60,8 +59,8 @@ void WpContext::set(int key, int value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as int. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as int. value=" << value); } } @@ -73,8 +72,8 @@ void WpContext::set(int key, const std::string &value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as std::string. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as std::string. value=" << value); } } @@ -86,8 +85,8 @@ void WpContext::set(int key, const char *value) break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as char*. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as char*. value=" << value); } } @@ -99,8 +98,8 @@ void WpContext::get(int key, int &value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as int. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as int. value=" << value); } } @@ -112,15 +111,15 @@ void WpContext::get(int key, std::string &value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as std::string. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as std::string. value=" << value); } } void WpContext::get(int key, const char **value) const { if (value == nullptr) - throw std::logic_error("invalud argument. output storage pointer is null."); + ThrowExc(InvalidParam, "output storage pointer is null."); switch (static_cast(key)) { case Key::PopupMessage: @@ -128,8 +127,8 @@ void WpContext::get(int key, const char **value) const break; default: - throw std::logic_error(FORMAT("Invalid key[" << key << - "] comes in to set as char*. value=" << value)); + ThrowExc(InternalError, "Invalid key[" << key << + "] comes in to set as char*. value=" << value); } } diff --git a/src/framework/common/wp-result.cpp b/src/framework/common/wp-result.cpp index fd2bcbc..4bb39a6 100644 --- a/src/framework/common/wp-result.cpp +++ b/src/framework/common/wp-result.cpp @@ -21,10 +21,6 @@ */ #include "common/wp-result.h" -#include - -#include "common/audit/logger.h" - namespace Csr { WpResult::WpResult() : diff --git a/src/framework/db/connection.cpp b/src/framework/db/connection.cpp index da0a0f9..2ebcbd7 100644 --- a/src/framework/db/connection.cpp +++ b/src/framework/db/connection.cpp @@ -14,9 +14,9 @@ * limitations under the License */ #include -#include #include "db/connection.h" +#include "common/exception.h" namespace Csr { namespace Db { @@ -26,7 +26,7 @@ Connection::Connection(const std::string &name, const int flags) : m_filename(name) { if (::sqlite3_open_v2(m_filename.c_str(), &m_handle, flags, nullptr)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, "db connection ctor failed: " << getErrorMessage()); } Connection::~Connection() @@ -38,7 +38,7 @@ int Connection::exec(const std::string &query) { if (::sqlite3_exec(m_handle, query.c_str(), nullptr, nullptr, nullptr) != SQLITE_OK) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, "db connection exec failed: " << getErrorMessage()); return sqlite3_changes(m_handle); } diff --git a/src/framework/db/manager.cpp b/src/framework/db/manager.cpp index 548950a..535014e 100644 --- a/src/framework/db/manager.cpp +++ b/src/framework/db/manager.cpp @@ -23,11 +23,11 @@ #include #include -#include #include "db/query.h" #include "db/statement.h" #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { namespace Db { @@ -104,13 +104,13 @@ std::string Manager::getScript(const std::string &scriptName) std::ifstream is(scriptPath); if (is.fail()) - throw std::runtime_error(FORMAT("Cannot open script: " << scriptPath)); + ThrowExc(DbFailed, "Cannot open script: " << scriptPath); std::istreambuf_iterator begin(is), end; auto str = std::string(begin, end); if (str.empty()) - throw std::runtime_error(FORMAT("Script file empty: " << scriptPath)); + ThrowExc(DbFailed, "Script file empty: " << scriptPath); return str; } @@ -128,7 +128,7 @@ int Manager::getSchemaVersion() { if (!isTableExist(SCHEMA_INFO_TABLE)) { WARN("Schema table doesn't exist. This case would be the first time of " - "db manager instantiated in target"); + "db manager instantiated in target"); return SchemaVersion::NOT_EXIST; } @@ -137,7 +137,7 @@ int Manager::getSchemaVersion() stmt.bind(DB_VERSION_STR); if (!stmt.step()) - throw std::logic_error(FORMAT("schema info table should exist!")); + ThrowExc(DbFailed, "schema info table should exist!"); return stmt.getInt(); } @@ -150,150 +150,85 @@ void Manager::setSchemaVersion(int sv) stmt.bind(sv); if (stmt.exec() == 0) - throw std::runtime_error(FORMAT("Failed to set schema version!")); + ThrowExc(DbFailed, "Failed to set schema version to: " << sv); } //=========================================================================== // ENGINE_STATE table //=========================================================================== -int Manager::getEngineState(int engineId) noexcept +int Manager::getEngineState(int engineId) { - try { - Statement stmt(m_conn, Query::SEL_ENGINE_STATE); + Statement stmt(m_conn, Query::SEL_ENGINE_STATE); - stmt.bind(engineId); + stmt.bind(engineId); - return stmt.step() ? stmt.getInt() : -1; - } catch (const std::exception &e) { - ERROR("getEngineState failed. error_msg=" << e.what()); - return -1; - } + return stmt.step() ? stmt.getInt() : -1; } -bool Manager::setEngineState(int engineId, int state) noexcept +void Manager::setEngineState(int engineId, int state) { - try { - Statement stmt(m_conn, Query::INS_ENGINE_STATE); + Statement stmt(m_conn, Query::INS_ENGINE_STATE); - stmt.bind(engineId); - stmt.bind(state); + stmt.bind(engineId); + stmt.bind(state); - return stmt.exec() != 0; - } catch (const std::exception &e) { - ERROR("setEngineState failed. error_msg=" << e.what()); - return false; - } + stmt.exec(); } //=========================================================================== // SCAN_REQUEST table //=========================================================================== -long Manager::getLastScanTime(const std::string &dir, - const std::string &dataVersion) noexcept +time_t Manager::getLastScanTime(const std::string &dir, + const std::string &dataVersion) { - try { - Statement stmt(m_conn, Query::SEL_SCAN_REQUEST); + Statement stmt(m_conn, Query::SEL_SCAN_REQUEST); - stmt.bind(dir); - stmt.bind(dataVersion); + stmt.bind(dir); + stmt.bind(dataVersion); - return stmt.step() ? static_cast(stmt.getInt64()) : -1; - } catch (const std::exception &e) { - ERROR("getLastScanTime failed. error_msg=" << e.what()); - return -1; - } + return stmt.step() ? static_cast(stmt.getInt64()) : -1; } -bool Manager::insertLastScanTime(const std::string &dir, long scanTime, - const std::string &dataVersion) noexcept +void Manager::insertLastScanTime(const std::string &dir, long scanTime, + const std::string &dataVersion) { - try { - Statement stmt(m_conn, Query::INS_SCAN_REQUEST); + Statement stmt(m_conn, Query::INS_SCAN_REQUEST); - stmt.bind(dir); - stmt.bind(static_cast(scanTime)); - stmt.bind(dataVersion); - - return stmt.exec() != 0; - } catch (const std::exception &e) { - ERROR("insertLastScanTime failed. error_msg=" << e.what()); - return false; - } + stmt.bind(dir); + stmt.bind(static_cast(scanTime)); + stmt.bind(dataVersion); + stmt.exec(); } -bool Manager::deleteLastScanTime(const std::string &dir) noexcept +void Manager::deleteLastScanTime(const std::string &dir) { - try { - Statement stmt(m_conn, Query::DEL_SCAN_REQUEST_BY_DIR); + Statement stmt(m_conn, Query::DEL_SCAN_REQUEST_BY_DIR); - stmt.bind(dir); - - stmt.exec(); - return true; // even if no rows are deleted - } catch (const std::exception &e) { - ERROR("deleteLastScanTime failed. error_msg=" << e.what()); - return false; - } + stmt.bind(dir); + stmt.exec(); } -bool Manager::cleanLastScanTime() noexcept +void Manager::cleanLastScanTime() { - try { - Statement stmt(m_conn, Query::DEL_SCAN_REQUEST); + Statement stmt(m_conn, Query::DEL_SCAN_REQUEST); - stmt.exec(); - - return true; // even if no rows are deleted - } catch (const std::exception &e) { - ERROR("cleanLastScanTime failed. error_msg=" << e.what()); - return false; - } + stmt.exec(); } //=========================================================================== // DETECTED_MALWARE_FILE table //=========================================================================== -RowsShPtr Manager::getDetectedMalwares(const std::string &dir) noexcept +RowsShPtr Manager::getDetectedMalwares(const std::string &dir) { - try { - Statement stmt(m_conn, Query::SEL_DETECTED_BY_DIR); - stmt.bind(dir); - - RowsShPtr rows = std::make_shared>(); - - while (stmt.step()) { - RowShPtr row = std::make_shared(); - - row->targetName = stmt.getText(); - row->dataVersion = stmt.getText(); - row->severity = static_cast(stmt.getInt()); - row->threat = static_cast(stmt.getInt()); - row->malwareName = stmt.getText(); - row->detailedUrl = stmt.getText(); - row->ts = static_cast(stmt.getInt64()); - row->isIgnored = static_cast(stmt.getInt()); - - rows->emplace_back(std::move(row)); - } - - return rows; - } catch (const std::exception &e) { - ERROR("getDetectedMalwares failed. error_msg=" << e.what()); - return nullptr; - } -} - -RowShPtr Manager::getDetectedMalware(const std::string &path) noexcept -{ - try { - Statement stmt(m_conn, Query::SEL_DETECTED_BY_PATH); - stmt.bind(path); + Statement stmt(m_conn, Query::SEL_DETECTED_BY_DIR); + stmt.bind(dir); - if (!stmt.step()) - return nullptr; + RowsShPtr rows = std::make_shared>(); + while (stmt.step()) { RowShPtr row = std::make_shared(); + row->targetName = stmt.getText(); row->dataVersion = stmt.getText(); row->severity = static_cast(stmt.getInt()); @@ -303,84 +238,78 @@ RowShPtr Manager::getDetectedMalware(const std::string &path) noexcept row->ts = static_cast(stmt.getInt64()); row->isIgnored = static_cast(stmt.getInt()); - return row; - } catch (const std::exception &e) { - ERROR("getDetectedMalware failed. error_msg=" << e.what()); - return nullptr; + rows->emplace_back(std::move(row)); } -} -bool Manager::insertDetectedMalware(const CsDetected &d, - const std::string &dataVersion, - bool isIgnored) noexcept -{ - try { - Statement stmt(m_conn, Query::INS_DETECTED); - - stmt.bind(d.targetName); - stmt.bind(dataVersion); - stmt.bind(static_cast(d.severity)); - stmt.bind(static_cast(d.threat)); - stmt.bind(d.malwareName); - stmt.bind(d.detailedUrl); - stmt.bind(static_cast(d.ts)); - stmt.bind(static_cast(isIgnored)); - - return stmt.exec() == 1; - } catch (const std::exception &e) { - ERROR("insertDetectedMalware failed. error_msg=" << e.what()); - return false; - } + return rows; } -bool Manager::setDetectedMalwareIgnored(const std::string &path, - bool flag) noexcept +RowShPtr Manager::getDetectedMalware(const std::string &path) { - try { - Statement stmt(m_conn, Query::UPD_DETECTED_INGNORED); + Statement stmt(m_conn, Query::SEL_DETECTED_BY_PATH); + stmt.bind(path); - stmt.bind(flag); - stmt.bind(path); + if (!stmt.step()) + return nullptr; - return stmt.exec() == 1; - } catch (const std::exception &e) { - ERROR("setDetectedMalwareIgnored failed. error_msg=" << e.what()); - return false; - } + RowShPtr row = std::make_shared(); + + row->targetName = stmt.getText(); + row->dataVersion = stmt.getText(); + row->severity = static_cast(stmt.getInt()); + row->threat = static_cast(stmt.getInt()); + row->malwareName = stmt.getText(); + row->detailedUrl = stmt.getText(); + row->ts = static_cast(stmt.getInt64()); + row->isIgnored = static_cast(stmt.getInt()); + + return row; } -bool Manager::deleteDetectedMalware(const std::string &path) noexcept +void Manager::insertDetectedMalware(const CsDetected &d, + const std::string &dataVersion, + bool isIgnored) { - try { - Statement stmt(m_conn, Query::DEL_DETECTED_BY_PATH); - - stmt.bind(path); + Statement stmt(m_conn, Query::INS_DETECTED); + + stmt.bind(d.targetName); + stmt.bind(dataVersion); + stmt.bind(static_cast(d.severity)); + stmt.bind(static_cast(d.threat)); + stmt.bind(d.malwareName); + stmt.bind(d.detailedUrl); + stmt.bind(static_cast(d.ts)); + stmt.bind(static_cast(isIgnored)); + stmt.exec(); +} - stmt.exec(); +void Manager::setDetectedMalwareIgnored(const std::string &path, + bool flag) +{ + Statement stmt(m_conn, Query::UPD_DETECTED_INGNORED); - return true; // even if no rows are deleted - } catch (const std::exception &e) { - ERROR("deleteDetectedMalware failed.error_msg=" << e.what()); - return false; - } + stmt.bind(flag); + stmt.bind(path); + stmt.exec(); } -bool Manager::deleteDeprecatedDetectedMalwares(const std::string &dir, - const std::string &dataVersion) noexcept +void Manager::deleteDetectedMalware(const std::string &path) { - try { - Statement stmt(m_conn, Query::DEL_DETECTED_DEPRECATED); + Statement stmt(m_conn, Query::DEL_DETECTED_BY_PATH); - stmt.bind(dir); - stmt.bind(dataVersion); + stmt.bind(path); + stmt.exec(); +} + +void Manager::deleteDeprecatedDetectedMalwares(const std::string &dir, + const std::string &dataVersion) +{ + Statement stmt(m_conn, Query::DEL_DETECTED_DEPRECATED); - stmt.exec(); + stmt.bind(dir); + stmt.bind(dataVersion); - return true; // even if no rows are deleted - } catch (const std::exception &e) { - ERROR("deleteDeprecatedDetectedMalwares failed.error_msg=" << e.what()); - return false; - } + stmt.exec(); } } // namespace Db diff --git a/src/framework/db/manager.h b/src/framework/db/manager.h index c784113..1109127 100644 --- a/src/framework/db/manager.h +++ b/src/framework/db/manager.h @@ -41,26 +41,25 @@ public: int getSchemaVersion(); // ENGINE_STATE - int getEngineState(int engineId) noexcept; - bool setEngineState(int engineId, int state) noexcept; + int getEngineState(int engineId); + void setEngineState(int engineId, int state); // SCAN_REQUEST - long getLastScanTime(const std::string &dir, - const std::string &dataVersion) noexcept; - bool insertLastScanTime(const std::string &dir, long scanTime, - const std::string &dataVersion) noexcept; - bool deleteLastScanTime(const std::string &dir) noexcept; - bool cleanLastScanTime() noexcept; + time_t getLastScanTime(const std::string &dir, const std::string &dataVersion); + void insertLastScanTime(const std::string &dir, long scanTime, + const std::string &dataVersion); + void deleteLastScanTime(const std::string &dir); + void cleanLastScanTime(); // DETECTED_MALWARE_FILE & USER_RESPONSE - RowsShPtr getDetectedMalwares(const std::string &dirpath) noexcept; - RowShPtr getDetectedMalware(const std::string &filepath) noexcept; - bool insertDetectedMalware(const CsDetected &, const std::string &dataVersion, - bool isIgnored) noexcept; - bool setDetectedMalwareIgnored(const std::string &path, bool flag) noexcept; - bool deleteDetectedMalware(const std::string &path) noexcept; - bool deleteDeprecatedDetectedMalwares(const std::string &dir, - const std::string &dataVersion) noexcept; + RowsShPtr getDetectedMalwares(const std::string &dirpath); + RowShPtr getDetectedMalware(const std::string &filepath); + void insertDetectedMalware(const CsDetected &, const std::string &dataVersion, + bool isIgnored); + void setDetectedMalwareIgnored(const std::string &path, bool flag); + void deleteDetectedMalware(const std::string &path); + void deleteDeprecatedDetectedMalwares(const std::string &dir, + const std::string &dataVersion); private: void resetDatabase(); diff --git a/src/framework/db/statement.cpp b/src/framework/db/statement.cpp index 50e215b..b1ddfbd 100644 --- a/src/framework/db/statement.cpp +++ b/src/framework/db/statement.cpp @@ -16,10 +16,10 @@ #include "db/statement.h" #include -#include #include "db/connection.h" #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { namespace Db { @@ -34,7 +34,8 @@ const int ColumnStartIndex = -1; Statement::Statement(const Connection &db, const std::string &query) : m_stmt(nullptr), m_bindingIndex(BindingStartIndex) { - switch (sqlite3_prepare_v2(db.get(), query.c_str(), query.size(), &m_stmt, nullptr)) { + switch (sqlite3_prepare_v2(db.get(), query.c_str(), query.size(), &m_stmt, + nullptr)) { case SQLITE_OK: m_bindParamCount = ::sqlite3_bind_parameter_count(m_stmt); m_columnCount = ::sqlite3_column_count(m_stmt); @@ -44,7 +45,7 @@ Statement::Statement(const Connection &db, const std::string &query) : break; default: - throw std::runtime_error(db.getErrorMessage()); + ThrowExc(DbFailed, db.getErrorMessage()); } } @@ -52,7 +53,7 @@ Statement::Statement(const Connection &db, const std::string &query) : Statement::~Statement() { if (SQLITE_OK != ::sqlite3_finalize(m_stmt)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } void Statement::reset() @@ -60,7 +61,7 @@ void Statement::reset() clearBindings(); if (::sqlite3_reset(m_stmt) != SQLITE_OK) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); m_columnIndex = m_columnCount + 1; } @@ -68,7 +69,7 @@ void Statement::reset() void Statement::clearBindings() const { if (::sqlite3_clear_bindings(m_stmt) != SQLITE_OK) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); m_bindingIndex = BindingStartIndex; } @@ -91,14 +92,14 @@ bool Statement::step() return false; default: - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } } int Statement::exec() { if (::sqlite3_step(m_stmt) != SQLITE_DONE) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); // column cannot be 'get' after sqlite done, so make index overflow. m_columnIndex = m_columnCount + 1; @@ -108,45 +109,45 @@ int Statement::exec() void Statement::bind(int value) const { if (!isBindingIndexValid()) - throw std::logic_error("index overflowed when binding int to stmt."); + ThrowExc(DbFailed, "index overflowed when binding int to stmt."); if (SQLITE_OK != ::sqlite3_bind_int(m_stmt, ++m_bindingIndex, value)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } void Statement::bind(sqlite3_int64 value) const { if (!isBindingIndexValid()) - throw std::logic_error("index overflowed when binding int64 to stmt."); + ThrowExc(DbFailed, "index overflowed when binding int64 to stmt."); if (SQLITE_OK != ::sqlite3_bind_int64(m_stmt, ++m_bindingIndex, value)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } void Statement::bind(const std::string &value) const { if (!isBindingIndexValid()) - throw std::logic_error("index overflowed when binding string to stmt."); + ThrowExc(DbFailed, "index overflowed when binding string to stmt."); - if (SQLITE_OK != ::sqlite3_bind_text(m_stmt, ++m_bindingIndex, value.c_str(), -1, + if (SQLITE_OK != ::sqlite3_bind_text(m_stmt, ++m_bindingIndex, value.c_str(), + -1, SQLITE_STATIC)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } void Statement::bind(void) const { if (!isBindingIndexValid()) - throw std::logic_error("index overflowed when binding fields from row"); + ThrowExc(DbFailed, "index overflowed when binding fields from row"); if (SQLITE_OK != ::sqlite3_bind_null(m_stmt, ++m_bindingIndex)) - throw std::runtime_error(getErrorMessage()); + ThrowExc(DbFailed, getErrorMessage()); } bool Statement::isNullColumn() const { if (!isColumnIndexValid()) - throw std::runtime_error(FORMAT("column isn't valud for index: " << - m_columnIndex)); + ThrowExc(DbFailed, "column isn't valud for index: " << m_columnIndex); return SQLITE_NULL == sqlite3_column_type(m_stmt, (m_columnIndex + 1)); } @@ -154,7 +155,7 @@ bool Statement::isNullColumn() const int Statement::getInt() const { if (!isColumnIndexValid()) - throw std::logic_error("index overflowed when getting fields from row"); + ThrowExc(DbFailed, "index overflowed when getting fields from row"); return sqlite3_column_int(m_stmt, ++m_columnIndex); } @@ -162,7 +163,7 @@ int Statement::getInt() const sqlite3_int64 Statement::getInt64() const { if (!isColumnIndexValid()) - throw std::logic_error("index overflowed when getting fields from row"); + ThrowExc(DbFailed, "index overflowed when getting fields from row"); return sqlite3_column_int64(m_stmt, ++m_columnIndex); } @@ -170,9 +171,10 @@ sqlite3_int64 Statement::getInt64() const const char *Statement::getText() const { if (!isColumnIndexValid()) - throw std::logic_error("index overflowed when getting fields from row"); + ThrowExc(DbFailed, "index overflowed when getting fields from row"); - return reinterpret_cast(sqlite3_column_text(m_stmt, ++m_columnIndex)); + return reinterpret_cast(sqlite3_column_text(m_stmt, + ++m_columnIndex)); } } // namespace Db diff --git a/src/framework/service/app-deleter.cpp b/src/framework/service/app-deleter.cpp index d259f9a..149401a 100644 --- a/src/framework/service/app-deleter.cpp +++ b/src/framework/service/app-deleter.cpp @@ -22,13 +22,13 @@ #include "service/app-deleter.h" #include -#include #include #include #include #include "common/audit/logger.h" +#include "common/exception.h" #define MAX_WAIT_SEC 10 @@ -85,7 +85,7 @@ namespace Csr { bool AppDeleter::remove(const std::string &pkgid) { if (pkgid.empty()) - throw std::logic_error("pkgid shouldn't be empty in AppDeleter"); + ThrowExc(InternalError, "pkgid shouldn't be empty in AppDeleter"); std::unique_ptr client( pkgmgr_client_new(PC_REQUEST), pkgmgr_client_free); diff --git a/src/framework/service/core-usage.cpp b/src/framework/service/core-usage.cpp index 744925b..841641d 100644 --- a/src/framework/service/core-usage.cpp +++ b/src/framework/service/core-usage.cpp @@ -20,15 +20,14 @@ * @version 1.0 * @brief */ +#include "service/core-usage.h" -#include #include #include #include #include -#include "service/core-usage.h" - +#include "common/exception.h" namespace Csr { @@ -40,7 +39,7 @@ void CpuUsageManager::initialize() bool CpuUsageManager::setThreadCoreUsage(int percent) { if (percent > 100 || percent <= 0) - throw std::runtime_error("invalid core usage percent."); + ThrowExc(InternalError, "invalid core usage percent: " << percent); cpu_set_t set; CPU_ZERO(&set); @@ -75,7 +74,7 @@ int CpuUsageManager::getUsedCnt() CPU_ZERO(&usedCore); if (sched_getaffinity(0, sizeof(cpu_set_t), &usedCore) != 0) - throw std::runtime_error("sched_getaffinity failed."); + ThrowExc(InternalError, "sched_getaffinity failed."); return CPU_COUNT(&usedCore); } diff --git a/src/framework/service/cs-loader.cpp b/src/framework/service/cs-loader.cpp index afcda2e..cf4b041 100755 --- a/src/framework/service/cs-loader.cpp +++ b/src/framework/service/cs-loader.cpp @@ -21,10 +21,10 @@ */ #include "service/cs-loader.h" -#include #include #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -48,7 +48,7 @@ int CsLoader::globalInit(const std::string &ro_res_dir, const std::string &rw_working_dir) { if (ro_res_dir.empty() || rw_working_dir.empty()) - throw std::invalid_argument("cs loader global init"); + ThrowExc(InvalidParam, "cs loader global init"); return m_pc.fpGlobalInit(ro_res_dir.c_str(), rw_working_dir.c_str()); } @@ -66,7 +66,7 @@ int CsLoader::contextCreate(csre_cs_context_h &c) int CsLoader::contextDestroy(csre_cs_context_h c) { if (c == nullptr) - throw std::invalid_argument("cs loader context destroy"); + ThrowExc(InvalidParam, "cs loader context destroy"); return m_pc.fpContextDestroy(c); } @@ -76,7 +76,7 @@ int CsLoader::scanData(csre_cs_context_h c, csre_cs_detected_h *pdetected) { if (c == nullptr || data.empty() || pdetected == nullptr) - throw std::invalid_argument("cs loader scan data"); + ThrowExc(InvalidParam, "cs loader scan data"); return m_pc.fpScanData(c, data.data(), data.size(), pdetected); } @@ -85,7 +85,7 @@ int CsLoader::scanFile(csre_cs_context_h c, const std::string &filepath, csre_cs_detected_h *pdetected) { if (c == nullptr || filepath.empty() || pdetected == nullptr) - throw std::invalid_argument("cs loader scan file"); + ThrowExc(InvalidParam, "cs loader scan file"); return m_pc.fpScanFile(c, filepath.c_str(), pdetected); } @@ -94,7 +94,7 @@ int CsLoader::scanAppOnCloud(csre_cs_context_h c, const std::string &appdir, csre_cs_detected_h *pdetected) { if (c == nullptr || appdir.empty() || pdetected == nullptr) - throw std::invalid_argument("cs loader scan app on cloud"); + ThrowExc(InvalidParam, "cs loader scan app on cloud"); return m_pc.fpScanAppOnCloud(c, appdir.c_str(), pdetected); } @@ -103,7 +103,7 @@ int CsLoader::getSeverity(csre_cs_detected_h d, csre_cs_severity_level_e *pseverity) { if (d == nullptr || pseverity == nullptr) - throw std::invalid_argument("cs loader get severity"); + ThrowExc(InvalidParam, "cs loader get severity"); return m_pc.fpGetSeverity(d, pseverity); } @@ -112,7 +112,7 @@ int CsLoader::getThreatType(csre_cs_detected_h d, csre_cs_threat_type_e *pthreat) { if (d == nullptr || pthreat == nullptr) - throw std::invalid_argument("cs loader get threat type"); + ThrowExc(InvalidParam, "cs loader get threat type"); return m_pc.fpGetThreatType(d, pthreat); } @@ -120,7 +120,7 @@ int CsLoader::getThreatType(csre_cs_detected_h d, int CsLoader::getMalwareName(csre_cs_detected_h d, std::string &value) { if (d == nullptr) - throw std::invalid_argument("cs loader get malware name"); + ThrowExc(InvalidParam, "cs loader get malware name"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetMalwareName(d, cvalue); @@ -130,7 +130,7 @@ int CsLoader::getMalwareName(csre_cs_detected_h d, std::string &value) int CsLoader::getDetailedUrl(csre_cs_detected_h d, std::string &value) { if (d == nullptr) - throw std::invalid_argument("cs loader get detailed url"); + ThrowExc(InvalidParam, "cs loader get detailed url"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetDetailedUrl(d, cvalue); @@ -140,7 +140,7 @@ int CsLoader::getDetailedUrl(csre_cs_detected_h d, std::string &value) int CsLoader::getTimestamp(csre_cs_detected_h d, time_t *timestamp) { if (d == nullptr || timestamp == nullptr) - throw std::invalid_argument("cs loader get time stamp"); + ThrowExc(InvalidParam, "cs loader get time stamp"); return m_pc.fpGetTimestamp(d, timestamp); } @@ -165,7 +165,7 @@ int CsLoader::destroyEngine(csre_cs_engine_h e) int CsLoader::getEngineApiVersion(csre_cs_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get error string"); + ThrowExc(InvalidParam, "cs loader get error string"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineApiVersion(e, cvalue); @@ -175,7 +175,7 @@ int CsLoader::getEngineApiVersion(csre_cs_engine_h e, std::string &value) int CsLoader::getEngineVendor(csre_cs_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get engine vendor"); + ThrowExc(InvalidParam, "cs loader get engine vendor"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineVendor(e, cvalue); @@ -185,7 +185,7 @@ int CsLoader::getEngineVendor(csre_cs_engine_h e, std::string &value) int CsLoader::getEngineName(csre_cs_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get engine name"); + ThrowExc(InvalidParam, "cs loader get engine name"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineName(e, cvalue); @@ -195,7 +195,7 @@ int CsLoader::getEngineName(csre_cs_engine_h e, std::string &value) int CsLoader::getEngineVersion(csre_cs_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get engine version"); + ThrowExc(InvalidParam, "cs loader get engine version"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineName(e, cvalue); @@ -205,7 +205,7 @@ int CsLoader::getEngineVersion(csre_cs_engine_h e, std::string &value) int CsLoader::getEngineDataVersion(csre_cs_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get engine version"); + ThrowExc(InvalidParam, "cs loader get engine version"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineDataVersion(e, cvalue); @@ -215,7 +215,7 @@ int CsLoader::getEngineDataVersion(csre_cs_engine_h e, std::string &value) int CsLoader::getEngineLatestUpdateTime(csre_cs_engine_h e, time_t *ptime) { if (e == nullptr || ptime == nullptr) - throw std::invalid_argument("cs loader get latest update time"); + ThrowExc(InvalidParam, "cs loader get latest update time"); return m_pc.fpGetEngineLatestUpdateTime(e, ptime); } @@ -224,7 +224,7 @@ int CsLoader::getEngineActivated(csre_cs_engine_h e, csre_cs_activated_e *pactivated) { if (e == nullptr || pactivated == nullptr) - throw std::invalid_argument("cs loader get engine activated"); + ThrowExc(InvalidParam, "cs loader get engine activated"); return m_pc.fpGetEngineActivated(e, pactivated); } @@ -233,7 +233,7 @@ int CsLoader::getEngineVendorLogo(csre_cs_engine_h e, std::vector &value) { if (e == nullptr) - throw std::invalid_argument("cs loader get engine vendor logo"); + ThrowExc(InvalidParam, "cs loader get engine vendor logo"); unsigned char *cvalue = nullptr; unsigned int size = 0; @@ -252,8 +252,8 @@ CsLoader::CsLoader(const std::string &enginePath) void *handle = dlopen(enginePath.c_str(), RTLD_LAZY); if (handle == nullptr) - throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath << - " errno: " << errno)); + ThrowExc(InternalError, "engine dlopen error. path: " << enginePath << + " errno: " << errno); m_pc.dlhandle = handle; @@ -318,9 +318,8 @@ CsLoader::CsLoader(const std::string &enginePath) m_pc.fpGetEngineLatestUpdateTime == nullptr || m_pc.fpGetEngineActivated == nullptr || m_pc.fpGetEngineVendorLogo == nullptr) { dlclose(handle); - throw std::runtime_error(FORMAT("Failed to load funcs from engine library. " - "engine path: " << enginePath << "errno: " << - errno)); + ThrowExc(EngineError, "Failed to load funcs from engine library. " + "engine path: " << enginePath << "errno: " << errno); } } @@ -333,12 +332,12 @@ CsEngineContext::CsEngineContext(std::shared_ptr &loader) : m_loader(loader), m_context(nullptr) { if (m_loader == nullptr) - throw std::logic_error("invalid argument. shouldn't be null."); + ThrowExc(InvalidParam, "loader shouldn't be null."); auto ret = m_loader->contextCreate(m_context); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get engine context by loader. ret: " << ret)); + ThrowExc(EngineError, "get engine context by loader. ret: " << ret); } CsEngineContext::~CsEngineContext() @@ -346,8 +345,7 @@ CsEngineContext::~CsEngineContext() auto ret = m_loader->contextDestroy(m_context); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " << - ret)); + ThrowExc(EngineError, "destroy engine context by loader. ret: " << ret); } csre_cs_context_h &CsEngineContext::get(void) @@ -359,12 +357,12 @@ CsEngineInfo::CsEngineInfo(std::shared_ptr &loader) : m_loader(loader), m_info(nullptr) { if (m_loader == nullptr) - throw std::logic_error("invalid argument. shouldn't be null."); + ThrowExc(InvalidParam, "loader shouldn't be null."); auto ret = m_loader->getEngineInfo(m_info); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get engine info by loader. ret: " << ret)); + ThrowExc(EngineError, "get engine info by loader. ret: " << ret); } CsEngineInfo::~CsEngineInfo() @@ -372,7 +370,7 @@ CsEngineInfo::~CsEngineInfo() auto ret = m_loader->destroyEngine(m_info); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("destroy engine info by loader. ret: " << ret)); + ThrowExc(EngineError, "destroy engine info by loader. ret: " << ret); } csre_cs_engine_h &CsEngineInfo::get(void) diff --git a/src/framework/service/file-system.cpp b/src/framework/service/file-system.cpp index 3dce313..8051c85 100644 --- a/src/framework/service/file-system.cpp +++ b/src/framework/service/file-system.cpp @@ -21,7 +21,7 @@ */ #include "service/file-system.h" -#include +#include #include #include #include @@ -239,7 +239,8 @@ FileShrPtr DirVisitor::next() while (true) { if (readdir_r(m_currDir.get(), m_currEntry.get(), &result) != 0) - throw std::runtime_error("exception occurred. reading dir = " + m_dirs.front()); + throw std::system_error(std::error_code(), + FORMAT("reading dir = " << m_dirs.front())); if (result == nullptr) { // end of dir stream DEBUG("DirVisitor: end visiting. dir=" << m_dirs.front()); diff --git a/src/framework/service/logic.cpp b/src/framework/service/logic.cpp index 3b9d908..0bc43c0 100644 --- a/src/framework/service/logic.cpp +++ b/src/framework/service/logic.cpp @@ -24,9 +24,9 @@ #include #include #include -#include #include "common/audit/logger.h" +#include "common/exception.h" #include "service/type-converter.h" #include "service/file-system.h" #include "ui/askuser.h" @@ -68,24 +68,24 @@ Logic::Logic() : SAMPLE_ENGINE_RW_WORKING_DIR); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("global init cs engine. ret: " << ret)); + ThrowExc(EngineError, "global init cs engine. ret: " << ret); CsEngineInfo csEngineInfo(m_cs); ret = m_cs->getEngineDataVersion(csEngineInfo.get(), m_csDataVersion); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get cs engine data version. ret: " << ret)); + ThrowExc(EngineError, "get cs engine data version. ret: " << ret); ret = m_wp->globalInit(SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("global init wp engine. ret: " << ret)); + ThrowExc(EngineError, "global init wp engine. ret: " << ret); WpEngineInfo wpEngineInfo(m_wp); ret = m_wp->getEngineDataVersion(wpEngineInfo.get(), m_wpDataVersion); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get wp engine data version. ret: " << ret)); + ThrowExc(EngineError, "get wp engine data version. ret: " << ret); DEBUG("Service logic ctor done"); } @@ -95,12 +95,12 @@ Logic::~Logic() int ret = m_cs->globalDeinit(); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("global deinit cs engine. ret: " << ret)); + ThrowExc(EngineError, "global deinit cs engine. ret: " << ret); ret = m_wp->globalDeinit(); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("global deinit wp engine. ret: " << ret)); + ThrowExc(EngineError, "global deinit wp engine. ret: " << ret); } RawBuffer Logic::dispatch(const RawBuffer &in) @@ -185,8 +185,8 @@ RawBuffer Logic::dispatch(const RawBuffer &in) } default: - throw std::range_error(FORMAT("Command id[" << static_cast(info.first) << - "] isn't in range.")); + ThrowExc(InternalError, "Command id[" << static_cast(info.first) << + "] isn't in range."); } } @@ -239,8 +239,7 @@ RawBuffer Logic::scanData(const CsContext &context, const RawBuffer &data) break; default: - throw std::logic_error(FORMAT("Invalid severity: " << - static_cast(d.severity))); + ThrowExc(InternalError, "Invalid severity: " << static_cast(d.severity)); } return BinaryQueue::Serialize(ret, d).pop(); @@ -311,8 +310,7 @@ RawBuffer Logic::scanFile(const CsContext &context, const std::string &filepath) break; default: - throw std::logic_error(FORMAT("Invalid severity: " << - static_cast(d.severity))); + ThrowExc(InternalError, "Invalid severity: " << static_cast(d.severity)); } m_db->insertDetectedMalware(d, m_csDataVersion, d.response == CSR_CS_IGNORE); @@ -450,8 +448,7 @@ RawBuffer Logic::checkUrl(const WpContext &context, const std::string &url) break; default: - throw std::logic_error(FORMAT("Invalid level: " << - static_cast(wr.riskLevel))); + ThrowExc(InternalError, "Invalid level: " << static_cast(wr.riskLevel)); } return BinaryQueue::Serialize(ret, wr).pop(); @@ -517,8 +514,7 @@ CsDetected Logic::convert(csre_cs_detected_h &result) int eret = m_cs->getSeverity(result, &eseverity); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting cs detected[seveirty]. " - "ret: " << eret)); + ThrowExc(EngineError, "getting severity of cs detected. ret: " << eret); d.severity = Csr::convert(eseverity); @@ -527,8 +523,7 @@ CsDetected Logic::convert(csre_cs_detected_h &result) eret = m_cs->getThreatType(result, ðreat); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting cs detected[threat]. " - "ret: " << eret)); + ThrowExc(EngineError, "getting threat of cs detected. ret: " << eret); d.threat = Csr::convert(ethreat); @@ -536,22 +531,19 @@ CsDetected Logic::convert(csre_cs_detected_h &result) eret = m_cs->getMalwareName(result, d.malwareName); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting cs detected[name]. " - "ret: " << eret)); + ThrowExc(EngineError, "getting malware name of cs detected. ret: " << eret); // getting detailed url eret = m_cs->getDetailedUrl(result, d.detailedUrl); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting cs detected[detailed url]. " - "ret: " << eret)); + ThrowExc(EngineError, "getting detailed url of cs detected. ret: " << eret); // getting time stamp eret = m_cs->getTimestamp(result, &d.ts); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting cs detected[timestamp]. " - "ret: " << eret)); + ThrowExc(EngineError, "getting time stamp of cs detected. ret: " << eret); return d; } @@ -567,7 +559,7 @@ WpResult Logic::convert(csre_wp_check_result_h &r) int eret = m_wp->getRiskLevel(r, &elevel); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret)); + ThrowExc(EngineError, "getting risk level of wp result. ret: " << eret); wr.riskLevel = Csr::convert(elevel); @@ -575,7 +567,7 @@ WpResult Logic::convert(csre_wp_check_result_h &r) eret = m_wp->getDetailedUrl(r, wr.detailedUrl); if (eret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret)); + ThrowExc(EngineError, "getting detailed url of wp result. ret: " << eret); return wr; } diff --git a/src/framework/service/thread-pool.cpp b/src/framework/service/thread-pool.cpp index a39d4cf..7668c17 100644 --- a/src/framework/service/thread-pool.cpp +++ b/src/framework/service/thread-pool.cpp @@ -22,10 +22,10 @@ */ #include "service/thread-pool.h" -#include #include #include "common/audit/logger.h" +#include "common/exception.h" #define __BEGIN_CRITICAL__ { std::lock_guard lock(this->m_mutex); #define __END_CRITICAL__ } @@ -38,7 +38,7 @@ ThreadPool::ThreadPool(size_t min, size_t max) : m_stop(false) { if (m_min > m_max) - throw std::logic_error("thread pool MIN shouldn't be bigger than MAX"); + ThrowExc(InvalidParam, "thread pool MIN shouldn't be bigger than MAX"); for (size_t i = 0; i < m_min; i++) add(); diff --git a/src/framework/service/type-converter.cpp b/src/framework/service/type-converter.cpp index a8fcda8..3cc422b 100644 --- a/src/framework/service/type-converter.cpp +++ b/src/framework/service/type-converter.cpp @@ -21,9 +21,8 @@ */ #include "service/type-converter.h" -#include - #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -40,7 +39,7 @@ csr_cs_severity_level_e convert(const csre_cs_severity_level_e &e) return CSR_CS_SEVERITY_HIGH; default: - throw std::logic_error(FORMAT("Invalid eseverity: " << static_cast(e))); + ThrowExc(InternalError, "Invalid eseverity: " << static_cast(e)); } } @@ -57,7 +56,7 @@ csr_cs_threat_type_e convert(const csre_cs_threat_type_e &e) return CSR_CS_THREAT_GENERIC; default: - throw std::logic_error(FORMAT("Invalid ethreat: " << static_cast(e))); + ThrowExc(InternalError, "Invalid ethreat: " << static_cast(e)); } } @@ -77,7 +76,7 @@ csr_wp_risk_level_e convert(const csre_wp_risk_level_e &e) return CSR_WP_RISK_HIGH; default: - throw std::logic_error(FORMAT("Invalid elevel: " << static_cast(e))); + ThrowExc(InternalError, "Invalid elevel: " << static_cast(e)); } } diff --git a/src/framework/service/wp-loader.cpp b/src/framework/service/wp-loader.cpp index a652efb..df8ffdb 100755 --- a/src/framework/service/wp-loader.cpp +++ b/src/framework/service/wp-loader.cpp @@ -21,10 +21,10 @@ */ #include "service/wp-loader.h" -#include #include #include "common/audit/logger.h" +#include "common/exception.h" namespace Csr { @@ -66,7 +66,7 @@ int WpLoader::contextCreate(csre_wp_context_h &c) int WpLoader::contextDestroy(csre_wp_context_h c) { if (c == nullptr) - throw std::invalid_argument("wp loader context destroy"); + ThrowExc(InvalidParam, "wp loader context destroy"); return m_pc.fpContextDestroy(c); } @@ -75,7 +75,7 @@ int WpLoader::checkUrl(csre_wp_context_h c, const std::string &url, csre_wp_check_result_h *presult) { if (c == nullptr || url.empty() || presult == nullptr) - throw std::invalid_argument("wp loader check url error"); + ThrowExc(InvalidParam, "wp loader check url error"); return m_pc.fpCheckUrl(c, (const char *)url.c_str(), presult); } @@ -84,7 +84,7 @@ int WpLoader::getRiskLevel(csre_wp_check_result_h r, csre_wp_risk_level_e *plevel) { if (r == nullptr || plevel == nullptr) - throw std::invalid_argument("wp loader Get Risk Level error"); + ThrowExc(InvalidParam, "wp loader Get Risk Level error"); return m_pc.fpGetRiskLevel(r, plevel); } @@ -92,7 +92,7 @@ int WpLoader::getRiskLevel(csre_wp_check_result_h r, int WpLoader::getDetailedUrl(csre_wp_check_result_h r, std::string &value) { if (r == nullptr) - throw std::invalid_argument("wp loader get detailed url error"); + ThrowExc(InvalidParam, "wp loader get detailed url error"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetDetailedUrl(r, cvalue); @@ -121,7 +121,7 @@ int WpLoader::destroyEngine(csre_wp_engine_h e) int WpLoader::getEngineApiVersion(csre_wp_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get error string"); + ThrowExc(InvalidParam, "wp loader get error string"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineApiVersion(e, cvalue); @@ -131,7 +131,7 @@ int WpLoader::getEngineApiVersion(csre_wp_engine_h e, std::string &value) int WpLoader::getEngineVendor(csre_wp_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get engine vendor"); + ThrowExc(InvalidParam, "wp loader get engine vendor"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineVendor(e, cvalue); @@ -141,7 +141,7 @@ int WpLoader::getEngineVendor(csre_wp_engine_h e, std::string &value) int WpLoader::getEngineName(csre_wp_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get engine name"); + ThrowExc(InvalidParam, "wp loader get engine name"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineName(e, cvalue); @@ -151,7 +151,7 @@ int WpLoader::getEngineName(csre_wp_engine_h e, std::string &value) int WpLoader::getEngineVersion(csre_wp_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get engine version"); + ThrowExc(InvalidParam, "wp loader get engine version"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineName(e, cvalue); @@ -161,7 +161,7 @@ int WpLoader::getEngineVersion(csre_wp_engine_h e, std::string &value) int WpLoader::getEngineDataVersion(csre_wp_engine_h e, std::string &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get engine version"); + ThrowExc(InvalidParam, "wp loader get engine version"); return getValueCstr(value, [&](const char **cvalue) { return m_pc.fpGetEngineDataVersion(e, cvalue); @@ -171,7 +171,7 @@ int WpLoader::getEngineDataVersion(csre_wp_engine_h e, std::string &value) int WpLoader::getEngineLatestUpdateTime(csre_wp_engine_h e, time_t *ptime) { if (e == nullptr || ptime == nullptr) - throw std::invalid_argument("wp loader get latest update time"); + ThrowExc(InvalidParam, "wp loader get latest update time"); return m_pc.fpGetEngineLatestUpdateTime(e, ptime); } @@ -180,7 +180,7 @@ int WpLoader::getEngineActivated(csre_wp_engine_h e, csre_wp_activated_e *pactivated) { if (e == nullptr || pactivated == nullptr) - throw std::invalid_argument("wp loader get engine activated"); + ThrowExc(InvalidParam, "wp loader get engine activated"); return m_pc.fpGetEngineActivated(e, pactivated); } @@ -189,7 +189,7 @@ int WpLoader::getEngineVendorLogo(csre_wp_engine_h e, std::vector &value) { if (e == nullptr) - throw std::invalid_argument("wp loader get engine vendor logo"); + ThrowExc(InvalidParam, "wp loader get engine vendor logo"); unsigned char *cvalue = nullptr; unsigned int size = 0; @@ -208,8 +208,8 @@ WpLoader::WpLoader(const std::string &enginePath) void *handle = dlopen(enginePath.c_str(), RTLD_LAZY); if (handle == nullptr) - throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath << - " errno: " << errno)); + ThrowExc(InternalError, "engine dlopen error. path: " << enginePath << + " errno: " << errno); m_pc.dlhandle = handle; @@ -262,9 +262,8 @@ WpLoader::WpLoader(const std::string &enginePath) m_pc.fpGetEngineLatestUpdateTime == nullptr || m_pc.fpGetEngineActivated == nullptr || m_pc.fpGetEngineVendorLogo == nullptr) { dlclose(handle); - throw std::runtime_error(FORMAT("Failed to load funcs from engine library. " - "engine path: " << enginePath << "errno: " << - errno)); + ThrowExc(EngineError, "Failed to load funcs from engine library. " + "engine path: " << enginePath << "errno: " << errno); } } @@ -277,12 +276,12 @@ WpEngineContext::WpEngineContext(std::shared_ptr &loader) : m_loader(loader), m_context(nullptr) { if (m_loader == nullptr) - throw std::logic_error("invalid argument. shouldn't be null."); + ThrowExc(InvalidParam, "loader shouldn't be null."); auto ret = m_loader->contextCreate(m_context); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get engine context by loader. ret: " << ret)); + ThrowExc(EngineError, "get engine context by loader. ret: " << ret); } WpEngineContext::~WpEngineContext() @@ -290,8 +289,7 @@ WpEngineContext::~WpEngineContext() auto ret = m_loader->contextDestroy(m_context); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " << - ret)); + ThrowExc(EngineError, "destroy engine context by loader. ret: " << ret); } csre_wp_context_h &WpEngineContext::get(void) @@ -303,12 +301,12 @@ WpEngineInfo::WpEngineInfo(std::shared_ptr &loader) : m_loader(loader), m_info(nullptr) { if (m_loader == nullptr) - throw std::logic_error("invalid argument. shouldn't be null."); + ThrowExc(InvalidParam, "loader shouldn't be null."); auto ret = m_loader->getEngineInfo(m_info); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("get engine info by loader. ret: " << ret)); + ThrowExc(EngineError, "get engine info by loader. ret: " << ret); } WpEngineInfo::~WpEngineInfo() @@ -316,7 +314,7 @@ WpEngineInfo::~WpEngineInfo() auto ret = m_loader->destroyEngine(m_info); if (ret != CSRE_ERROR_NONE) - throw std::runtime_error(FORMAT("destroy engine info by loader. ret: " << ret)); + ThrowExc(EngineError, "destroy engine info by loader. ret: " << ret); } csre_wp_engine_h &WpEngineInfo::get(void) diff --git a/src/framework/ui/popup/logic.cpp b/src/framework/ui/popup/logic.cpp index 02faa0e..6df3ab2 100644 --- a/src/framework/ui/popup/logic.cpp +++ b/src/framework/ui/popup/logic.cpp @@ -21,13 +21,13 @@ */ #include "logic.h" -#include #include #include #include #include "common/binary-queue.h" #include "common/audit/logger.h" +#include "common/exception.h" #include "ui/common.h" #include "csr/content-screening-types.h" @@ -69,7 +69,7 @@ bool isCsCommand(const CommandId &cid) return false; default: - throw std::logic_error("Protocol error. unknown popup-service command id."); + ThrowExc(InternalError, "Protocol error. unknown popup-service command id."); } } @@ -128,7 +128,7 @@ RawBuffer Logic::dispatch(const RawBuffer &in) return csNotifyFile(message, d); default: - throw std::logic_error("Cannot be happened."); + ThrowExc(InternalError, "protocol error. invalid ui command id."); } } else { std::string message; @@ -143,7 +143,7 @@ RawBuffer Logic::dispatch(const RawBuffer &in) return wpNotify(message, item); default: - throw std::logic_error("Cannot be happened."); + ThrowExc(InternalError, "protocol error. invalid ui command id."); } } } diff --git a/src/include/csr/error.h b/src/include/csr/error.h index efbc1e1..8a976af 100644 --- a/src/include/csr/error.h +++ b/src/include/csr/error.h @@ -46,6 +46,7 @@ typedef enum { CSR_ERROR_INVALID_HANDLE = TIZEN_ERROR_CSR | 0x02, /**< The given handle is invalid */ CSR_ERROR_SERVER = TIZEN_ERROR_CSR | 0x03, /**< Server has been failed for some reason */ CSR_ERROR_NO_TASK = TIZEN_ERROR_CSR | 0x04, /**< No Task exists*/ + CSR_ERROR_DB = TIZEN_ERROR_CSR | 0x05, /**< DB transaction error */ CSR_ERROR_ENGINE_PERMISSION = TIZEN_ERROR_CSR | 0x11, /**< Insufficient permission of engine */ CSR_ERROR_ENGINE_NOT_EXIST = TIZEN_ERROR_CSR | 0x12, /**< No engine exists*/ CSR_ERROR_ENGINE_DIASABLED = TIZEN_ERROR_CSR | 0x13, /**< Engine is in disabled state*/ diff --git a/test/test-common.cpp b/test/test-common.cpp index 08d4c6d..faedd18 100644 --- a/test/test-common.cpp +++ b/test/test-common.cpp @@ -28,9 +28,9 @@ void exceptionGuard(const std::function &f) try { f(); } catch (const std::exception &e) { - BOOST_REQUIRE_MESSAGE(0, "std::exception catched: " << e.what()); + BOOST_REQUIRE_MESSAGE(0, "std::exception caught: " << e.what()); } catch (...) { - BOOST_REQUIRE_MESSAGE(0, "Unknown exception catched"); + BOOST_REQUIRE_MESSAGE(0, "Unknown exception caught"); } } diff --git a/test/test-internal-database.cpp b/test/test-internal-database.cpp index 3610bc5..f02f037 100644 --- a/test/test-internal-database.cpp +++ b/test/test-internal-database.cpp @@ -67,13 +67,13 @@ BOOST_AUTO_TEST_CASE(engine_state) Db::Manager db(TEST_DB_FILE, TEST_DB_SCRIPTS); - ASSERT_IF(db.setEngineState(1, 1), true); - ASSERT_IF(db.setEngineState(2, 2), true); + db.setEngineState(1, 1); + db.setEngineState(2, 2); ASSERT_IF(db.getEngineState(1), 1); ASSERT_IF(db.getEngineState(2), 2); - ASSERT_IF(db.setEngineState(1, 2), true); + db.setEngineState(1, 2); ASSERT_IF(db.getEngineState(1), 2); EXCEPTION_GUARD_END @@ -89,17 +89,15 @@ BOOST_AUTO_TEST_CASE(scan_time) long scantime = 100; std::string dataVersion = "1.0.0"; - ASSERT_IF(db.cleanLastScanTime(), true); + db.cleanLastScanTime(); ASSERT_IF(db.getLastScanTime(dir, dataVersion), -1); - ASSERT_IF(db.insertLastScanTime(dir, scantime, dataVersion), true); + db.insertLastScanTime(dir, scantime, dataVersion); - ASSERT_IF(db.insertLastScanTime("/opt/data", scantime + 100, dataVersion), - true); - ASSERT_IF(db.insertLastScanTime("/opt/data/etc", scantime + 200, dataVersion), - true); + db.insertLastScanTime("/opt/data", scantime + 100, dataVersion); + db.insertLastScanTime("/opt/data/etc", scantime + 200, dataVersion); ASSERT_IF(db.getLastScanTime(dir, dataVersion), scantime); - ASSERT_IF(db.cleanLastScanTime(), true); + db.cleanLastScanTime(); EXCEPTION_GUARD_END } @@ -145,13 +143,13 @@ BOOST_AUTO_TEST_CASE(detected_malware_file) auto detectedList = db.getDetectedMalwares("/opt"); ASSERT_IF(detectedList->empty(), true); - ASSERT_IF(db.insertDetectedMalware(malware1, initDataVersion, false), true); + db.insertDetectedMalware(malware1, initDataVersion, false); detected = db.getDetectedMalware(malware1.targetName); checkSameMalware(malware1, *detected); ASSERT_IF(detected->dataVersion, initDataVersion); ASSERT_IF(detected->isIgnored, false); - ASSERT_IF(db.insertDetectedMalware(malware2, initDataVersion, true), true); + db.insertDetectedMalware(malware2, initDataVersion, true); detected = db.getDetectedMalware(malware2.targetName); checkSameMalware(malware2, *detected); ASSERT_IF(detected->dataVersion, initDataVersion); @@ -171,14 +169,14 @@ BOOST_AUTO_TEST_CASE(detected_malware_file) } // setDetectedMalwareIgnored test - ASSERT_IF(db.setDetectedMalwareIgnored(malware1.targetName, true), true); + db.setDetectedMalwareIgnored(malware1.targetName, true); detected = db.getDetectedMalware(malware1.targetName); checkSameMalware(malware1, *detected); ASSERT_IF(detected->isIgnored, true); // deleteDeprecatedDetectedMalwares test - ASSERT_IF(db.insertDetectedMalware(malware3, changedDataVersion, false), true); - ASSERT_IF(db.deleteDeprecatedDetectedMalwares("/opt", changedDataVersion), true); + db.insertDetectedMalware(malware3, changedDataVersion, false); + db.deleteDeprecatedDetectedMalwares("/opt", changedDataVersion); detected = db.getDetectedMalware(malware3.targetName); checkSameMalware(malware3, *detected); ASSERT_IF(detected->dataVersion, changedDataVersion); @@ -188,7 +186,7 @@ BOOST_AUTO_TEST_CASE(detected_malware_file) CHECK_IS_NULL(db.getDetectedMalware(malware2.targetName)); // deleteDetectedMalware test - ASSERT_IF(db.deleteDetectedMalware(malware3.targetName), true); + db.deleteDetectedMalware(malware3.targetName); CHECK_IS_NULL(db.getDetectedMalware(malware3.targetName)); EXCEPTION_GUARD_END -- 2.7.4