diff --git a/base/include/common_mapped_file_errors.h b/base/include/common_mapped_file_errors.h index f672aecbf1f16fbe55e2c576937a0cf630963e8c..7174fb4c5e180f85f0c6d6426d9b0fe6079af55c 100644 --- a/base/include/common_mapped_file_errors.h +++ b/base/include/common_mapped_file_errors.h @@ -24,12 +24,11 @@ #define UTILS_COMMON_TIMER_ERRORS_H #include -#include "errors.h" #include "common_errors.h" +#include "errors.h" namespace OHOS { namespace Utils { - /** * ErrCode layout * diff --git a/base/include/mapped_file.h b/base/include/mapped_file.h index 0ccca64f2804152293862c09d3f48d548dd70038..2c0616ac172bb64ecd774331c1e90d233457044d 100644 --- a/base/include/mapped_file.h +++ b/base/include/mapped_file.h @@ -23,8 +23,9 @@ #define UTILS_BASE_MAPPED_FILE_H #include -#include +#include #include +#include #include #include "errors.h" @@ -94,7 +95,7 @@ public: inline char* End() const { - return data_ == nullptr? nullptr : data_ + size_ - 1; + return data_ == nullptr ? nullptr : data_ + size_ - 1; } inline char* RegionStart() const @@ -149,9 +150,10 @@ private: return (input % PageSize() == 0) ? input : (input / PageSize() + 1) * PageSize(); } - bool ValidMappedSize(off_t &targetSize, const struct stat &stat); + bool ValidMappedSize(off_t& targetSize, const struct stat& stat); + bool NormalizePath(); bool NormalizeSize(); - bool NormalizeMode(); + void NormalizeMode(); bool OpenFile(); bool SyncFileSize(off_t newSize); void Reset(); @@ -169,9 +171,9 @@ private: off_t offset_; MapMode mode_; int fd_ = -1; - int mapProt_; - int mapFlag_; - int openFlag_; + int mapProt_ = 0; + int mapFlag_ = 0; + int openFlag_ = 0; const char *hint_; }; diff --git a/base/include/semaphore_ex.h b/base/include/semaphore_ex.h index 5c4ca67cb0156c526dcb1bcdfaefa19dfca6fa1f..ccb1fd11abb901f3b3502acd82799f1b11999ac5 100644 --- a/base/include/semaphore_ex.h +++ b/base/include/semaphore_ex.h @@ -39,172 +39,6 @@ #include // timespec since c11 namespace OHOS { - -const int INVALID_SEMA_VALUE = -1; - -/** - * @brief NamedSemaphore. - * - * The only difference between the NamedSemaphore and the Semaphore - * lies in the form of creation and destruction. - * Generally, the name of the specified semaphore is explicitly specified - * at the time of creation, and can be accessed directly by name, - * so it can be used in any process/thread that knows its name. - * The characteristic of the NamedSemaphore is that they are saved in a file, - * so it is necessary to close the semaphore at the end like closing the file. - */ -class NamedSemaphore : public NoCopyable { -public: - -/** - * @brief Construct a NamedSemaphore object with a default name, - * and initial value of the semaphore. - * - * The constructor only creates a NamedSemaphore object and does not - * call sem_open(), so you need to call Create() to create semaphores - * after construction. - * - * @param size the initial value of semaphore. - */ - explicit NamedSemaphore(size_t); - -/** - * @brief Construct a NamedSemaphore object, - * specify the name and initial value of the semaphore. - * - * The constructor only creates a NamedSemaphore object and does not - * call sem_open(), so you need to call Create() to create semaphores - * after construction. - * - * @param name the name of NamedSemaphore; NamedSemaphore objects constructed - * by constructors that do not specify a name are assigned - * a unique name by default. - * @param size the initial value of semaphore. - */ - NamedSemaphore(const std::string&, size_t); - -/** - * @brief Destroy a NamedSemaphore object. - */ - ~NamedSemaphore() override; - -/** - * @brief Create and initialize a named semaphore. - * - * When a Namedsemaphore is created, a sem.xxx file is generated under - * /dev/shm, and all processes/threads that open the semaphore - * (including the processes/threads that created it) increment the reference - * counter for that file managed by the kernel. - * - * @return Success returns ture, failure returns false. - */ - bool Create(); - -/** - * @brief Remove the semaphore from the system. - * - * When Unlink() is called, the sem.xxx file under /dev/shm rather than - * the semaphore itself will be deleted immediately, and all processes that - * have opened the semaphore can still use it normally (because the semaphore - * file that has been opened is in memory), even if Unlink() is called - * immediately after opening the file, Wait(), Post() can also operate - * normally on the semaphore. - * Each semaphore has a reference counter that records the number of times - * it has been opened, and when the reference counter is 0, - * the named semaphore can be deleted from the file system by Unlink(). - * That is, the kernel does not actually delete the semaphore until - * all processes that open the semaphore have closed the semaphore - * (the last sem_close call completes). - * - * @return Success returns ture, failure returns false. - */ - bool Unlink(); - -/** - * @brief Open a Namedsemaphore file that has already been created. - * - * @return Success returns ture, failure returns false. - */ - bool Open(); - -/** - * @brief Turn off the NamedSemaphore. - * - * Turn off the semaphore and do not remove it from the system. - * - * @return Success returns ture, failure returns false. - */ - bool Close(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1). - * - * If the current count value is 0, the call blocks util another call of Post() - * makes the count greater than 0. - * - * @return Success returns 0; Failure returns -1, the semaphore will not be - * changed by the interface, and errno is set to indicate a specific error. - */ - bool Wait(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1); - * Non-blocking version. - * - * The non-blocking version of Wait() returns an error directly - * when the current semaphore = 0, not blocking. - * - * @return Success returns 0; Failure returns -1, the signal will - * not be changed by the interface, - * and errno is set to indicate a specific error. - */ - bool TryWait(); - -/** - * @brief Interface for acquiring semaphore (the count of semaphore -1); - * Specifies the blocking time version. - * - * The version of Wait() that specifies the blocking time, - * if the value of the semaphore is great than 0, - * the -1 operation is performed, and the function returns immediately; - * When the -1 operation cannot be executed, the call will block - * (specify the blocking time). - * - * @param ts Specifies the blocking time of the call. - * @return Success returns 0; Failure returns -1, the semaphore will - * not be changed by the interface, - * and errno is set to indicate a specific error. - */ - bool TimedWait(const struct timespec& ts); - -/** - * @brief Interface for releasing semaphore (the count of semaphore +1). - * - * If the value of the semaphore thus becomes greater than 0, - * another process/thread that is blocked due to the sem_wait of the call - * will be woken up and will lock the semaphore. - * - * @return Success returns 0; Failure returns -1, the semaphore will not be - * changed by the interface, and errno is set to indicate a specific error. - */ - bool Post(); - -/** - * @brief Get the value of the semaphore. - * - * @return The value of the semaphore is successfully returned; - * Failure returns INVALID_SEMA_VALUE, which is -1. - */ - int GetValue() const; - -private: - std::string name_; // The name of the NamedSemaphore object - int maxCount_; // The initial value of the NamedSemaphore object - void* sema_; // The pointer to the sem_t structure, which is essentially a long integer. - bool named_; // The flag of a Namedsemaphore that is false when no named semaphore name is specified. - -}; - /** * @brief Semaphore. This class is a counter to implement functions such as * mutual exclusion between processes/threads, synchronization, etc. diff --git a/base/src/event_demultiplexer.cpp b/base/src/event_demultiplexer.cpp index fef76d7bfee08014ad1fcd521cfeb5c85b313e43..87df8a71f0527960f537ad45991a12f199ccca61 100644 --- a/base/src/event_demultiplexer.cpp +++ b/base/src/event_demultiplexer.cpp @@ -85,26 +85,6 @@ uint32_t EventDemultiplexer::UpdateEventHandler(EventHandler* handler) return Update(EPOLL_CTL_MOD, handler); } -uint32_t EventDemultiplexer::RemoveEventHandler(EventHandler* handler) -{ - if (handler == nullptr) { - return TIMER_ERR_INVALID_VALUE; - } - - std::lock_guard lock(mutex_); - auto itor = eventHandlers_.find(handler->GetHandle()); - if (itor == eventHandlers_.end()) { - return TIMER_ERR_OK; - } - - eventHandlers_.erase(itor); - if (static_cast(eventHandlers_.size()) < maxEvents_) { - maxEvents_ = eventHandlers_.size() / HALF_OF_MAX_EVENT; - } - - return Update(EPOLL_CTL_DEL, handler); -} - uint32_t EventDemultiplexer::Update(int operation, EventHandler* handler) { struct epoll_event event; @@ -148,22 +128,10 @@ void EventDemultiplexer::Polling(int timeout /* ms */) uint32_t EventDemultiplexer::Epoll2Reactor(uint32_t epollEvents) { - if ((epollEvents & EPOLLHUP) && !(epollEvents & EPOLLIN)) { - return EventReactor::CLOSE_EVENT; - } - - if (epollEvents & EPOLLERR) { - return EventReactor::ERROR_EVENT; - } - if (epollEvents & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) { return EventReactor::READ_EVENT; } - if (epollEvents & EPOLLOUT) { - return EventReactor::WRITE_EVENT; - } - return EventReactor::NONE_EVENT; } @@ -174,10 +142,6 @@ uint32_t EventDemultiplexer::Reactor2Epoll(uint32_t reactorEvent) return TIMER_ERR_OK; case EventReactor::READ_EVENT: return EPOLLIN | EPOLLPRI; - case EventReactor::WRITE_EVENT: - return EPOLLOUT; - case EventReactor::READ_EVENT | EventReactor::WRITE_EVENT: - return EPOLLIN | EPOLLPRI | EPOLLOUT; default: UTILS_LOGD("invalid event %{public}u.", reactorEvent); return TIMER_ERR_DEAL_FAILED; diff --git a/base/src/event_demultiplexer.h b/base/src/event_demultiplexer.h index 3440abd8a5078b3f2c1fa82627a1d910b6e4d48a..5c25e5663c090835009b9066f20ea6c67d439edc 100644 --- a/base/src/event_demultiplexer.h +++ b/base/src/event_demultiplexer.h @@ -38,7 +38,6 @@ public: void Polling(int timeout); uint32_t UpdateEventHandler(EventHandler* handler); - uint32_t RemoveEventHandler(EventHandler* handler); private: uint32_t Update(int operation, EventHandler* handler); diff --git a/base/src/event_handler.cpp b/base/src/event_handler.cpp index f318cd0477aad27e1e8ceec45fbe75329382d221..fee1cabe71374f527094583dbd0d510cc315522b 100644 --- a/base/src/event_handler.cpp +++ b/base/src/event_handler.cpp @@ -31,17 +31,6 @@ void EventHandler::EnableRead() Update(); } -void EventHandler::EnableWrite() -{ - events_ |= EventReactor::WRITE_EVENT; - Update(); -} - -void EventHandler::DisableWrite() -{ - events_ &= ~EventReactor::WRITE_EVENT; - Update(); -} void EventHandler::DisableAll() { events_ = EventReactor::NONE_EVENT; @@ -50,29 +39,11 @@ void EventHandler::DisableAll() void EventHandler::HandleEvents(uint32_t events) { - if (events & (EventReactor::CLOSE_EVENT)) { - if (closeCallback_) { - closeCallback_(); - } - } - - if (events & (EventReactor::ERROR_EVENT)) { - if (errorCallback_) { - errorCallback_(); - } - } - if (events & (EventReactor::READ_EVENT)) { if (readCallback_) { readCallback_(); } } - - if (events & (EventReactor::WRITE_EVENT)) { - if (writeCallback_) { - writeCallback_(); - } - } } void EventHandler::Update() diff --git a/base/src/event_handler.h b/base/src/event_handler.h index 5a17082454b27aaeb709b3a9877736b55a70000f..af75cbea09bfb1a381843b1cf5a9c7e43465c8da 100644 --- a/base/src/event_handler.h +++ b/base/src/event_handler.h @@ -40,16 +40,11 @@ public: uint32_t Events() const { return (events_); } void EnableRead(); - void EnableWrite(); - void DisableWrite(); void DisableAll(); const EventReactor* GetEventReactor() const { return reactor_; } - void SetCloseCallback(const Callback& closeCallback) { closeCallback_ = closeCallback; } - void SetErrorCallback(const Callback& errorCallback) { errorCallback_ = errorCallback; } void SetReadCallback(const Callback& readCallback) { readCallback_ = readCallback; } - void SetWriteCallback(const Callback& writeCallback) { writeCallback_ = writeCallback; } void HandleEvents(uint32_t events); @@ -62,9 +57,6 @@ private: EventReactor* reactor_; Callback readCallback_; - Callback writeCallback_; - Callback closeCallback_; - Callback errorCallback_; }; } diff --git a/base/src/event_reactor.cpp b/base/src/event_reactor.cpp index bb57ca644107ee76ec47f089e5b60b88dc729c57..91c6ebdada19d307a9b2fa5a8240f244fc98ebea 100644 --- a/base/src/event_reactor.cpp +++ b/base/src/event_reactor.cpp @@ -35,13 +35,6 @@ EventReactor::~EventReactor() { } -void EventReactor::RemoveEventHandler(EventHandler* handler) -{ - if ((handler != nullptr) && (handler->GetEventReactor() == this) && (demultiplexer_ != nullptr)) { - demultiplexer_->RemoveEventHandler(handler); - } -} - void EventReactor::UpdateEventHandler(EventHandler* handler) { if ((handler != nullptr) && (handler->GetEventReactor() == this) && (demultiplexer_ != nullptr)) { diff --git a/base/src/event_reactor.h b/base/src/event_reactor.h index 794e44a50ef93a470ae7c315f1dd70cee1679e3d..83139bdc6277a4153a068696ddcba0d504cc7d26 100644 --- a/base/src/event_reactor.h +++ b/base/src/event_reactor.h @@ -63,7 +63,6 @@ public: } void UpdateEventHandler(EventHandler* handler); - void RemoveEventHandler(EventHandler* handler); uint32_t ScheduleTimer(const TimerCallback& cb, uint32_t interval /* ms */, int& timerFd, bool once); void CancelTimer(int timerFd); diff --git a/base/src/mapped_file.cpp b/base/src/mapped_file.cpp index 594d9d45647e261c2f57225b5c7eb5bfe49fc66f..a3f2f4f53b9c6f5e0c825c18f8e6b03390d7bbfe 100644 --- a/base/src/mapped_file.cpp +++ b/base/src/mapped_file.cpp @@ -12,34 +12,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "mapped_file.h" #include #include #include #include +#include "common_mapped_file_errors.h" #include "errors.h" #include "file_ex.h" #include "utils_log.h" -#include "common_mapped_file_errors.h" -#include "mapped_file.h" namespace OHOS { namespace Utils { off_t MappedFile::pageSize_ = static_cast(sysconf(_SC_PAGESIZE)); MappedFile::MappedFile(std::string& path, MapMode mode, off_t offset, off_t size, const char *hint) - :path_(path), size_(size), offset_(offset), mode_(mode), hint_(hint) -{ - if (Map() != MAPPED_FILE_ERR_OK) { - UTILS_LOGW("%{public}s: Mapping Failed.", __FUNCTION__); - } -} + :path_(path), size_(size), offset_(offset), mode_(mode), hint_(hint) {} -bool MappedFile::ValidMappedSize(off_t &targetSize, const struct stat &stb) +bool MappedFile::ValidMappedSize(off_t& targetSize, const struct stat& stb) { off_t max = RoundSize(stb.st_size) - offset_; // Avoid mapped size excessing - // that of the file more than a page, - if (max > 0) { // since write operation on it may raise signal 7. + // that of the file more than a page, + if (max > 0) { // since write operation on it may raise signal 7. targetSize = targetSize > max ? max : targetSize; } else { return false; @@ -47,19 +42,37 @@ bool MappedFile::ValidMappedSize(off_t &targetSize, const struct stat &stb) return true; } +bool MappedFile::NormalizePath() +{ + char canonicalPath[PATH_MAX]; + if (realpath(path_.c_str(), canonicalPath) == nullptr) { + if (errno != ENOENT) { + UTILS_LOGE("%{public}s get realpath failed.", __FUNCTION__); + return false; + } + } else { + path_ = canonicalPath; + } + + return true; +} bool MappedFile::NormalizeSize() { if (size_ == 0 || size_ < DEFAULT_LENGTH) { - UTILS_LOGD("%{public}s: Failed. Invalid mapping size: %{public}lld", + UTILS_LOGE("%{public}s: Failed. Invalid mapping size: %{public}lld", __FUNCTION__, static_cast(size_)); return false; } errno = 0; + if (!NormalizePath()) { + UTILS_LOGE("%{public}s normalize path failed. %{public}s", __FUNCTION__, strerror(errno)); + return false; + } if (!FileExists(path_)) { if ((mode_ & MapMode::CREATE_IF_ABSENT) == MapMode::DEFAULT) { - UTILS_LOGD("%{public}s: Failed. %{public}s", __FUNCTION__, strerror(errno)); + UTILS_LOGE("%{public}s: Failed. %{public}s", __FUNCTION__, strerror(errno)); return false; } @@ -82,7 +95,7 @@ bool MappedFile::NormalizeSize() // Get valid size if (!ValidMappedSize(size_, stb)) { - UTILS_LOGD("%{public}s: Failed. Invalid params. Specified size: %{public}lld, File size: %{public}lld", \ + UTILS_LOGE("%{public}s: Failed. Invalid params. Specified size: %{public}lld, File size: %{public}lld", \ __FUNCTION__, static_cast(size_), static_cast(stb.st_size)); return false; } @@ -91,7 +104,7 @@ bool MappedFile::NormalizeSize() return true; } -bool MappedFile::NormalizeMode() +void MappedFile::NormalizeMode() { mode_ &= (MapMode::PRIVATE | MapMode::READ_ONLY | MapMode::CREATE_IF_ABSENT); @@ -119,35 +132,30 @@ bool MappedFile::NormalizeMode() openFlag_ |= O_CREAT; } } - - return true; } ErrCode MappedFile::Normalize() { if (isNormed_) { - UTILS_LOGD("%{public}s: Failed. Already normalized.", __FUNCTION__); + UTILS_LOGD("%{public}s: Already normalized.", __FUNCTION__); return ERR_INVALID_OPERATION; } // resolve params for mapping region // offset if (offset_ < 0 || (offset_ % PageSize() != 0)) { - UTILS_LOGD("%{public}s: Failed. Invalid offset: %{public}lld", __FUNCTION__, static_cast(offset_)); + UTILS_LOGE("%{public}s: Failed. Invalid offset: %{public}lld", __FUNCTION__, static_cast(offset_)); return ERR_INVALID_VALUE; } // size if (!NormalizeSize()) { - UTILS_LOGD("%{public}s: Failed. Cannot normalize size.", __FUNCTION__); + UTILS_LOGE("%{public}s: Failed. Cannot normalize size.", __FUNCTION__); return ERR_INVALID_VALUE; } // Set open flags, mapping types and protections - if (!NormalizeMode()) { - UTILS_LOGD("%{public}s: Failed. Cannot normalize mode.", __FUNCTION__); - return ERR_INVALID_VALUE; - } + NormalizeMode(); isNormed_ = true; return MAPPED_FILE_ERR_OK; @@ -157,11 +165,15 @@ bool MappedFile::OpenFile() { int fd = open(path_.c_str(), openFlag_, S_IRWXU | S_IRGRP | S_IROTH); if (fd == -1) { - UTILS_LOGD("%{public}s: Failed. Cannot open file - %{public}s.", __FUNCTION__, strerror(errno)); + UTILS_LOGE("%{public}s: Failed. Cannot open file - %{public}s.", __FUNCTION__, strerror(errno)); return false; } if (isNewFile_) { + if (!NormalizePath()) { + UTILS_LOGE("%{public}s normalize path failed. %{public}s", __FUNCTION__, strerror(errno)); + return false; + } if (ftruncate(fd, EndOffset() + 1) == -1) { UTILS_LOGD("%{public}s: Failed. Cannot change file size: %{public}s.", __FUNCTION__, strerror(errno)); if (close(fd) == -1) { @@ -222,11 +234,11 @@ ErrCode MappedFile::Map() } while (true); if (data == MAP_FAILED) { - UTILS_LOGD("%{public}s: Mapping Failed. %{public}s", __FUNCTION__, strerror(errno)); + UTILS_LOGE("%{public}s: Mapping Failed. %{public}s", __FUNCTION__, strerror(errno)); return MAPPED_FILE_ERR_FAILED; } - rStart_ = reinterpret_cast(data); + rStart_ = reinterpret_cast(data); // set region boundary. rEnd_ = rStart_ + (RoundSize(size_) - 1LL); // set segment start @@ -247,12 +259,6 @@ ErrCode MappedFile::Unmap() UTILS_LOGW("%{public}s. Try unmapping with params changed.", __FUNCTION__); } - if (reinterpret_cast(rStart_) % PageSize() != 0) { - UTILS_LOGD("%{public}s: Failed. Invalid addr. Region start addr: %{public}p", - __FUNCTION__, reinterpret_cast(rStart_)); - return ERR_INVALID_VALUE; - } - if (munmap(rStart_, static_cast(size_)) == -1) { UTILS_LOGD("%{public}s: Failed. %{public}s.", __FUNCTION__, strerror(errno)); return MAPPED_FILE_ERR_FAILED; @@ -275,10 +281,6 @@ bool MappedFile::SyncFileSize(off_t newSize) } else if (offset_ + newSize <= stb.st_size) { UTILS_LOGW("%{public}s: Failed. Unextend file size, no need to sync.", __FUNCTION__); } else { - if (fd_ == -1) { - UTILS_LOGD("%{public}s: Failed. Invalid fd.", __PRETTY_FUNCTION__); - return false; - } if (ftruncate(fd_, offset_ + newSize) == -1) { UTILS_LOGD("%{public}s: Failed. Cannot extend file size: %{public}s.", __FUNCTION__, strerror(errno)); return false; @@ -289,21 +291,28 @@ bool MappedFile::SyncFileSize(off_t newSize) return true; } - ErrCode MappedFile::Resize(off_t newSize, bool sync) { + if (newSize == DEFAULT_LENGTH) { + struct stat stb = {0}; + if (stat(path_.c_str(), &stb) != 0) { + UTILS_LOGW("%{public}s: Failed. Get file size failed! Mapped size will be that of a page.", __FUNCTION__); + newSize = PageSize(); + } + + if (newSize == DEFAULT_LENGTH) { + newSize = stb.st_size; + } + } + if (newSize == 0 || newSize < DEFAULT_LENGTH || newSize == size_) { UTILS_LOGD("%{public}s: Failed. Cannot remap with the same /negative size.", __FUNCTION__); return ERR_INVALID_OPERATION; } if (!isMapped_) { - UTILS_LOGD("%{public}s: Failed. Cannot remap with no mapped file exists.", __FUNCTION__); - return ERR_INVALID_OPERATION; - } - - if (!isNormed_) { - UTILS_LOGD("%{public}s: Failed. Cannot remap with params unnormalized.", __FUNCTION__); + UTILS_LOGD("%{public}s: Failed. Invalid status. mapped:%{public}d, normed:%{public}d", \ + __FUNCTION__, isMapped_, isNormed_); return ERR_INVALID_OPERATION; } @@ -365,11 +374,11 @@ ErrCode MappedFile::TurnNext() } struct stat stb = {0}; - if (stat(path_.c_str(), &stb) != 0) { + int ret = stat(path_.c_str(), &stb); + if (ret != 0) { UTILS_LOGD("%{public}s: Failed. Get file size failed.", __FUNCTION__); return MAPPED_FILE_ERR_FAILED; } - if (EndOffset() + 1 >= stb.st_size) { UTILS_LOGD("%{public}s: Failed. No contents remained.", __FUNCTION__); return ERR_INVALID_OPERATION; @@ -382,8 +391,9 @@ ErrCode MappedFile::TurnNext() // if mapped, rStart_ and rEnd_ are viable if (isMapped_) { + char* curEnd = End(); // case 1: remap needed - if (End() == rEnd_) { + if (curEnd == rEnd_) { // check if larger than exact file size. if (EndOffset() + 1 + size_ > stb.st_size) { size_ = stb.st_size - EndOffset() - 1; @@ -393,8 +403,11 @@ ErrCode MappedFile::TurnNext() offset_ += oldSize; ErrCode res = Unmap(); - if (res != MAPPED_FILE_ERR_OK || (res = Resize()) != MAPPED_FILE_ERR_OK) { - UTILS_LOGD("%{public}s Failed. Fail to UnMap/Resize.", __FUNCTION__); + if (res == MAPPED_FILE_ERR_OK) { + res = Resize(); + } + if (res != MAPPED_FILE_ERR_OK) { + UTILS_LOGE("%{public}s Failed. Fail to UnMap/Resize.", __FUNCTION__); // restore offset_ = oldOff; size_ = oldSize; @@ -405,10 +418,9 @@ ErrCode MappedFile::TurnNext() } // case 2: no need to remap, but to adjust boundary. - if (End() + oldSize > rEnd_) { // otherwise else keep original "size_" - size_ = rEnd_ - End(); + if (curEnd + oldSize > rEnd_) { // otherwise keep original "size_" + size_ = rEnd_ - curEnd; } - data_ += oldSize; offset_ += oldSize; return MAPPED_FILE_ERR_OK; @@ -445,7 +457,7 @@ ErrCode MappedFile::Clear(bool force) { if (isMapped_) { ErrCode res = Unmap(); - if (!force && res != MAPPED_FILE_ERR_OK && res != ERR_INVALID_OPERATION) { + if (!force && res != MAPPED_FILE_ERR_OK) { UTILS_LOGD("%{public}s failed. UnMapping Failed.", __FUNCTION__); return res; } @@ -464,14 +476,14 @@ MappedFile::~MappedFile() { if (isMapped_) { ErrCode res = Unmap(); - if (res != MAPPED_FILE_ERR_OK && res != ERR_INVALID_OPERATION) { + if (res != MAPPED_FILE_ERR_OK) { UTILS_LOGW("%{public}s: File unmapping failed, it will be automatically \ unmapped when the process is terminated.", __FUNCTION__); } } if (fd_ != -1 && close(fd_) == -1) { - UTILS_LOGW("%{public}s: Failed. Cannot close the file: %{public}s.", \ + UTILS_LOGE("%{public}s: Failed. Cannot close the file: %{public}s.", \ __FUNCTION__, strerror(errno)); } } @@ -518,9 +530,9 @@ bool MappedFile::ChangeOffset(off_t val) isNormed_ = false; return true; - } else { - UTILS_LOGW("%{public}s: Change params failed. Unmapping failed.", __FUNCTION__); } + + UTILS_LOGW("%{public}s: Change params failed. Unmapping failed.", __FUNCTION__); } return false; } @@ -533,9 +545,9 @@ bool MappedFile::ChangeSize(off_t val) isNormed_ = false; return true; - } else { - UTILS_LOGW("%{public}s: Change params failed. Unmapping failed.", __FUNCTION__); } + + UTILS_LOGW("%{public}s: Change params failed. Unmapping failed.", __FUNCTION__); } return false; } diff --git a/base/src/semaphore_ex.cpp b/base/src/semaphore_ex.cpp index 205bf09cc36159ab6f7419a0496120a5811b3fbd..5023a75884a9b595aaf793e17d3f86cc042c595d 100644 --- a/base/src/semaphore_ex.cpp +++ b/base/src/semaphore_ex.cpp @@ -26,122 +26,6 @@ using namespace std; namespace OHOS { - -std::string GenUniqueName() -{ - static const uint64_t magic = 0xbcdecdeffedcedcbULL; - static uint64_t count = 0; - static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; - - pthread_mutex_lock(&mutex); - count++; - std::ostringstream fmt; - static const int outWidth = 20; - fmt << "_unnamed_sema_" << getpid() << "_" << magic << "_" - << std::setw(outWidth) << std::setfill('0') << count++; - pthread_mutex_unlock(&mutex); - return fmt.str(); -} - -NamedSemaphore::NamedSemaphore(size_t size) - :name_(GenUniqueName()), maxCount_(size), sema_(nullptr), named_(false) -{ -} - -NamedSemaphore::NamedSemaphore(const std::string& name, size_t size) - :name_(name), maxCount_(size), sema_(nullptr), named_(true) -{ -} - -NamedSemaphore::~NamedSemaphore() -{ - if (!named_) { - Unlink(); - } -} - -bool NamedSemaphore::Create() -{ - Unlink(); - sema_ = sem_open(name_.c_str(), O_CREAT, - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, maxCount_); // mode: 0666 - return (sema_ != SEM_FAILED); -} - -bool NamedSemaphore::Unlink() -{ - return sem_unlink(name_.c_str()) == 0; -} - -bool NamedSemaphore::Open() -{ - sema_ = sem_open(name_.c_str(), 0); - return (sema_ != SEM_FAILED); -} - -bool NamedSemaphore::Close() -{ - if (sema_ == nullptr) { - return false; - } - - if (sem_close(reinterpret_cast(sema_)) == 0) { - sema_ = nullptr; - return true; - } - return false; -} - -bool NamedSemaphore::Wait() -{ - if (sema_ == nullptr) { - return false; - } - - return (sem_wait(reinterpret_cast(sema_)) == 0); -} - -bool NamedSemaphore::TimedWait(const struct timespec& ts) -{ - if (sema_ == nullptr) { - return false; - } - - return (sem_timedwait(reinterpret_cast(sema_), &ts) == 0); -} - -bool NamedSemaphore::TryWait() -{ - if (sema_ == nullptr) { - return false; - } - - return (sem_trywait(reinterpret_cast(sema_)) == 0); - -} - -bool NamedSemaphore::Post() -{ - if ((sema_ == nullptr) || (GetValue() >= maxCount_)) { - return false; - } - - return (sem_post(reinterpret_cast(sema_)) == 0); -} - -int NamedSemaphore::GetValue() const -{ - if (sema_ == nullptr) { - return INVALID_SEMA_VALUE; - } - - int val = -1; - if (sem_getvalue(reinterpret_cast(sema_), &val) == 0) { - return val; - } - return INVALID_SEMA_VALUE; -} - void Semaphore::Wait() { std::unique_lock lck(mutex_); diff --git a/base/test/unittest/common/utils_event_test.cpp b/base/test/unittest/common/utils_event_test.cpp index ea00d932ea32a32f46d2be7830e8711421bd9090..7ec56e128aeedacc3d4244baa5c340a77499f792 100644 --- a/base/test/unittest/common/utils_event_test.cpp +++ b/base/test/unittest/common/utils_event_test.cpp @@ -80,6 +80,7 @@ void TestCallback() {} */ HWTEST_F(UtilsEventTest, testIOEventHandler001, TestSize.Level0) { + g_data = 0; // 1. Create io event handler std::shared_ptr handler = std::make_shared(-1); @@ -122,6 +123,7 @@ HWTEST_F(UtilsEventTest, testIOEventHandler001, TestSize.Level0) */ HWTEST_F(UtilsEventTest, testIOEventHandler002, TestSize.Level0) { + g_data = 0; // 1. Create io event handler std::shared_ptr handler = std::make_shared(-1); @@ -154,6 +156,57 @@ HWTEST_F(UtilsEventTest, testIOEventHandler002, TestSize.Level0) // 8. Remove the handler handler->Stop(reactor.get()); EXPECT_EQ(reactor->FindHandler(handler.get()), EVENT_SYS_ERR_NOT_FOUND); + + // 9. Add handler, then delete handler. handler will remove itself from the reactor during deconstruction. + ASSERT_TRUE(handler->Start(reactor.get())); + handler.reset(); +} + +/* + * @tc.name: testIOEventReactor001 + * @tc.desc: test basic interfaces of IOEventReactor. + */ +HWTEST_F(UtilsEventTest, testIOEventReactor001, TestSize.Level0) +{ + g_data = 0; + // Get fd + int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + ASSERT_NE(fd, -1); + + // 1. Create io event handlers + std::shared_ptr handler1 = std::make_shared(fd); + std::shared_ptr handler2 = std::make_shared(fd); + std::shared_ptr handler3 = std::make_shared(-1); // -1: invalid fd + std::shared_ptr handler4 = std::make_shared(fd); + + // 2. Create a reactor but not run + std::shared_ptr reactor = std::make_shared(); + ASSERT_EQ(reactor->SetUp(), EVENT_SYS_ERR_OK); + + // 3. Add handler + EXPECT_EQ(reactor->AddHandler(handler1.get()), EVENT_SYS_ERR_OK); + EXPECT_EQ(reactor->AddHandler(handler2.get()), EVENT_SYS_ERR_OK); + EXPECT_NE(reactor->AddHandler(handler3.get()), EVENT_SYS_ERR_OK); + EXPECT_NE(reactor->AddHandler(nullptr), EVENT_SYS_ERR_OK); + + // 4. Remove handler + EXPECT_NE(reactor->RemoveHandler(nullptr), EVENT_SYS_ERR_OK); + EXPECT_NE(reactor->RemoveHandler(handler4.get()), EVENT_SYS_ERR_OK); + EXPECT_EQ(reactor->RemoveHandler(handler2.get()), EVENT_SYS_ERR_OK); + + // 5. Update handler + EXPECT_NE(reactor->UpdateHandler(nullptr), EVENT_SYS_ERR_OK); + EXPECT_NE(reactor->UpdateHandler(handler3.get()), EVENT_SYS_ERR_OK); + EXPECT_EQ(reactor->UpdateHandler(handler1.get()), EVENT_SYS_ERR_OK); + EXPECT_EQ(reactor->UpdateHandler(handler4.get()), EVENT_SYS_ERR_OK); + + // 6. Find handler + EXPECT_NE(reactor->FindHandler(nullptr), EVENT_SYS_ERR_OK); + EXPECT_NE(reactor->FindHandler(handler3.get()), EVENT_SYS_ERR_OK); + + // 7. Clean handler + EXPECT_NE(reactor->Clean(-1), EVENT_SYS_ERR_OK); + EXPECT_EQ(reactor->Clean(fd), EVENT_SYS_ERR_OK); } TimerFdHandler::TimerFdHandler(int fd, const TimerEventCallback& cb) @@ -223,6 +276,7 @@ void TimerFdHandler::TimeOut() */ HWTEST_F(UtilsEventTest, testEvent001, TestSize.Level0) { + g_data = 0; // 1. Open timer int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); ASSERT_NE(fd, -1); @@ -254,6 +308,128 @@ HWTEST_F(UtilsEventTest, testEvent001, TestSize.Level0) loopThread.join(); } +/* + * @tc.name: testEvent002 + * @tc.desc: test changing event to EVENT_NONE. + */ +HWTEST_F(UtilsEventTest, testEvent002, TestSize.Level0) +{ + g_data = 0; + // 1. Open timer + int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + ASSERT_NE(fd, -1); + // 2. Create timer event handler + std::shared_ptr handler = std::make_shared(fd, &TimerCallback1); + + // 3. Create reactor for event loop + std::unique_ptr reactor = std::make_unique(); + ASSERT_EQ(reactor->SetUp(), EVENT_SYS_ERR_OK); + + // 4. Initialize timer handler and add it to reactor + ASSERT_TRUE(handler->Initialize(10)); + ASSERT_TRUE(handler->Start(reactor.get())); + + // 5. Run event loop + std::thread loopThread([&reactor]{ + reactor->Run(-1); + }); + + // 6. Change settings + reactor->DisableHandling(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + reactor->EnableHandling(); + handler->SetEvents(Events::EVENT_NONE); + + // 7. Wait for event handling + std::this_thread::sleep_for(std::chrono::milliseconds(16)); + + // 8. Check result, execute once at least + EXPECT_EQ(g_data, 0); + + // 9. terminate the event-loop (aka Run()) + reactor->Terminate(); + loopThread.join(); +} + +/* + * @tc.name: testEvent003 + * @tc.desc: test disable single event. + */ +HWTEST_F(UtilsEventTest, testEvent003, TestSize.Level0) +{ + g_data = 0; + // 1. Open timer + int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + ASSERT_NE(fd, -1); + // 2. Create timer event handler + std::shared_ptr handler = std::make_shared(fd, &TimerCallback1); + + // 3. Create reactor for event loop + std::unique_ptr reactor = std::make_unique(); + ASSERT_EQ(reactor->SetUp(), EVENT_SYS_ERR_OK); + + // 4. Initialize timer handler and add it to reactor + ASSERT_TRUE(handler->Initialize(10)); + ASSERT_TRUE(handler->Start(reactor.get())); + + // 5. Run event loop + std::thread loopThread([&reactor]{ + reactor->Run(-1); + }); + + // 6. Change settings + reactor->EnableHandling(); + ASSERT_TRUE(handler->Stop(reactor.get())); // block to get lock, so no need to wait. + + // 7. Check result, execute once at least + EXPECT_EQ(g_data, 0); + + // 8. terminate the event-loop (aka Run()) + reactor->Terminate(); + loopThread.join(); +} + +/* + * @tc.name: testEvent004 + * @tc.desc: test removing callback. + */ +HWTEST_F(UtilsEventTest, testEvent004, TestSize.Level0) +{ + g_data = 0; + // 1. Open timer + int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + ASSERT_NE(fd, -1); + // 2. Create timer event handler + std::shared_ptr handler = std::make_shared(fd, &TimerCallback1); + + // 3. Create reactor for event loop + std::unique_ptr reactor = std::make_unique(); + ASSERT_EQ(reactor->SetUp(), EVENT_SYS_ERR_OK); + + // 4. Initialize timer handler and add it to reactor + ASSERT_TRUE(handler->Initialize(10)); + ASSERT_TRUE(handler->Start(reactor.get())); + + // 5. Run event loop + std::thread loopThread([&reactor]{ + reactor->Run(-1); + }); + + // 6. Change settings + reactor->EnableHandling(); + handler->SetCallback(nullptr); + + // 7. Wait for event handling + std::this_thread::sleep_for(std::chrono::milliseconds(16)); + + // 8. Check result, execute once at least + EXPECT_EQ(g_data, 0); + + // 9. terminate the event-loop (aka Run()) + reactor->Terminate(); + loopThread.join(); +} + // Try to substitue underlying implementation of OHOS::UTILS::TIMER class TimerEventHandler { public: @@ -638,10 +814,10 @@ void TimeOutCallback2() } /* - * @tc.name: testEvent002 + * @tc.name: testNewTimer001 * @tc.desc: test basic function of timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent002, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer001, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer"); @@ -654,10 +830,10 @@ HWTEST_F(UtilsEventTest, testEvent002, TestSize.Level0) } /* - * @tc.name: testEvent003 + * @tc.name: testNewTimer002 * @tc.desc: test basic function of timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent003, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer002, TestSize.Level0) { g_data1 = 0; g_data2 = 0; @@ -673,10 +849,10 @@ HWTEST_F(UtilsEventTest, testEvent003, TestSize.Level0) } /* - * @tc.name: testEvent004 + * @tc.name: testNewTimer003 * @tc.desc: test basic function of timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent004, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer003, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer"); @@ -723,10 +899,10 @@ void A::StopTimer() } /* - * @tc.name: testEvent005 + * @tc.name: testNewTimer004 * @tc.desc: test wrapper of the timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent005, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer004, TestSize.Level0) { A a(10); EXPECT_TRUE(a.Init()); @@ -737,10 +913,10 @@ HWTEST_F(UtilsEventTest, testEvent005, TestSize.Level0) } /* - * @tc.name: testEvent006 + * @tc.name: testNewTimer005 * @tc.desc: test abnormal case of timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent006, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer005, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer", -1); @@ -761,10 +937,10 @@ HWTEST_F(UtilsEventTest, testEvent006, TestSize.Level0) } /* - * @tc.name: testEvent007 + * @tc.name: testNewTimer006 * @tc.desc: sleep test for ivi of timer implemented by new event-system. */ -HWTEST_F(UtilsEventTest, testEvent007, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer006, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer"); @@ -783,7 +959,7 @@ HWTEST_F(UtilsEventTest, testEvent007, TestSize.Level0) } /* - * @tc.name: testEvent008 + * @tc.name: testNewTimer007 * @tc.desc: recursive test of timer implemented by new event-system. */ void DoFunc(Timer &timer, int &count) @@ -814,7 +990,7 @@ void DoFunc2(Timer &timer, int &count) g_data1++; } -HWTEST_F(UtilsEventTest, testEvent008, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer007, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer"); @@ -833,10 +1009,10 @@ HWTEST_F(UtilsEventTest, testEvent008, TestSize.Level0) } /* - * @tc.name: testEvent09 + * @tc.name: testNewTimer008 * @tc.desc: test execute-once and execute-periodly tasks. */ -HWTEST_F(UtilsEventTest, testEvent09, TestSize.Level0) +HWTEST_F(UtilsEventTest, testNewTimer008, TestSize.Level0) { g_data1 = 0; Timer timer("test_timer"); diff --git a/base/test/unittest/common/utils_mapped_file_test.cpp b/base/test/unittest/common/utils_mapped_file_test.cpp index 897413377d3824f96104c1d60fbc9b3d2c733e16..765ba6a9c343e1cb1f820917aec444dd2ce8776f 100644 --- a/base/test/unittest/common/utils_mapped_file_test.cpp +++ b/base/test/unittest/common/utils_mapped_file_test.cpp @@ -12,17 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "mapped_file.h" +#include #include +#include #include #include -#include -#include +#include "common_mapped_file_errors.h" +#include "directory_ex.h" #include "errors.h" #include "file_ex.h" -#include "directory_ex.h" -#include "common_mapped_file_errors.h" -#include "mapped_file.h" using namespace testing::ext; using namespace OHOS::Utils; @@ -127,6 +127,7 @@ HWTEST_F(UtilsMappedFileTest, testDefaultMapping001, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // check status ASSERT_TRUE(mf.IsMapped()); @@ -145,8 +146,7 @@ HWTEST_F(UtilsMappedFileTest, testDefaultMapping001, TestSize.Level0) // 3. read from mapped file std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -191,6 +191,7 @@ HWTEST_F(UtilsMappedFileTest, testNewSharedMappingDefaultSize001, TestSize.Level // 2. map file MappedFile mf(filename, MapMode::DEFAULT | MapMode::CREATE_IF_ABSENT); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // check if file is created ASSERT_TRUE(FileExists(filename)); @@ -225,8 +226,7 @@ HWTEST_F(UtilsMappedFileTest, testNewSharedMappingDefaultSize001, TestSize.Level std::string toRead("Waiting to be read."); SaveStringToFile(filename, toRead, 0, true); std::string readout; - char* cur = mf.Begin(); - for (; *cur != '\0'; cur++) { + for (char* cur = mf.Begin(); *cur != '\0'; cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, toRead); @@ -245,12 +245,14 @@ HWTEST_F(UtilsMappedFileTest, testNewSharedMapping001, TestSize.Level0) RemoveTestFile(filename); // set params - char* hint = reinterpret_cast(0x80000); // new mapping region will not guaranteed to be located at `hint` + // new mapping region will not guaranteed to be located at `hint` + char* hint = reinterpret_cast(0x80000); // 0x80000: hint(expected address). off_t size = 1024; off_t offset = 4 * 1024; // 1. map a non-existed file MappedFile mf(filename, MapMode::DEFAULT | MapMode::CREATE_IF_ABSENT, offset, size, hint); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // check if file is created ASSERT_TRUE(FileExists(filename)); @@ -262,8 +264,8 @@ HWTEST_F(UtilsMappedFileTest, testNewSharedMapping001, TestSize.Level0) // check specified size struct stat stb = {0}; if (stat(filename.c_str(), &stb) == 0) { - EXPECT_EQ(stb.st_size, offset + size); // Exact file size should be offset + mapped size, contents will be - // zero-filled. + // Exact file size should be offset + mapped size, contents will be zero-filled. + EXPECT_EQ(stb.st_size, offset + size); } ASSERT_EQ(mf.Size(), size); @@ -290,8 +292,7 @@ HWTEST_F(UtilsMappedFileTest, testNewSharedMapping001, TestSize.Level0) std::string toRead("Waiting to be read."); SaveStringToFile(filename, toRead, offset, true); std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End() && *cur != '\0'; cur++) { + for (char* cur = mf.Begin(); cur <= mf.End() && *cur != '\0'; cur++) { readout.push_back(*cur); } std::cout << "Read finished" << std::endl; @@ -316,6 +317,7 @@ HWTEST_F(UtilsMappedFileTest, testPrivateMapping001, TestSize.Level0) // 2. map file MappedFile mf(filename, MapMode::DEFAULT | MapMode::PRIVATE); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status ASSERT_TRUE(mf.IsMapped()); @@ -323,8 +325,7 @@ HWTEST_F(UtilsMappedFileTest, testPrivateMapping001, TestSize.Level0) // 4. read from mapped file std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -359,6 +360,7 @@ HWTEST_F(UtilsMappedFileTest, testSharedReadOnlyMapping001, TestSize.Level0) // 2. map file MappedFile mf(filename, MapMode::DEFAULT | MapMode::READ_ONLY); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status ASSERT_TRUE(mf.IsMapped()); @@ -366,8 +368,7 @@ HWTEST_F(UtilsMappedFileTest, testSharedReadOnlyMapping001, TestSize.Level0) // 4. read from mapped file std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -392,6 +393,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap001, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -414,7 +416,6 @@ HWTEST_F(UtilsMappedFileTest, testReMap001, TestSize.Level0) stat(filename.c_str(), &stb); EXPECT_TRUE(stb.st_size == mf.Size() || mf.PageSize() == mf.Size()); - RemoveTestFile(filename); } @@ -438,9 +439,21 @@ HWTEST_F(UtilsMappedFileTest, testReMap002, TestSize.Level0) ASSERT_TRUE(CreateTestFile(filename, content)); ASSERT_TRUE(CreateTestFile(filename1, content1)); - // 2. map file MappedFile mf(filename); + // Change params when unmapped. + ASSERT_TRUE(mf.ChangeSize(mf.Size() + 1024)); + ASSERT_TRUE(mf.ChangeSize(MappedFile::DEFAULT_LENGTH)); + ASSERT_TRUE(mf.ChangeOffset(mf.PageSize())); + ASSERT_TRUE(mf.ChangeOffset(0)); + ASSERT_TRUE(mf.ChangePath(filename1)); + ASSERT_TRUE(mf.ChangePath(filename)); + ASSERT_TRUE(mf.ChangeHint(reinterpret_cast(0x89000))); // 0x89000: random address. + ASSERT_TRUE(mf.ChangeMode(MapMode::READ_ONLY)); + + // 2. map file + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); ASSERT_TRUE(mf.IsNormed()); @@ -452,15 +465,16 @@ HWTEST_F(UtilsMappedFileTest, testReMap002, TestSize.Level0) // 5. read from Mapped File std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); // 6. change params - mf.ChangePath(filename1); - mf.ChangeSize(MappedFile::DEFAULT_LENGTH); + ASSERT_TRUE(mf.ChangePath(filename1)); + ASSERT_TRUE(mf.ChangeSize(MappedFile::DEFAULT_LENGTH)); + ASSERT_TRUE(mf.ChangeHint(reinterpret_cast(0x80000))); // 0x80000: random address. + ASSERT_TRUE(mf.ChangeMode(MapMode::DEFAULT | MapMode::CREATE_IF_ABSENT)); // 7. check status after changing EXPECT_FALSE(mf.IsMapped()); @@ -478,8 +492,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap002, TestSize.Level0) // 11. read from Mapped File std::string readout1; - char* cur1 = mf.Begin(); - for (; cur1 <= mf.End(); cur1++) { + for (char* cur1 = mf.Begin(); cur1 <= mf.End(); cur1++) { readout1.push_back(*cur1); } EXPECT_EQ(readout1, content1); @@ -510,6 +523,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap003, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -522,8 +536,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap003, TestSize.Level0) // 5. read from Mapped File std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -548,8 +561,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap003, TestSize.Level0) // 11. read from Mapped File std::string readout1; - char* cur1 = mf.Begin(); - for (; cur1 <= mf.End(); cur1++) { + for (char* cur1 = mf.Begin(); cur1 <= mf.End(); cur1++) { readout1.push_back(*cur1); } EXPECT_EQ(readout1, content1); @@ -574,6 +586,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap004, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -630,6 +643,7 @@ HWTEST_F(UtilsMappedFileTest, testReMap005, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -667,6 +681,46 @@ HWTEST_F(UtilsMappedFileTest, testReMap005, TestSize.Level0) EXPECT_STREQ(res.c_str(), content.append("E").c_str()); // Changes will be sync in the original file. } +/* + * @tc.name: testReMap006 + * @tc.desc: Test remapping to via Resize(off_t, bool). + */ +HWTEST_F(UtilsMappedFileTest, testReMap006, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_remap.txt"; + std::string content = "Test for remapping use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + off_t size = 20; + MappedFile mf(filename, MapMode::DEFAULT, 0, size); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 3. check status after mapping + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 4. check size + ASSERT_TRUE(size == mf.Size()); + + // 5. remap to extend region + ASSERT_EQ(mf.Resize(MappedFile::DEFAULT_LENGTH, true), MAPPED_FILE_ERR_OK); + off_t lessSize = mf.Size() - 8; + ASSERT_EQ(mf.Resize(lessSize, true), MAPPED_FILE_ERR_OK); + // check status after remapping + EXPECT_TRUE(mf.IsMapped()); + EXPECT_TRUE(mf.IsNormed()); + + // 6. check size after remapping + struct stat stb = {0}; + stat(filename.c_str(), &stb); + EXPECT_EQ(lessSize, mf.Size()); +} + /* * @tc.name: testTurnNext001 * @tc.desc: Test TurnNext() when `IsMapped()`. @@ -683,15 +737,16 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext001, TestSize.Level0) struct stat stb = {0}; ASSERT_EQ(stat(filename.c_str(), &stb), 0); - off_t orig = stb.st_size; // 25 bit + off_t orig = stb.st_size; // 23 bytes // 2. extend its size int fd = open(filename.c_str(), O_RDWR | O_CLOEXEC); ASSERT_NE(fd, -1); - ASSERT_EQ(ftruncate(fd, MappedFile::PageSize() + MappedFile::PageSize() / 100LL), 0); + ASSERT_EQ(ftruncate(fd, MappedFile::PageSize() + MappedFile::PageSize() / 100LL), 0); // 100: ratio to a page. // 3. map file MappedFile mf(filename, MapMode::DEFAULT, 0, orig); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 4. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -708,7 +763,8 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext001, TestSize.Level0) off_t endOff; // 6. keep turnNext within a page - for (unsigned int cnt = 2; cnt < (MappedFile::PageSize() / orig); cnt++) { + for (unsigned int cnt = 2; cnt < (MappedFile::PageSize() / orig); cnt++) { // 2: start from 2 to take the first + // TunrNext() calling in consideration. endOff = mf.EndOffset(); EXPECT_EQ(mf.TurnNext(), MAPPED_FILE_ERR_OK); EXPECT_EQ(mf.StartOffset(), endOff + 1); @@ -769,6 +825,7 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext002, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); off_t curSize = mf.Size(); off_t curOff = mf.StartOffset(); @@ -803,6 +860,7 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext003, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -844,6 +902,7 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext004, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status after mapping ASSERT_TRUE(mf.IsMapped()); @@ -855,6 +914,74 @@ HWTEST_F(UtilsMappedFileTest, testTurnNext004, TestSize.Level0) RemoveTestFile(filename); } +/* + * @tc.name: testTurnNext005 + * @tc.desc: Test TurnNext() with file size less than one page. + */ +HWTEST_F(UtilsMappedFileTest, testTurnNext005, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_remap.txt"; + std::string content = "Test for remapping use.00"; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + struct stat stb = {0}; + ASSERT_EQ(stat(filename.c_str(), &stb), 0); + off_t orig = stb.st_size; // 25 bytes + + // 2. extend its size + int fd = open(filename.c_str(), O_RDWR | O_CLOEXEC); + ASSERT_NE(fd, -1); + ASSERT_EQ(ftruncate(fd, MappedFile::PageSize() + 10), 0); // 10: remain contents less than 25bits. + + // 3. map file + MappedFile mf(filename, MapMode::DEFAULT, 0, orig); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 4. check status after mapping + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 5. turn next mapped region with the same size as the file's initial size. + EXPECT_EQ(mf.TurnNext(), MAPPED_FILE_ERR_OK); + + off_t endOff; + // 6. keep turnNext within a page + for (unsigned int cnt = 2; cnt < (MappedFile::PageSize() / orig); cnt++) { // 2: start from 2 to take the first + // TunrNext() calling in consideration. + endOff = mf.EndOffset(); + EXPECT_EQ(mf.TurnNext(), MAPPED_FILE_ERR_OK); + EXPECT_EQ(mf.StartOffset(), endOff + 1); + EXPECT_EQ(mf.Size(), orig); + } + std::cout << "==Last TurnNext() with The Same Size==" << std::endl; + PrintStatus(mf); + + // 7. this turn will reach the bottom of a page + endOff = mf.EndOffset(); + char* rEnd = mf.RegionEnd(); + char* end = mf.End(); + EXPECT_EQ(mf.TurnNext(), MAPPED_FILE_ERR_OK); + EXPECT_EQ(mf.StartOffset(), endOff + 1); + EXPECT_EQ(mf.Size(), static_cast(rEnd - end)); + std::cout << "==Reached Bottom of A Page==" << std::endl; + PrintStatus(mf); + + // 8. this turn will trigger a remapping + endOff = mf.EndOffset(); + EXPECT_EQ(mf.TurnNext(), MAPPED_FILE_ERR_OK); + EXPECT_TRUE(mf.IsMapped()); + EXPECT_EQ(mf.StartOffset(), endOff + 1); + EXPECT_EQ(mf.Size(), 10); + EXPECT_EQ(mf.RegionStart(), mf.Begin()); + EXPECT_EQ(static_cast(mf.RegionEnd() - mf.RegionStart()) + 1LL, mf.PageSize()); + std::cout << "==Remap A New Page==" << std::endl; + PrintStatus(mf); +} + /* * @tc.name: testInvalidMap001 * @tc.desc: Test file mapping with invalid offset. @@ -872,10 +999,16 @@ HWTEST_F(UtilsMappedFileTest, testInvalidMap001, TestSize.Level0) // 2. map file off_t offset = 100; // Specify offset that is not multiple of page-size. MappedFile mf(filename, MapMode::DEFAULT, offset); + ASSERT_NE(mf.Map(), MAPPED_FILE_ERR_OK); + + MappedFile mf1(filename, MapMode::DEFAULT, -1); + ASSERT_NE(mf1.Map(), MAPPED_FILE_ERR_OK); // 3. check status EXPECT_FALSE(mf.IsMapped()); EXPECT_FALSE(mf.IsNormed()); // mapping will fail in normalize stage. + EXPECT_FALSE(mf1.IsMapped()); + EXPECT_FALSE(mf1.IsNormed()); // mapping will fail in normalize stage. RemoveTestFile(filename); } @@ -897,6 +1030,7 @@ HWTEST_F(UtilsMappedFileTest, testInvalidMap002, TestSize.Level0) // 2. map file off_t offset = 4 * 1024; // Specify offset excessing the substantial size of the file. MappedFile mf(filename, MapMode::DEFAULT, offset); + ASSERT_NE(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status EXPECT_FALSE(mf.IsMapped()); @@ -918,6 +1052,7 @@ HWTEST_F(UtilsMappedFileTest, testInvalidMap003, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_NE(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status EXPECT_FALSE(mf.IsMapped()); @@ -926,6 +1061,194 @@ HWTEST_F(UtilsMappedFileTest, testInvalidMap003, TestSize.Level0) RemoveTestFile(filename); } +/* + * @tc.name: testInvalidMap004 + * @tc.desc: Test mapping with invalid size. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap004, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_4.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + MappedFile mf(filename, MapMode::DEFAULT, 0, -2); // -2: less than DEFAULT_LENGTH(-1) + ASSERT_EQ(mf.Map(), ERR_INVALID_VALUE); + + // 3. map again with another invalid param. + MappedFile mf1(filename, MapMode::DEFAULT, 0, 0); + ASSERT_EQ(mf1.Map(), ERR_INVALID_VALUE); + + // 3. check status + EXPECT_FALSE(mf.IsMapped()); + EXPECT_FALSE(mf.IsNormed()); // mapping will fail in normalize stage. + EXPECT_FALSE(mf1.IsMapped()); + EXPECT_FALSE(mf1.IsNormed()); // mapping will fail in normalize stage. + + RemoveTestFile(filename); +} + +/* + * @tc.name: testInvalidMap005 + * @tc.desc: Test mapping an already mapped file. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap005, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_6.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + ASSERT_EQ(mf.Map(), ERR_INVALID_OPERATION); // Map again. + + // 3. check status + EXPECT_TRUE(mf.IsMapped()); + EXPECT_TRUE(mf.IsNormed()); + + RemoveTestFile(filename); +} + +/* + * @tc.name: testInvalidMap006 + * @tc.desc: Test resize with invalid params. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap006, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_7.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 3. check status + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 4. resize + EXPECT_EQ(mf.Resize(0), ERR_INVALID_OPERATION); + EXPECT_EQ(mf.Resize(-2), ERR_INVALID_OPERATION); // -2: less than DEFAULT_LENGTH(-1). + EXPECT_EQ(mf.Resize(mf.Size()), ERR_INVALID_OPERATION); + + // 5. Unmap first then resize. + ASSERT_EQ(mf.Unmap(), MAPPED_FILE_ERR_OK); + EXPECT_EQ(mf.Resize(mf.Size() + 8), ERR_INVALID_OPERATION); + + RemoveTestFile(filename); +} + +/* + * @tc.name: testInvalidMap007 + * @tc.desc: Test resize with no param changed. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap007, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_8.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 3. check status + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 4. resize + EXPECT_EQ(mf.Resize(), ERR_INVALID_OPERATION); + + RemoveTestFile(filename); +} + +/* + * @tc.name: testInvalidMap008 + * @tc.desc: Test TurnNext() with params changed. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap008, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_9.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. map file + MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 3. check status + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 5. Change params + ASSERT_TRUE(mf.ChangeSize(mf.Size() + 1)); + + // 6. check status + ASSERT_FALSE(mf.IsMapped()); + ASSERT_FALSE(mf.IsNormed()); + + // 4. turn next. + EXPECT_EQ(mf.TurnNext(), ERR_INVALID_OPERATION); + + RemoveTestFile(filename); +} + +/* + * @tc.name: testInvalidMap009 + * @tc.desc: Test ChangeXX() with invalid params. + */ +HWTEST_F(UtilsMappedFileTest, testInvalidMap009, TestSize.Level0) +{ + // 1. create a new file + std::string filename = "test_invalid_10.txt"; + std::string content = "Test for invalid use."; + filename.insert(0, SUITE_PATH).insert(0, BASE_PATH); + RemoveTestFile(filename); + + ASSERT_TRUE(CreateTestFile(filename, content)); + + // 2. create MappedFile + MappedFile mf(filename); + + // 3. map file + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); + + // 4. check status + ASSERT_TRUE(mf.IsMapped()); + ASSERT_TRUE(mf.IsNormed()); + + // 5. Change params + ASSERT_FALSE(mf.ChangeOffset(mf.StartOffset())); + ASSERT_FALSE(mf.ChangeSize(mf.Size())); + ASSERT_FALSE(mf.ChangeHint(mf.GetHint())); + ASSERT_FALSE(mf.ChangeMode(mf.GetMode())); + ASSERT_FALSE(mf.ChangePath(mf.GetPath())); + + RemoveTestFile(filename); +} + /* * @tc.name: testAutoAdjustedMode001 * @tc.desc: Test mapping file with invalid mapping mode, but can be auto adjusted. @@ -944,6 +1267,7 @@ HWTEST_F(UtilsMappedFileTest, testAutoAdjustedMode001, TestSize.Level0) MapMode mode = static_cast(1) | static_cast(16) | MapMode::PRIVATE | MapMode::READ_ONLY; // bits out of the scope will be ignored. MappedFile mf(filename, mode); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status EXPECT_TRUE(mf.IsMapped()); @@ -972,6 +1296,7 @@ HWTEST_F(UtilsMappedFileTest, testAutoAdjustedSize001, TestSize.Level0) // 2. map file off_t size = 5 * 1024; // Specified size excessing the last page of the file. MappedFile mf(filename, MapMode::DEFAULT, 0, size); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 3. check status EXPECT_TRUE(mf.IsMapped()); @@ -1010,6 +1335,7 @@ HWTEST_F(UtilsMappedFileTest, testAutoAdjustedSize002, TestSize.Level0) off_t offset = 4 * 1024; off_t size = 5 * 1024; // Specified size excessing the last page of the file. MappedFile mf(filename, MapMode::DEFAULT, offset, size); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 4. check status EXPECT_TRUE(mf.IsMapped()); @@ -1043,6 +1369,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile001, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); off_t size = mf.Size(); off_t offset = mf.StartOffset(); @@ -1074,8 +1401,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile001, TestSize.Level0) // 5. read from mapped file std::string readout; - char* cur = mfNew.Begin(); - for (; cur <= mfNew.End(); cur++) { + for (char* cur = mfNew.Begin(); cur <= mfNew.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -1110,6 +1436,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile002, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); off_t size = mf.Size(); off_t offset = mf.StartOffset(); @@ -1143,8 +1470,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile002, TestSize.Level0) ASSERT_EQ(mfNew.Map(), MAPPED_FILE_ERR_OK); // 6. read from mapped file std::string readout; - char* cur = mfNew.Begin(); - for (; cur <= mfNew.End(); cur++) { + for (char* cur = mfNew.Begin(); cur <= mfNew.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content); @@ -1185,7 +1511,9 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile003, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); MappedFile mf1(filename1); + ASSERT_EQ(mf1.Map(), MAPPED_FILE_ERR_OK); off_t size = mf1.Size(); off_t offset = mf1.StartOffset(); @@ -1208,8 +1536,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile003, TestSize.Level0) // 5. read from mapped file std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content1); @@ -1251,7 +1578,9 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile004, TestSize.Level0) // 2. map file MappedFile mf(filename); + ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); MappedFile mf1(filename1); + ASSERT_EQ(mf1.Map(), MAPPED_FILE_ERR_OK); off_t size = mf1.Size(); off_t offset = mf1.StartOffset(); @@ -1275,8 +1604,7 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile004, TestSize.Level0) ASSERT_EQ(mf.Map(), MAPPED_FILE_ERR_OK); // 6. read from mapped file std::string readout; - char* cur = mf.Begin(); - for (; cur <= mf.End(); cur++) { + for (char* cur = mf.Begin(); cur <= mf.End(); cur++) { readout.push_back(*cur); } EXPECT_EQ(readout, content1); @@ -1296,6 +1624,5 @@ HWTEST_F(UtilsMappedFileTest, testMoveMappedFile004, TestSize.Level0) RemoveTestFile(filename1); } - } // namespace } // namespace OHOS \ No newline at end of file diff --git a/base/test/unittest/common/utils_refbase_test.cpp b/base/test/unittest/common/utils_refbase_test.cpp index 2d3b149e76ab4cbeeb812d42975ec84ed5e02455..a2a303d698f58ad46acfd246ac23869eb22d1e2d 100644 --- a/base/test/unittest/common/utils_refbase_test.cpp +++ b/base/test/unittest/common/utils_refbase_test.cpp @@ -736,6 +736,47 @@ HWTEST_F(UtilsRefbaseTest, testRefbase006, TestSize.Level0) EXPECT_EQ(g_sptrCount, 0); } +/* + * @tc.name: testRefbase007 + * @tc.desc: test count of refcounter. + */ +HWTEST_F(UtilsRefbaseTest, testRefbase007, TestSize.Level0) +{ + sptr testObject1(new RefBase()); + EXPECT_EQ(testObject1->GetRefCounter()->GetRefCount(), 1); + wptr testObject2(testObject1); + EXPECT_EQ(testObject1->GetRefCounter()->GetRefCount(), 2); // 2: Refbase and WeakRefCounter +} + +/* + * @tc.name: testRefbase008 + * @tc.desc: test move constructor. + */ +HWTEST_F(UtilsRefbaseTest, testRefbase008, TestSize.Level0) +{ + RefBase baseObject1{}; + EXPECT_EQ(baseObject1.GetRefCounter()->GetRefCount(), 1); + + RefBase baseObject2{}; + EXPECT_EQ(baseObject2.GetRefCounter()->GetRefCount(), 1); + baseObject2 = std::move(baseObject1); + EXPECT_EQ(baseObject2.GetRefCounter()->GetRefCount(), 1); + EXPECT_EQ(baseObject1.GetRefCounter(), nullptr); + EXPECT_EQ(baseObject1.GetSptrRefCount(), 0); + EXPECT_EQ(baseObject1.GetWptrRefCount(), 0); + + RefBase baseObject3{}; + EXPECT_EQ(baseObject3.GetRefCounter()->GetRefCount(), 1); + baseObject3 = std::move(baseObject2); + EXPECT_EQ(baseObject3.GetRefCounter()->GetRefCount(), 1); + EXPECT_EQ(baseObject2.GetRefCounter(), nullptr); + EXPECT_EQ(baseObject2.GetSptrRefCount(), 0); + EXPECT_EQ(baseObject2.GetWptrRefCount(), 0); + + baseObject2 = std::move(baseObject1); + EXPECT_EQ(baseObject1.GetRefCounter(), baseObject2.GetRefCounter()); +} + class WptrTest : public RefBase { public: WptrTest() @@ -971,6 +1012,28 @@ HWTEST_F(UtilsRefbaseTest, testWptrefbase008, TestSize.Level0) EXPECT_EQ(testObject1->GetWptrRefCount(), 2); } +/* + * @tc.name: testSptrWptrefbase001 + * @tc.desc: test interaction between sptr and wptr. + */ +HWTEST_F(UtilsRefbaseTest, testSptrWptrefbase001, TestSize.Level0) +{ + wptr testObject1(new RefBase()); + EXPECT_EQ(testObject1->GetWptrRefCount(), 1); + { + sptr testObject2{}; + testObject2 = testObject1; + EXPECT_EQ(testObject2->GetSptrRefCount(), 1); + EXPECT_EQ(testObject2->GetWptrRefCount(), 2); // 2: sptr and WeakRefCounter + + sptr testObject3 = testObject1.promote(); + EXPECT_EQ(testObject2->GetSptrRefCount(), 2); // 2: 2 sptrs + EXPECT_EQ(testObject2->GetWptrRefCount(), 3); // 3: 2 sptrs and WeakRefCounter + testObject2->ExtendObjectLifetime(); + } + EXPECT_EQ(testObject1->GetWptrRefCount(), 1); +} + /* * @tc.name: testRefbaseDebug001 * @tc.desc: Test for single thread. Tracker can be enabled after construction diff --git a/base/test/unittest/common/utils_timer_test.cpp b/base/test/unittest/common/utils_timer_test.cpp index acaed1b64dbcf4af3ee8bb1650207d4377d6f122..5e15470a3fb63447bb531a42eb1a73b32459ac9a 100644 --- a/base/test/unittest/common/utils_timer_test.cpp +++ b/base/test/unittest/common/utils_timer_test.cpp @@ -337,5 +337,41 @@ HWTEST_F(UtilsTimerTest, testTimer011, TestSize.Level0) timer.Shutdown(); EXPECT_GE(g_data1, 8); /* 12 for max */ } + +/* + * @tc.name: testTimer012 + * @tc.desc: Test double setup. + */ +HWTEST_F(UtilsTimerTest, testTimer012, TestSize.Level0) +{ + g_data1 = 0; + Utils::Timer timer("test_timer"); + uint32_t ret = timer.Setup(); + EXPECT_EQ(Utils::TIMER_ERR_OK, ret); + ret = timer.Setup(); + EXPECT_EQ(Utils::TIMER_ERR_INVALID_VALUE, ret); + + timer.Shutdown(); +} + +/* + * @tc.name: testTimer013 + * @tc.desc: Test uncommon operations. + */ +HWTEST_F(UtilsTimerTest, testTimer013, TestSize.Level0) +{ + g_data1 = 0; + Utils::Timer timer("test_timer", -1); + uint32_t ret = timer.Setup(); + EXPECT_EQ(Utils::TIMER_ERR_OK, ret); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + timer.Shutdown(); + + Utils::Timer timer1("test_timer_1"); + ret = timer1.Setup(); + EXPECT_EQ(Utils::TIMER_ERR_OK, ret); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + timer1.Shutdown(false); +} } // namespace } // namespace OHOS \ No newline at end of file