decouple ace_engine_lite from js_builtin

Signed-off-by: wuhy_irobot2013 <wuhuayang@huawei.com>
Change-Id: Ib338ed294314e456fbe30acf91dfdf1cb3e231b0
This commit is contained in:
wuhy_irobot2013
2021-08-12 17:13:59 +08:00
parent 28b5c3b590
commit b37ba22066
41 changed files with 4893 additions and 56 deletions
+11 -11
View File
@@ -14,6 +14,10 @@
import("//build/lite/config/subsystem/aafwk/path.gni")
ACE_LITE_PATH = "//foundation/ace/ace_engine_lite/frameworks"
ACE_LITE_COMMON_PATH = "//foundation/ace/ace_engine_lite/frameworks/common"
NATIVE_ENGINE_PATH = "//foundation/ace/ace_engine_lite/frameworks/native_engine"
MODULE_MANAGER_PATH =
"//foundation/ace/ace_engine_lite/frameworks/module_manager"
GRAPHIC_LITE_PATH = "//foundation/graphic/ui"
ace_lite_include_dirs = [
@@ -48,17 +52,22 @@ ace_lite_include_dirs += [
"$ACE_LITE_PATH/src/core",
"$ACE_LITE_PATH/src/core/animation",
"$ACE_LITE_PATH/src/core/base",
"$ACE_LITE_PATH/src/core/base/cache",
"$ACE_LITE_PATH/src/core/components",
"$ACE_LITE_PATH/src/core/context",
"$ACE_LITE_PATH/src/core/directive",
"$ACE_LITE_PATH/src/core/router",
"$ACE_LITE_PATH/src/core/jsi",
"$ACE_LITE_PATH/src/core/modules",
"$ACE_LITE_PATH/src/core/router",
"$ACE_LITE_PATH/src/core/stylemgr",
"$ACE_LITE_PATH/src/core/wrapper",
"$ACE_LITE_PATH/targets",
"$ACE_LITE_COMMON_PATH/log",
"$ACE_LITE_COMMON_PATH/memory",
"$ACE_LITE_COMMON_PATH/memory/cache",
"$ACE_LITE_COMMON_PATH/utils",
"$NATIVE_ENGINE_PATH",
"$NATIVE_ENGINE_PATH/jsi",
"$MODULE_MANAGER_PATH",
"//third_party/jerryscript/jerry-core/include",
"//third_party/jerryscript/jerry-ext/include/jerryscript-ext",
"///third_party/jerryscript/jerry-port/default/include",
@@ -88,13 +97,8 @@ ace_lite_include_dirs_simulator = [
ace_lite_sources = [
"$ACE_LITE_PATH/src/core/animation/transition_impl.cpp",
"$ACE_LITE_PATH/src/core/async/js_async_work.cpp",
"$ACE_LITE_PATH/src/core/async/message_queue_utils.cpp",
"$ACE_LITE_PATH/src/core/base/ace_lock.cpp",
"$ACE_LITE_PATH/src/core/base/ace_log.cpp",
"$ACE_LITE_PATH/src/core/base/ace_mem_base.cpp",
"$ACE_LITE_PATH/src/core/base/async_task_manager.cpp",
"$ACE_LITE_PATH/src/core/base/cache/cache_manager.cpp",
"$ACE_LITE_PATH/src/core/base/dft_impl.cpp",
"$ACE_LITE_PATH/src/core/base/dfx_assist.cpp",
"$ACE_LITE_PATH/src/core/base/event_util.cpp",
@@ -104,8 +108,6 @@ ace_lite_sources = [
"$ACE_LITE_PATH/src/core/base/lazy_load_manager.cpp",
"$ACE_LITE_PATH/src/core/base/lazy_load_watcher.cpp",
"$ACE_LITE_PATH/src/core/base/locale_util.cpp",
"$ACE_LITE_PATH/src/core/base/mem_proc.cpp",
"$ACE_LITE_PATH/src/core/base/memory_heap.cpp",
"$ACE_LITE_PATH/src/core/base/number_parser.cpp",
"$ACE_LITE_PATH/src/core/base/product_adapter.cpp",
"$ACE_LITE_PATH/src/core/base/string_util.cpp",
@@ -156,11 +158,9 @@ ace_lite_sources = [
"$ACE_LITE_PATH/src/core/dialog/js_dialog.cpp",
"$ACE_LITE_PATH/src/core/directive/descriptor_utils.cpp",
"$ACE_LITE_PATH/src/core/directive/directive_watcher_callback.cpp",
"$ACE_LITE_PATH/src/core/jsi/jsi.cpp",
"$ACE_LITE_PATH/src/core/modules/app_module.cpp",
"$ACE_LITE_PATH/src/core/modules/dfx_module.cpp",
"$ACE_LITE_PATH/src/core/modules/dialog_module.cpp",
"$ACE_LITE_PATH/src/core/modules/module_manager.cpp",
"$ACE_LITE_PATH/src/core/modules/presets/cjson_parser.cpp",
"$ACE_LITE_PATH/src/core/modules/presets/console_log_impl.cpp",
"$ACE_LITE_PATH/src/core/modules/presets/console_module.cpp",
+4 -7
View File
@@ -38,9 +38,7 @@ config("ace_lite_config") {
shared_library("ace_lite") {
configs -= [ "//build/lite/config:language_cpp" ]
cflags = [
"-Wall"
]
cflags = [ "-Wall" ]
cflags_cc = cflags
configs += [ ":ace_lite_config" ]
public_configs = configs
@@ -48,22 +46,21 @@ shared_library("ace_lite") {
sources = ace_lite_sources
public_deps = [
"${appexecfwk_lite_path}/interfaces/kits/bundle_lite/js/builtin:capability_api",
"$ACE_LITE_COMMON_PATH:ace_common_lite",
"$MODULE_MANAGER_PATH:ace_module_manager_lite",
"$NATIVE_ENGINE_PATH:ace_native_engine_lite",
"//base/global/i18n_lite/frameworks/i18n:global_i18n",
"//base/global/resmgr_lite/frameworks/resmgr_lite:global_resmgr",
"//base/security/huks/frameworks/crypto_lite/js/builtin:ace_kit_cipher",
"//build/lite/config/component/cJSON:cjson_shared",
"//foundation/graphic/surface:lite_surface",
"//foundation/graphic/ui:lite_ui",
"//foundation/multimedia/camera_lite/frameworks:camera_lite",
"//foundation/multimedia/media_lite/frameworks/player_lite:player_lite",
"//foundation/multimedia/media_lite/interfaces/kits/player_lite/js/builtin:audio_lite_api",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/jerryscript/jerry-core:jerry-core_shared",
"//third_party/jerryscript/jerry-ext:jerry-ext_shared",
"//third_party/jerryscript/jerry-libm:jerry-libm_shared",
"//third_party/jerryscript/jerry-port/default:jerry-port-default_shared",
"//utils/native/lite/js/builtin:ace_utils_kits",
"//utils/native/lite/timer_task:ace_kit_timer",
]
+53
View File
@@ -0,0 +1,53 @@
#Copyright (c) 2021 Huawei Device Co., Ltd.
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import("//build/lite/config/component/lite_component.gni")
ace_common_root = "//foundation/ace/ace_engine_lite/frameworks/common"
ace_interface_root =
"//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin"
ace_target_root = "//foundation/ace/ace_engine_lite/frameworks/targets"
lite_component("ace_common_lite") {
features = [ ":ace_common" ]
}
shared_library("ace_common") {
include_dirs = [
"$ace_common_root/log",
"$ace_common_root/memory",
"$ace_common_root/memory/cache",
"$ace_common_root/utils",
"$ace_interface_root/base",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/bounds_checking_function/include",
]
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "liteos_m") {
include_dirs += [ "$ace_target_root/liteos_a" ]
} else if (ohos_kernel_type == "linux") {
include_dirs += [ "$ace_target_root/linux" ]
}
cflags = [ "-Wall" ]
cflags_cc = cflags
sources = [
"$ace_common_root/log/ace_log.cpp",
"$ace_common_root/memory/ace_mem_base.cpp",
"$ace_common_root/memory/cache/cache_manager.cpp",
"$ace_common_root/memory/mem_proc.cpp",
"$ace_common_root/memory/memory_heap.cpp",
]
public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
}
+80
View File
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ace_log.h"
#include <stdarg.h>
#include <stdio.h>
#ifdef TARGET_SIMULATOR
namespace OHOS {
namespace ACELite {
void PrintInfo(const char *format, va_list args)
{
vprintf(format, args);
printf("\n");
}
void HILOG_FATAL(HiLogModuleType mod, const char *msg, ...)
{
(void)(mod);
printf("[ACELite][FATAL]:");
va_list args;
va_start(args, msg);
PrintInfo(msg, args);
va_end(args);
}
void HILOG_ERROR(HiLogModuleType mod, const char *msg, ...)
{
(void)(mod);
printf("[ACELite][ERROR]:");
va_list args;
va_start(args, msg);
PrintInfo(msg, args);
va_end(args);
}
void HILOG_INFO(HiLogModuleType mod, const char *msg, ...)
{
(void)(mod);
printf("[ACELite][INFO]:");
va_list args;
va_start(args, msg);
PrintInfo(msg, args);
va_end(args);
}
void HILOG_WARN(HiLogModuleType mod, const char *msg, ...)
{
(void)(mod);
printf("[ACELite][WARN]:");
va_list args;
va_start(args, msg);
PrintInfo(msg, args);
va_end(args);
}
void HILOG_DEBUG(HiLogModuleType mod, const char *msg, ...)
{
(void)(mod);
printf("[ACELite][DEBUG]:");
va_list args;
va_start(args, msg);
PrintInfo(msg, args);
va_end(args);
}
} // namespace ACELite
} // namespace OHOS
#endif // TARGET_SIMULATOR
+70
View File
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_ACE_LOG_H
#define OHOS_ACELITE_ACE_LOG_H
#include "acelite_config.h"
#if defined(FEATURE_ACELITE_HI_LOG_PRINTF) && defined(FEATURE_ACELITE_MC_LOG_PRINTF)
#error Only one marco can be defined
#elif defined(FEATURE_ACELITE_HI_LOG_PRINTF) && defined(TARGET_SIMULATOR)
#error Only one marco can be defined
#elif defined(FEATURE_ACELITE_MC_LOG_PRINTF) && defined(TARGET_SIMULATOR)
#error Only one macro can be defined
#endif
#if defined(FEATURE_ACELITE_HI_LOG_PRINTF)
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0xD003900
#define LOG_TAG "ACE"
#include "hilog/log.h"
#elif defined(FEATURE_ACELITE_MC_LOG_PRINTF)
#include "hilog/log.h"
#ifndef HILOG_DEBUG
#define HILOG_DEBUG(mod, format, ...)
#endif
#ifndef HILOG_ERROR
#define HILOG_ERROR(mod, format, ...)
#endif
#ifndef HILOG_FATAL
#define HILOG_FATAL(mod, format, ...)
#endif
#ifndef HILOG_INFO
#define HILOG_INFO(mod, format, ...)
#endif
#ifndef HILOG_WARN
#define HILOG_WARN(mod, format, ...)
#endif
#ifndef HILOG_RACE
#define HILOG_RACE(mod, format, ...)
#endif
#elif (defined(TARGET_SIMULATOR))
namespace OHOS {
namespace ACELite {
typedef enum { HILOG_MODULE_ACE = 1 } HiLogModuleType;
void HILOG_FATAL(HiLogModuleType mod, const char *msg, ...);
void HILOG_ERROR(HiLogModuleType mod, const char *msg, ...);
void HILOG_INFO(HiLogModuleType mod, const char *msg, ...);
void HILOG_WARN(HiLogModuleType mod, const char *msg, ...);
void HILOG_DEBUG(HiLogModuleType mod, const char *msg, ...);
} // namespace ACELite
} // namespace OHOS
#else
#error One macro must be defined
#endif
#endif // OHOS_ACELITE_ACE_LOG_H
+70
View File
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ace_mem_base.h"
#include <cstdlib>
#include "cache_manager.h"
namespace OHOS {
namespace ACELite {
/**
* @brief g_customHookSet
* Record the memory hooks used for ACE, only can be setup once when system start-up.
* The standard memory allocating methods are used as default.
*/
static ACEMemHooks g_memoryHooks = {malloc, free, calloc};
/**
* @brief g_customHookSet flag for representing if the customer hooks are set
*/
static bool g_customHookSet = false;
void InitMemHooks(const ACEMemHooks &hooks)
{
if (g_customHookSet) {
// only can be configured once
return;
}
if ((hooks.malloc_func == nullptr) || (hooks.free_func == nullptr)) {
// the malloc and free must be given
return;
}
g_memoryHooks.malloc_func = hooks.malloc_func;
g_memoryHooks.free_func = hooks.free_func;
g_memoryHooks.calloc_func = hooks.calloc_func;
// set the flag
g_customHookSet = true;
}
void InitCacheBuf(uintptr_t bufAddress, size_t bufSize)
{
CacheManager::GetInstance().SetupCacheMemInfo(bufAddress, bufSize);
}
void *ace_malloc(size_t size)
{
return g_memoryHooks.malloc_func(size);
}
void *ace_calloc(size_t num, size_t size)
{
return (g_memoryHooks.calloc_func != nullptr) ? (g_memoryHooks.calloc_func(num, size)) : nullptr;
}
void ace_free(void *ptr)
{
g_memoryHooks.free_func(ptr);
}
} // namespace ACELite
} // namespace OHOS
+66
View File
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_CACHE_CONFIG_H
#define OHOS_ACELITE_CACHE_CONFIG_H
#include <cstdint>
namespace OHOS {
namespace ACELite {
/**
* The magic number used at the beginning of every cache memory area.
*/
constexpr uint8_t MAGIC_NUMBER_COUNT = 2; // will put one magic number at the begin and end of every buffer for each
constexpr uint8_t MAGIC_NUMBER_LENGTH = 4; // count in bytes
constexpr uint8_t MAGIC_NUMBER_TOTAL_LENGTH_FOR_EACH = MAGIC_NUMBER_LENGTH * MAGIC_NUMBER_COUNT;
constexpr uint32_t CACHE_MEM_MAGIC_NUMBER = 0xCCCCCCCC;
constexpr uint8_t ALIGNMENT_SIZE = 8;
constexpr uint8_t CACHE_USER_MAX_COUNT = 16;
/**
* Every cache user can not use more than the max length buffer.
* Count in KB.
*/
constexpr uint16_t CACHE_REQUIREMENT_MAX_KBS = 4096; // the cache max total size, 4M
constexpr uint8_t CACHE_UNIT_MAX_KBS = 128; // max 128KB
constexpr uint32_t CACHE_UNIT_MAX_BYTES = CACHE_UNIT_MAX_KBS * 1024;
/**
* Define the purpose of the specific cache memory range.
*/
enum CacheUser : uint8_t {
USER_LOCALICATION,
USER_PAGE_FILE,
USER_MAX_COUNT
};
/**
* Records the cache requester info.
*/
struct CacheUnit {
// the cache unit owner
CacheUser cacheUser_;
// the required min buffer length, count in KB
uint8_t minLength_;
// constructors
CacheUnit() : cacheUser_(USER_MAX_COUNT), minLength_(CACHE_UNIT_MAX_KBS) {}
CacheUnit(CacheUser user, uint8_t length) : cacheUser_(user), minLength_(length) {}
};
} // namespace ACELite
} // namespace OHOS
#endif // OHOS_ACELITE_CACHE_CONFIG_H
+210
View File
@@ -0,0 +1,210 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cache_manager.h"
#include "ace_log.h"
#include "securec.h"
namespace OHOS {
namespace ACELite {
/**
* This table will decide the cache usage distribution. If one module want to use cache functionality,
* it must config here first. The cache manager will assign buffer according to the actual whole
* buffer rang, if the buffer supplement is rich, every cache user might be assigned one buffer
* rang bigger than its lowest requirement.
*
* NOTE: the user must not be duplicated in this list
*/
const CacheUnit CacheManager::DEFAULT_CONFIG_TABLE[] = {
{USER_LOCALICATION, 16}, // localication key-value cache, lowest 16KB
};
CacheManager::CacheManager() : cacheState_(STATE_NORMAL)
{
configTable_ = DEFAULT_CONFIG_TABLE;
configTableLen_ = sizeof(DEFAULT_CONFIG_TABLE) / sizeof(CacheUnit);
ResetDistributedInfo();
}
CacheManager &CacheManager::GetInstance()
{
static CacheManager cacheManager;
return cacheManager;
}
void CacheManager::ResetDistributedInfo()
{
wholeCacheMemInfo_.cacheStartAddr = 0;
wholeCacheMemInfo_.cacheLength = 0;
if (EOK !=
memset_s(cacheUnitInfo_, sizeof(CacheMemInfo) * USER_MAX_COUNT, 0, sizeof(CacheMemInfo) * USER_MAX_COUNT)) {
HILOG_ERROR(HILOG_MODULE_ACE, "reset cache info failed");
}
}
void CacheManager::SetConfigTable(const CacheUnit *table, size_t count)
{
if (cacheState_ == STATE_SUCCESS) {
// reset
cacheState_ = STATE_NORMAL;
ResetDistributedInfo();
}
configTable_ = table;
configTableLen_ = count;
}
void CacheManager::SetupCacheMemInfo(uintptr_t startAddr, size_t length)
{
// only can be setup once
if (cacheState_ == STATE_SUCCESS) {
return;
}
// try to distribute the whole buffer, and if the buffer length can not meet the lowest requirement, just give up
cacheState_ = DistributeCacheRange(startAddr, length);
if (cacheState_ != STATE_SUCCESS) {
return;
}
wholeCacheMemInfo_.cacheStartAddr = startAddr;
wholeCacheMemInfo_.cacheLength = length;
}
CacheSetupState CacheManager::PrecheckStatus(uintptr_t startAddr, size_t totalBytes) const
{
// check basic info
if (configTableLen_ == 0 || configTable_ == nullptr) {
// no user, return normal as no one cares
return STATE_NORMAL;
}
if (configTableLen_ > CACHE_USER_MAX_COUNT) {
HILOG_ERROR(HILOG_MODULE_ACE, "too many user!");
return STATE_FAILURE;
}
if (startAddr == 0 || totalBytes == 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "error cache buffer rang!");
return STATE_FAILURE;
}
// calculate the lowest requirement
size_t lowestRequiredKBs = 0;
size_t index = 0;
while (index < configTableLen_) {
lowestRequiredKBs = lowestRequiredKBs + configTable_[index].minLength_;
index++;
}
if (lowestRequiredKBs > CACHE_REQUIREMENT_MAX_KBS) {
HILOG_ERROR(HILOG_MODULE_ACE, "the requirement KBs is too much!");
return STATE_FAILURE;
}
constexpr uint16_t bytesOneKB = 1024;
// convert the required KBs to bytes
size_t totalRequiredBytes = lowestRequiredKBs * bytesOneKB;
// consider the magic number length for each unit
totalRequiredBytes += (configTableLen_ * MAGIC_NUMBER_TOTAL_LENGTH_FOR_EACH);
if (totalRequiredBytes > totalBytes) {
// the given buffer is less than the lowest requirement
HILOG_ERROR(HILOG_MODULE_ACE, "the cache buffer length can not meet the lowest requirement!");
return STATE_FAILURE;
}
return STATE_SUCCESS;
}
CacheSetupState CacheManager::DistributeCacheRange(uintptr_t startAddr, size_t totalBytes)
{
CacheSetupState setupResult = PrecheckStatus(startAddr, totalBytes);
if (setupResult != STATE_SUCCESS) {
return setupResult;
}
size_t index = 0;
constexpr uint16_t bytesOneKB = 1024;
size_t offset = 0;
while (index < configTableLen_) {
size_t requestBytes = (configTable_[index].minLength_ * bytesOneKB) + MAGIC_NUMBER_TOTAL_LENGTH_FOR_EACH;
uintptr_t startPos = startAddr + offset;
cacheUnitInfo_[configTable_[index].cacheUser_].cacheStartAddr = startPos;
cacheUnitInfo_[configTable_[index].cacheUser_].cacheLength = requestBytes;
// set magic number
*(reinterpret_cast<uint32_t *>(startPos)) = CACHE_MEM_MAGIC_NUMBER;
*(reinterpret_cast<uint32_t *>(startPos + requestBytes - MAGIC_NUMBER_LENGTH)) = CACHE_MEM_MAGIC_NUMBER;
offset = offset + requestBytes;
index++;
}
return STATE_SUCCESS;
}
bool CacheManager::IsEnvReady(CacheUser user) const
{
if (cacheState_ != STATE_SUCCESS) {
return false;
}
return ((user < USER_MAX_COUNT) && (cacheUnitInfo_[user].cacheStartAddr != 0));
}
uintptr_t CacheManager::GetCacheBufAddress(CacheUser user) const
{
if (!IsEnvReady(user)) {
return 0;
}
return cacheUnitInfo_[user].cacheStartAddr + MAGIC_NUMBER_LENGTH;
}
size_t CacheManager::GetCacheBufLength(CacheUser user) const
{
if (!IsEnvReady(user)) {
return 0;
}
return cacheUnitInfo_[user].cacheLength - MAGIC_NUMBER_TOTAL_LENGTH_FOR_EACH;
}
bool CacheManager::IsCacheOverflow(CacheUser user) const
{
if (!IsEnvReady(user)) {
return false;
}
// get head and tail magic number
uint32_t *bufferHead = reinterpret_cast<uint32_t *>(cacheUnitInfo_[user].cacheStartAddr);
uint32_t headMagicNumber = reinterpret_cast<uint32_t>(*(bufferHead));
uint32_t *bufferTail = reinterpret_cast<uint32_t *>(cacheUnitInfo_[user].cacheStartAddr +
cacheUnitInfo_[user].cacheLength - MAGIC_NUMBER_LENGTH);
uint32_t tailMagicNumber = reinterpret_cast<uint32_t>(*(bufferTail));
// if the head magic number was over write, it means someone else overflow this area
if (headMagicNumber != CACHE_MEM_MAGIC_NUMBER) {
HILOG_ERROR(HILOG_MODULE_ACE, "the cache buffer[%d] was overflown by someone else?", user);
return true;
}
// if the tail magic number was over write, it means the user itself overflow this area
if (tailMagicNumber != CACHE_MEM_MAGIC_NUMBER) {
HILOG_ERROR(HILOG_MODULE_ACE, "the cache buffer[%d] was overflown by self?", user);
return true;
}
return false;
}
bool CacheManager::IsWholeCacheHealthy() const
{
if (cacheState_ != STATE_SUCCESS) {
return false;
}
for (int i = 0; i < USER_MAX_COUNT; i++) {
if (IsCacheOverflow(CacheUser(i))) {
return false;
}
}
return true;
}
} // namespace ACELite
} // namespace OHOS
+95
View File
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_CACHE_MANAGER_H
#define OHOS_ACELITE_CACHE_MANAGER_H
#include "cache_config.h"
#include <cstddef>
#include <cstdint>
#include "non_copyable.h"
namespace OHOS {
namespace ACELite {
/**
* The structure used for recording the cache memory detail information.
*/
struct CacheMemInfo {
// the cache memory start address, including the magic number at beginning
uintptr_t cacheStartAddr;
// count in bytes, and the max capability is 4M, including the maginc number at the beginning and ending
size_t cacheLength;
};
enum CacheSetupState : uint8_t {
STATE_NORMAL, // the cache is not initialized ever, or no user is configured
STATE_SUCCESS, // the cache was initialized and distributed to all users successfully
STATE_FAILURE, // the cache was tried be initialized but failed to distributed to all users
};
/**
* This is one singleton instance for cache memory management. It can be used
* out of the applications' lifecycle. It records the memory area for all kinds
* of caching purpose in the frameworks. If the cache memory rang is not setup,
* the cache functionality will not work.
*/
class CacheManager final {
public:
static CacheManager &GetInstance();
void SetupCacheMemInfo(uintptr_t startAddr, size_t length);
// return the start addrss of the assigned buffer the unit can use, which doesn't includ the starting magic number
uintptr_t GetCacheBufAddress(CacheUser user) const;
// return the total buffer length the unit can use, which doesn't include the starting and ending magic numbers
size_t GetCacheBufLength(CacheUser user) const;
bool IsCacheAvailable(CacheUser user) const;
bool IsCacheOverflow(CacheUser user) const;
bool IsWholeCacheHealthy() const;
/**
* @brief SetConfigTable give the config table from outside, call this function carefully
* @param table the config table
* @param count the actual user count
*/
void SetConfigTable(const CacheUnit *table, size_t count);
private:
ACE_DISALLOW_COPY_AND_MOVE(CacheManager);
CacheManager();
~CacheManager() = default;
/**
* @brief ResetDistributedInfo clean up all assigned buffer info
*/
void ResetDistributedInfo();
/**
* @brief DistributeCacheRange called once to assign proper memory rang to all the user in the config table
* @param startAddr the entire cache buffer start address
* @param totalBytes the entire cache length
* @return the result of the assignment process, if the memory size can not meet the lowest request, the process
* will return false as failure
*/
CacheSetupState DistributeCacheRange(uintptr_t startAddr, size_t totalBytes);
CacheSetupState PrecheckStatus(uintptr_t startAddr, size_t length) const;
bool IsEnvReady(CacheUser user) const;
CacheMemInfo wholeCacheMemInfo_;
CacheMemInfo cacheUnitInfo_[USER_MAX_COUNT]; // count in bytes
const CacheUnit *configTable_;
size_t configTableLen_;
CacheSetupState cacheState_;
static const CacheUnit DEFAULT_CONFIG_TABLE[];
};
} // namespace ACELite
} // namespace OHOS
#endif // OHOS_ACELITE_CACHE_MANAGER_H
+27
View File
@@ -0,0 +1,27 @@
#Copyright (c) 2021 Huawei Device Co., Ltd.
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import("//build/lite/config/test.gni")
import("//foundation/ace/ace_engine_lite/test/ace_test_config.gni")
unittest("js_frameworks_test_cache_manager") {
output_extension = "bin"
output_dir = test_output_root
configs = [ "$ace_lite_root/test:test_common_config" ]
sources = [ "common/cache_manager_tdd_test.cpp" ]
deps = ace_test_deps
}
group("cache_manager_unittest") {
deps = [ ":js_frameworks_test_cache_manager" ]
}
@@ -0,0 +1,266 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cache_manager_tdd_test.h"
#include "ace_mem_base.h"
namespace OHOS {
namespace ACELite {
const CacheUnit CacheManagerTddTest::TEST_CONFIG_TABLE[] = {
{USER_LOCALICATION, 16}, // localication key-value cache, lowest 16KB
};
void CacheManagerTddTest::SetUp()
{
const size_t count = 1;
CacheManager::GetInstance().SetConfigTable(TEST_CONFIG_TABLE, count);
}
/**
* @tc.name: CacheDistributeTest001
* @tc.desc: Verify the cache distribution process
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute001, TestSize.Level1)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 20 * 1024; // 20KB
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
/**
* @tc.steps: step2. trigger the cache setup
*/
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
/**
* @tc.steps: step3. verify the result
*/
uintptr_t localicationPos = CacheManager::GetInstance().GetCacheBufAddress(CacheUser::USER_LOCALICATION);
size_t localicationBufSize = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
const uintptr_t targetPos = startAddr + MAGIC_NUMBER_LENGTH;
const size_t unit = 1024;
const uint8_t magicNumberCount = MAGIC_NUMBER_COUNT;
const uint8_t localicationMin = 16;
const size_t targetLength = localicationMin * unit;
EXPECT_EQ(localicationPos, targetPos);
EXPECT_EQ(localicationBufSize, targetLength);
ace_free(buffer);
buffer = nullptr;
}
/**
* @tc.name: CacheDistributeTest002
* @tc.desc: Verify the cache distribution process
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute002, TestSize.Level1)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 20 * 1024; // 40KB
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
const uint8_t pageFileBufLength = 6;
const uint8_t localicationBufLength = 8;
const CacheUnit customerCacheUnitTable[] = {
{USER_PAGE_FILE, pageFileBufLength},
{USER_LOCALICATION, localicationBufLength},
};
/**
* @tc.steps: step2. trigger the cache setup
*/
const size_t count = 2;
CacheManager::GetInstance().SetConfigTable(customerCacheUnitTable, count);
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
/**
* @tc.steps: step3. verify the result
*/
uintptr_t bufferPos = CacheManager::GetInstance().GetCacheBufAddress(CacheUser::USER_LOCALICATION);
size_t bufSize = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
const size_t unit = 1024;
const uint8_t magicNumberCount = MAGIC_NUMBER_COUNT;
uintptr_t targetPos =
startAddr + (pageFileBufLength * unit) + (magicNumberCount * MAGIC_NUMBER_LENGTH) + MAGIC_NUMBER_LENGTH;
const size_t targetLength = localicationBufLength * unit;
EXPECT_EQ(bufferPos, targetPos);
EXPECT_EQ(bufSize, targetLength);
ace_free(buffer);
buffer = nullptr;
}
/**
* @tc.name: CacheDistributeTest003
* @tc.desc: Verify the cache distribution process
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute003, TestSize.Level1)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 2 * 1024; // 2KB
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
/**
* @tc.steps: step2. trigger the cache setup
*/
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
/**
* @tc.steps: step3. verify the result
*/
uintptr_t localPos = CacheManager::GetInstance().GetCacheBufAddress(CacheUser::USER_LOCALICATION);
size_t localBufSize = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
EXPECT_EQ(localPos, 0);
EXPECT_EQ(localBufSize, 0);
ace_free(buffer);
buffer = nullptr;
}
/**
* @tc.name: CacheDistributeTest004
* @tc.desc: Verify the cache distribution process
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute004, TestSize.Level1)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 20 * 1024; // 20KB
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
/**
* @tc.steps: step2. trigger the cache setup
*/
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
/**
* @tc.steps: step3. verify the result
*/
uintptr_t bufStartPos = CacheManager::GetInstance().GetCacheBufAddress(CacheUser::USER_LOCALICATION);
size_t bufLength = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
uint32_t headMagicNumber = *(uint32_t *)(bufStartPos - MAGIC_NUMBER_LENGTH);
EXPECT_EQ(headMagicNumber, CACHE_MEM_MAGIC_NUMBER);
const uint8_t magicNumberCount = MAGIC_NUMBER_COUNT;
uint32_t tailMagicNumber = *(uint32_t *)(bufStartPos + bufLength);
EXPECT_EQ(tailMagicNumber, CACHE_MEM_MAGIC_NUMBER);
ace_free(buffer);
buffer = nullptr;
}
/**
* @tc.name: CacheDistributeTest005
* @tc.desc: Verify the cache distribution process and overflow checking
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute005, TestSize.Level0)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 20 * 1024; // 20KB
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
/**
* @tc.steps: step2. trigger the cache setup
*/
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
size_t bufLength = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
if (bufLength < MAGIC_NUMBER_LENGTH) {
ace_free(buffer);
buffer = nullptr;
return;
}
/**
* @tc.steps: step3. overflow the cache head and tail
*/
buffer[0] = 0x11;
size_t tailPos = bufLength - MAGIC_NUMBER_LENGTH;
buffer[tailPos] = 0x22;
EXPECT_TRUE(CacheManager::GetInstance().IsCacheOverflow(CacheUser::USER_LOCALICATION));
EXPECT_FALSE(CacheManager::GetInstance().IsWholeCacheHealthy());
ace_free(buffer);
buffer = nullptr;
}
/**
* @tc.name: CacheDistributeTest006
* @tc.desc: Verify the cache distribution process, considering the magic number length
* @tc.require: AR000F8FOG
*/
HWTEST_F(CacheManagerTddTest, CacheDistribute006, TestSize.Level1)
{
/**
* @tc.steps: step1. prepare cache buffer
*/
const size_t totalSize = 16 * 1024; // 16KB, the total length equals to the requirement
char *buffer = static_cast<char *>(ace_malloc(sizeof(char) * totalSize));
if (buffer == nullptr) {
return;
}
/**
* @tc.steps: step2. trigger the cache setup, will failed, as no extra space for the magic numbers
*/
uintptr_t startAddr = reinterpret_cast<uintptr_t>(buffer);
CacheManager::GetInstance().SetupCacheMemInfo(startAddr, totalSize);
/**
* @tc.steps: step3. check the result, the distributing will fail
*/
uintptr_t bufStartPos = CacheManager::GetInstance().GetCacheBufAddress(CacheUser::USER_LOCALICATION);
size_t bufLength = CacheManager::GetInstance().GetCacheBufLength(CacheUser::USER_LOCALICATION);
EXPECT_EQ(bufStartPos, 0);
EXPECT_EQ(bufLength, 0);
ace_free(buffer);
buffer = nullptr;
}
/**
* used for debugging TDD implementation on simulator
*/
void CacheManagerTddTest::RunTests()
{
#ifndef TDD_ASSERTIONS
CacheDistribute001();
CacheDistribute002();
CacheDistribute003();
CacheDistribute004();
CacheDistribute005();
CacheDistribute006();
#endif // TDD_ASSERTIONS
}
} // namespace ACELite
} // namespace OHOS
@@ -0,0 +1,54 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_CACHE_MANAGER_TDD_TEST_H
#define OHOS_ACELITE_CACHE_MANAGER_TDD_TEST_H
#include "acelite_config.h"
#include "cache_config.h"
#include "cache_manager.h"
#ifdef TDD_ASSERTIONS
#include <climits>
#include <gtest/gtest.h>
#endif
#include "test_common.h"
namespace OHOS {
namespace ACELite {
#ifdef TDD_ASSERTIONS
using namespace std;
using namespace testing::ext;
class CacheManagerTddTest : public testing::Test {
#else
class CacheManagerTddTest {
#endif
public:
CacheManagerTddTest() = default;
~CacheManagerTddTest() = default;
void SetUp();
void CacheDistribute001();
void CacheDistribute002();
void CacheDistribute003();
void CacheDistribute004();
void CacheDistribute005();
void CacheDistribute006();
void RunTests();
private:
static const CacheUnit TEST_CONFIG_TABLE[];
};
} // namespace ACELite
} // namespace OHOS
#endif // OHOS_ACELITE_CACHE_MANAGER_TDD_TEST_H
+176
View File
@@ -0,0 +1,176 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mem_proc.h"
#ifdef SIMULATOR_MEMORY_ANALYSIS
#include <cstdio>
#include <windows.h>
#include <psapi.h>
#include "ace_log.h"
#include "gfx_utils/file.h"
#include "jerryscript-core.h"
#include "jerryscript.h"
#include "js_fwk_common.h"
#include "securec.h"
#include "time.h"
namespace OHOS {
namespace ACELite {
constexpr uint8_t MSG_LENGTH = 100;
constexpr uint32_t UNIT = 1024;
AceMemProc *AceMemProc::GetInstance()
{
static AceMemProc instance;
return &instance;
}
void AceMemProc::ClearUp()
{
if (!IsEnabled()) {
return;
}
// backup prev txt, create a new txt
struct stat fileStat;
int32_t state = stat(MEM_LOG_FILE_PATH, &fileStat);
if ((state != 0) || (fileStat.st_size == 0)) {
HILOG_ERROR(HILOG_MODULE_ACE, "Back up file error.");
return;
}
// it exists and not empty
time_t seconds = time(NULL);
char markdata[MSG_LENGTH];
if (sprintf_s(markdata, MSG_LENGTH, "%ti.txt", seconds) < 0) {
close(state);
state = -1;
return;
}
char *fullPath = RelocateJSSourceFilePath(MEM_BACK_UP_LOG_FILE_PREFIX, markdata);
if (fullPath == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "Back up file error.");
} else {
rename(MEM_LOG_FILE_PATH, fullPath);
ace_free(fullPath);
fullPath = nullptr;
}
close(state);
state = -1;
}
void AceMemProc::SysMemTracing()
{
if (!IsEnabled()) {
return;
}
HANDLE handle = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc = {0};
if (!GetProcessMemoryInfo(handle, (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc))) {
HILOG_ERROR(HILOG_MODULE_ACE, "Get process memory error.");
return;
}
FILE *fp = fopen(MEM_LOG_FILE_PATH, "a+");
if (fp == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "Get file error.");
return;
}
// physical memory
char markdata[MSG_LENGTH];
if (sprintf_s(markdata, MSG_LENGTH, "Phy:%d(KB)\n", uint32_t(pmc.WorkingSetSize / UNIT)) < 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "Output file error.");
fclose(fp);
fp = nullptr;
return;
}
fputs(markdata, fp);
// virtual memory
if (sprintf_s(markdata, MSG_LENGTH, "Vir:%d(KB)\n", uint32_t(pmc.PagefileUsage / UNIT)) < 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "Output file error.");
fclose(fp);
fp = nullptr;
return;
}
fputs(markdata, fp);
fflush(fp);
fclose(fp);
fp = nullptr;
}
void AceMemProc::JerryMemTracing()
{
if (!IsEnabled()) {
return;
}
jerry_heap_stats_t stats = {0};
if (!jerry_get_memory_stats(&stats)) {
HILOG_ERROR(HILOG_MODULE_ACE, "Get jerry heap stats error.");
return;
}
FILE *fp = nullptr;
fp = fopen(MEM_LOG_FILE_PATH, "a+");
if (fp == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "Get file error");
return;
}
size_t total = stats.size;
size_t current = stats.allocated_bytes;
size_t peak = stats.peak_allocated_bytes;
// jerry total memory
char markdata[MSG_LENGTH];
if (sprintf_s(markdata, MSG_LENGTH, "jerry heap total:%d(KB)\n", uint32_t(total / UNIT)) < 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "Output file error.");
fclose(fp);
fp = nullptr;
return;
}
fputs(markdata, fp);
// jerry current memory
if (sprintf_s(markdata, MSG_LENGTH, "jerry heap current:%d(KB)\n", uint32_t(current / UNIT)) < 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "Output file error.");
fclose(fp);
fp = nullptr;
return;
}
fputs(markdata, fp);
// jerry peak memory
if (sprintf_s(markdata, MSG_LENGTH, "jerry heap peak:%d(KB)\n", uint32_t(peak / UNIT)) < 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "Output file error.");
fclose(fp);
fp = nullptr;
return;
}
fputs(markdata, fp);
fflush(fp);
fclose(fp);
fp = nullptr;
}
bool AceMemProc::IsEnabled()
{
return IsFileExisted(MEM_PROC_ENABLE_FLAG_FILE);
}
} // namespace ACELite
} // namespace OHOS
#endif // SIMULATOR_MEMORY_ANALYSIS
+79
View File
@@ -0,0 +1,79 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_MEM_PROC_H
#define OHOS_ACELITE_MEM_PROC_H
#include "acelite_config.h"
#ifdef SIMULATOR_MEMORY_ANALYSIS
#define CLEAR_UP() AceMemProc::GetInstance()->ClearUp()
#define SYS_MEMORY_TRACING() AceMemProc::GetInstance()->SysMemTracing()
#define JERRY_MEMORY_TRACING() AceMemProc::GetInstance()->JerryMemTracing()
#else
#define CLEAR_UP()
#define SYS_MEMORY_TRACING()
#define JERRY_MEMORY_TRACING()
#endif // SIMULATOR_MEMORY_ANALYSIS
#ifdef SIMULATOR_MEMORY_ANALYSIS
namespace OHOS {
namespace ACELite {
class AceMemProc {
public:
/**
* @brief Use static global variable for easy access in different source code file.
*
* @return global singleton AceMemProc object
*/
static AceMemProc *GetInstance();
/**
* @brief Check if the memory proc is enabled or not.
*
* @return true for enabled, false for not
*/
static bool IsEnabled();
/**
* @brief Clear up the previous analysis file.
*/
void ClearUp();
/**
* @brief Output the system memory.
*/
void SysMemTracing();
/**
* @brief Output the jerry memory.
*
*/
void JerryMemTracing();
private:
/**
* @brief Default constructor.
*/
AceMemProc() = default;
/**
* @brief Default destructor.
*/
~AceMemProc() = default;
};
} // namespace ACELite
} // namespace OHOS
#endif // SIMULATOR_MEMORY_ANALYSIS
#endif // OHOS_ACELITE_MEM_PROC_H
+40
View File
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "memory_heap.h"
#include "ace_mem_base.h"
namespace OHOS {
namespace ACELite {
void *MemoryHeap::operator new(size_t size)
{
return ace_malloc(size);
}
void *MemoryHeap::operator new[](size_t size)
{
return ace_malloc(size);
}
void MemoryHeap::operator delete(void *p)
{
ace_free(p);
}
void MemoryHeap::operator delete[](void *p)
{
ace_free(p);
}
} // namespace ACELite
} // namespace OHOS
+43
View File
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_NON_COPYABLE_H
#define OHOS_ACELITE_NON_COPYABLE_H
namespace OHOS {
namespace ACELITE {
#define ACE_DISALLOW_COPY_AND_MOVE(className) \
ACE_DISALLOW_COPY(className); \
ACE_DISALLOW_MOVE(className)
#define ACE_DISALLOW_COPY(className) \
className(const className &) = delete; \
className &operator=(const className &) = delete
#define ACE_DISALLOW_MOVE(className) \
className(className &&) = delete; \
className &operator=(className &&) = delete
class NonCopyable {
protected:
NonCopyable() = default;
virtual ~NonCopyable() = default;
private:
ACE_DISALLOW_COPY_AND_MOVE(NonCopyable);
};
} // namespace ACELITE
} // namespace OHOS
#endif // OHOS_ACELITE_NON_COPYABLE_H
+58
View File
@@ -0,0 +1,58 @@
#Copyright (c) 2021 Huawei Device Co., Ltd.
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import("//build/lite/config/component/lite_component.gni")
ace_frameworks_root = "//foundation/ace/ace_engine_lite/frameworks"
ace_interface_root =
"//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin"
ace_target_root = "//foundation/ace/ace_engine_lite/frameworks/targets"
lite_component("ace_module_manager_lite") {
features = [ ":ace_module_manager" ]
}
shared_library("ace_module_manager") {
include_dirs = [
"$ace_frameworks_root/common/log",
"$ace_frameworks_root/common/utils",
"$ace_frameworks_root/include/base",
"$ace_frameworks_root/native_engine/jsi",
"$ace_interface_root/base",
"$ace_interface_root/jsi",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/jerryscript/jerry-core/include",
"//third_party/bounds_checking_function/include",
]
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "liteos_m") {
include_dirs += [ "$ace_target_root/liteos_a" ]
} else if (ohos_kernel_type == "linux") {
include_dirs += [ "$ace_target_root/linux" ]
}
cflags = [ "-Wall" ]
cflags_cc = cflags
sources = [ "$ace_frameworks_root/module_manager/module_manager.cpp" ]
public_deps = [
"$ace_frameworks_root/common:ace_common_lite",
"$ace_frameworks_root/native_engine:ace_native_engine_lite",
"${appexecfwk_lite_path}/interfaces/kits/bundle_lite/js/builtin:capability_api",
"//base/security/huks/frameworks/crypto_lite/js/builtin:ace_kit_cipher",
"//foundation/multimedia/media_lite/interfaces/kits/player_lite/js/builtin:audio_lite_api",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/jerryscript/jerry-core:jerry-core_shared",
"//utils/native/lite/js/builtin:ace_utils_kits",
]
}
@@ -0,0 +1,348 @@
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "module_manager.h"
#include <stdlib.h>
#include <string.h>
#include "acelite_config.h"
#include "securec.h"
#include "ace_log.h"
#include "internal/jsi_internal.h"
#include "ohos_module_config.h"
namespace OHOS {
namespace ACELite {
// Initialization of static variables
JSIValue ModuleManager::requiredSystemModules = 0;
JSIValue ModuleManager::RequireModule(const char * const moduleName)
{
char* category = nullptr;
char* name = nullptr;
if (!ParseModuleName(moduleName, &category, &name)) {
HILOG_ERROR(HILOG_MODULE_ACE, "ModuleManager::RequireModule: parse module name failed");
return JSI::CreateUndefined();
}
JSIValue moduleObj;
if (!strcmp(category, CATEGORY_SYSTEM)) {
uint16_t moduleCount = sizeof(OHOS_MODULES) / sizeof(Module);
moduleObj = GetModuleObject(name, OHOS_MODULES, moduleCount, requiredSystemModules);
#ifdef FEATURE_PRODUCT_MODULE
if ((JSI::ValueIsUndefined(moduleObj)) && (productModulesGetter_ != nullptr)) {
uint16_t prodModCount;
const Module* prodModules = productModulesGetter_(prodModCount);
moduleObj = GetModuleObject(name, prodModules, prodModCount, requiredSystemModules);
}
#endif // FEATURE_PRODUCT_MODULE
#ifdef FEATURE_PRIVATE_MODULE
if ((JSI::ValueIsUndefined(moduleObj)) && (privateModulesGetter_ != nullptr)) {
const char * const bundleName = (bundleNameGetter_ != nullptr) ? bundleNameGetter_() : nullptr;
moduleObj = GetModuleObject(name, nullptr, 0, requiredSystemModules, bundleName);
}
#endif // FEATURE_PRIVATE_MODULE
} else {
moduleObj = JSI::CreateUndefined();
HILOG_ERROR(HILOG_MODULE_ACE, "ModuleManager:RequireModule category %s does not exists!", category);
}
ace_free(category);
category = nullptr;
ace_free(name);
name = nullptr;
return moduleObj;
}
void ModuleManager::CleanUpModule()
{
if (requiredSystemModules != 0) {
JSI::ReleaseValue(requiredSystemModules);
requiredSystemModules = 0;
}
InvokeCallbacks(onDestroyHead_);
}
bool ModuleManager::ParseModuleName(const char * const moduleName, char** category, char** name) const
{
if ((moduleName == nullptr) || (category == nullptr) || (name == nullptr)) {
return false;
}
// Get moduleName str
char* str = nullptr;
if (!CreateString(moduleName, &str)) {
return false;
}
// Get category
char* next = nullptr;
char* tokenStr = strtok_s(str, ".", &next);
if (!CreateString(tokenStr, category)) {
ace_free(str);
str = nullptr;
return false;
}
// Get name
tokenStr = strtok_s(nullptr, ".", &next);
if (!CreateString(tokenStr, name)) {
ace_free(str);
str = nullptr;
ace_free(*category);
*category = nullptr;
return false;
}
ace_free(str);
str = nullptr;
tokenStr = nullptr;
next = nullptr;
return true;
}
bool ModuleManager::CreateString(const char * const srcStr, char** resPtr) const
{
if ((srcStr == nullptr) || (resPtr == nullptr)) {
return false;
}
size_t length = strlen(srcStr);
if (length >= UINT16_MAX) {
return false;
}
(*resPtr) = static_cast<char *>(ace_malloc(length + 1));
if ((*resPtr) == nullptr) {
return false;
}
if (memcpy_s((*resPtr), length, srcStr, length) != 0) {
ace_free(*resPtr);
*resPtr = nullptr;
return false;
}
(*resPtr)[length] = '\0';
return true;
}
JSIValue ModuleManager::GetModuleObject(const char * const moduleName, const Module* modules, uint16_t modulesCount,
JSIValue& categoryObj, const char * const bundleName)
{
if (moduleName == nullptr) {
return JSI::CreateUndefined();
}
if (bundleName == nullptr) {
if (modules == nullptr) {
return JSI::CreateUndefined();
}
for (uint16_t i = 0; i < modulesCount; i++) {
const char *regName = modules[i].name;
if ((regName != nullptr) && (strcmp(moduleName, regName) == 0)) {
return InitModuleObject(moduleName, modules[i], categoryObj);
}
}
}
#ifdef FEATURE_PRIVATE_MODULE
else {
uint16_t count;
const PrivateModule *privateModules =
(privateModulesGetter_ != nullptr) ? privateModulesGetter_(count) : nullptr;
if (privateModules == nullptr) {
return JSI::CreateUndefined();
}
for (uint16_t i = 0; i < count; i++) {
const char *regBundleName = privateModules[i].bundleName;
const char *regPrivateName = privateModules[i].module.name;
if ((regBundleName != nullptr) && (regPrivateName != nullptr) &&
(strcmp(bundleName, regBundleName) == 0) &&
(strcmp(moduleName, regPrivateName) == 0)) {
return InitModuleObject(moduleName, privateModules[i].module, categoryObj);
}
}
HILOG_WARN(HILOG_MODULE_ACE, "ModuleManager:module %s does not exists!", moduleName);
}
#endif
return JSI::CreateUndefined();
}
JSIValue ModuleManager::InitModuleObject(const char * const name, Module module, JSIValue& categoryObj)
{
if (categoryObj == 0) {
categoryObj = JSI::CreateObject();
}
// Get module object from cached object
JSIValue moduleObj = JSI::GetNamedProperty(categoryObj, name);
if (JSI::ValueIsUndefined(moduleObj)) {
JSIValue exports = JSI::CreateObject();
module.initFunc(exports);
// Get OnDestroy callback from module object
NativeCallback destroy = GetNativeCallback(exports, nullptr);
JsiCallback destroyHandler = GetJsiCallback(exports, ON_DESTROY_HANDLER);
InsertCallback(onDestroyHead_, destroy, destroyHandler);
// Insert OnTerminate callback to callback list
InsertTerminateCallback(name, exports);
// Set module object to cached object
JSI::SetNamedProperty(categoryObj, name, exports);
JSI::ReleaseValue(exports);
moduleObj = JSI::GetNamedProperty(categoryObj, name);
}
return moduleObj;
}
void ModuleManager::InsertTerminateCallback(const char * const name, const JSIValue& moduleObj)
{
if (name == nullptr) {
return;
}
// Determine if this callback has been inserted
CallbackNode *node = onTerminateHead_;
while (node != nullptr) {
if ((node->moduleName != nullptr) && (strcmp(name, node->moduleName) == 0)) {
return;
}
node = node->next;
}
// Get OnTerminate callback from module object
NativeCallback terminate = GetNativeCallback(moduleObj, ON_TERMINATE);
JsiCallback terminateHandler = GetJsiCallback(moduleObj, ON_TERMINATE_HANDLER);
InsertCallback(onTerminateHead_, terminate, terminateHandler, name);
}
void ModuleManager::OnTerminate()
{
InvokeCallbacks(onTerminateHead_);
}
void ModuleManager::InsertCallback(CallbackNode *&head, NativeCallback callback,
JsiCallback callbackHandler, const char * const moduleName) const
{
if ((callback == nullptr) && (callbackHandler == nullptr)) {
return;
}
auto node = new CallbackNode();
if (node == nullptr) {
return;
}
node->callback = callback;
node->callbackHandler = callbackHandler;
if (moduleName != nullptr) {
char *copiedName = nullptr;
if (CreateString(moduleName, &copiedName)) {
node->moduleName = copiedName;
}
}
if (head == nullptr) {
head = node;
} else {
node->next = head;
head = node;
}
}
void ModuleManager::InvokeCallbacks(CallbackNode *&head) const
{
CallbackNode *node = head;
while (node != nullptr) {
NativeCallback callback = node->callback;
JsiCallback callbackHandler = node->callbackHandler;
if (callback != nullptr) {
(*callback)();
}
if (callbackHandler != nullptr) {
(*callbackHandler)(JSI_ERR_OK);
}
head = node->next;
delete node;
node = head;
}
head = nullptr;
}
void* ModuleManager::GetObjectPointer(JSIValue object) const
{
if (!JSI::ValueIsObject(object)) {
return nullptr;
}
void *nativePtr = nullptr;
jerry_value_t jObj = AS_JERRY_VALUE(object);
bool exist = jerry_get_object_native_pointer(jObj, &nativePtr, nullptr);
if (!exist || (nativePtr == nullptr)) {
return nullptr;
}
jerry_delete_object_native_pointer(jObj, nullptr);
return nativePtr;
}
void* ModuleManager::GetObjectNamedPointer(JSIValue object, const char * const name) const
{
if (!JSI::ValueIsObject(object)) {
return nullptr;
}
JSIValue funObj = JSI::GetNamedProperty(object, name);
void *nativePtr = nullptr;
if (JSI::ValueIsObject(funObj)) {
nativePtr = GetObjectPointer(funObj);
DeleteObjectProperty(object, name);
}
JSI::ReleaseValue(funObj);
return nativePtr;
}
void ModuleManager::DeleteObjectProperty(JSIValue object, const char * const name) const
{
if (name == nullptr) {
return;
}
jerry_value_t jName = jerry_create_string(reinterpret_cast<const jerry_char_t *>(name));
jerry_delete_property(AS_JERRY_VALUE(object), jName);
jerry_release_value(jName);
}
NativeCallback ModuleManager::GetNativeCallback(JSIValue object, const char * const name) const
{
void *callback = nullptr;
if (name == nullptr) {
callback = GetObjectPointer(object);
} else {
callback = GetObjectNamedPointer(object, name);
}
return reinterpret_cast<NativeCallback>(callback);
}
JsiCallback ModuleManager::GetJsiCallback(JSIValue object, const char * const name) const
{
void *callback = GetObjectNamedPointer(object, name);
return reinterpret_cast<JsiCallback>(callback);
}
void ModuleManager::SetProductModulesGetter(ProductModulesGetter getter)
{
productModulesGetter_ = getter;
}
void ModuleManager::SetPrivateModulesGetter(PrivateModulesGetter getter)
{
privateModulesGetter_ = getter;
}
void ModuleManager::SetBundleNameGetter(BundleNameGetter getter)
{
bundleNameGetter_ = getter;
}
} // namespace ACELite
} // namespace OHOS
+173
View File
@@ -0,0 +1,173 @@
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_MODULE_MANAGER_H
#define OHOS_ACELITE_MODULE_MANAGER_H
#include "jsi.h"
#include "non_copyable.h"
#include "product_adapter.h"
namespace OHOS {
namespace ACELite {
/**
* Function pointer type used for getting current bundle name.
*/
typedef const char *(*BundleNameGetter)();
/**
* @brief module manager for module load.
*/
class ModuleManager final : public MemoryHeap {
public:
ACE_DISALLOW_COPY_AND_MOVE(ModuleManager);
/**
* @brief Get the single instance of ModuleManager
*
* @returns the instance.
*/
static ModuleManager* GetInstance()
{
static ModuleManager instance;
return &instance;
}
/**
* @brief: require javascript module object with given module name.
*
* @param: moduleName name of the module required
* @returns: javascript module object
*/
JSIValue RequireModule(const char * const moduleName);
/**
* @brief: Release module object created by RequireModule.
* This Method should be called when current js page is
* going to destroy
*/
void CleanUpModule();
/**
* @brief: Call OnTerminate callbacks of required modules.
* This Method should be called when current application is
* going to terminate
*/
void OnTerminate();
/**
* @brief: Set product modules getter hook.
*
* @param: the hook
*/
void SetProductModulesGetter(ProductModulesGetter getter);
/**
* @brief: Set private modules getter hook.
*
* @param: the hook
*/
void SetPrivateModulesGetter(PrivateModulesGetter getter);
/**
* @brief: Set bundle name getter hook.
*
* @param: the hook
*/
void SetBundleNameGetter(BundleNameGetter getter);
private:
struct CallbackNode : public MemoryHeap {
ACE_DISALLOW_COPY_AND_MOVE(CallbackNode);
CallbackNode() : moduleName(nullptr), callback(nullptr), callbackHandler(nullptr), next(nullptr) {}
~CallbackNode()
{
if (moduleName != nullptr) {
ace_free(moduleName);
moduleName = nullptr;
}
}
char *moduleName;
NativeCallback callback;
JsiCallback callbackHandler;
struct CallbackNode *next;
};
ModuleManager()
: onDestroyHead_(nullptr),
onTerminateHead_(nullptr),
productModulesGetter_(nullptr),
privateModulesGetter_(nullptr),
bundleNameGetter_(nullptr)
{
}
virtual ~ModuleManager() {}
/**
* @brief: get category and name with given moduleName.
*
* @param [in] moduleName module name passed from JS, e.g. system.vibrator
* @param [out] category pointer to category which this module belongs to
* Content should be freed with free() when it is not used anymore
* @param [out] name pointer to module name parsed from moduleName, e.g. vibrator
* Content should be freed with free() when it is not used anymore
* @return whether operation succeed
*/
bool ParseModuleName(const char * const moduleName, char** category, char** name) const;
/**
* @brief: get module object with given module name.
*
* @param [in] moduleName module name
* @param [in] modules array of module infos
* @param [in] modulesCount length of modules
* @param [inout] categoryObj pointer to static object, e.g. requiredSystemModules
* @param [in] bundleName bundle name of specific private module
* @return javascript required module object
*/
JSIValue GetModuleObject(const char * const moduleName, const Module* modules, uint16_t modulesCount,
JSIValue& categoryObj, const char * const bundleName = nullptr);
JSIValue InitModuleObject(const char * const name, Module module, JSIValue& categoryObj);
// *resPtr should be freed by caller when it's not nullptr and won't be used any more
bool CreateString(const char * const srcStr, char** resPtr) const;
void InsertCallback(CallbackNode *&head, NativeCallback callback,
JsiCallback callbackHandler, const char * const moduleName = nullptr) const;
void InsertTerminateCallback(const char * const name, const JSIValue& moduleObj);
void InvokeCallbacks(CallbackNode *&head) const;
void* GetObjectPointer(JSIValue object) const;
void* GetObjectNamedPointer(JSIValue object, const char * const name) const;
void DeleteObjectProperty(JSIValue object, const char * const name) const;
NativeCallback GetNativeCallback(JSIValue object, const char * const name) const;
JsiCallback GetJsiCallback(JSIValue object, const char * const name) const;
// For different native module type
const char* CATEGORY_SYSTEM = "system";
// JS object for caching modules
static JSIValue requiredSystemModules;
CallbackNode *onDestroyHead_;
CallbackNode *onTerminateHead_;
ProductModulesGetter productModulesGetter_;
PrivateModulesGetter privateModulesGetter_;
BundleNameGetter bundleNameGetter_;
};
} // namespace ACELite
} // namespace OHOS
#endif // OHOS_ACELITE_MODULE_MANAGER_H
@@ -0,0 +1,126 @@
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_OHOS_MODULE_CONFIG_H
#define OHOS_ACELITE_OHOS_MODULE_CONFIG_H
#include "acelite_config.h"
#include "jsi_types.h"
namespace OHOS {
namespace ACELite {
#ifdef ENABLE_MODULE_REQUIRE_TEST
extern void InitSampleModule(JSIValue exports);
#endif
extern void InitRouterModule(JSIValue exports);
extern void InitAppModule(JSIValue exports);
#ifdef FEATURE_MODULE_AUDIO
extern void InitAudioModule(JSIValue exports);
#endif // FEATURE_MODULE_AUDIO
#ifdef FEATURE_ACELITE_DFX_MODULE
extern void InitDfxModule(JSIValue exports);
#endif // FEATURE_ACELITE_DFX_MODULE
#ifdef ENABLE_MODULE_CIPHER
extern void InitCipherModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_DIALOG
extern void InitDialogModule(JSIValue exports);
#endif // FEATURE_MODULE_DIALOG
#ifdef FEATURE_MODULE_STORAGE
extern void InitNativeApiFs(JSIValue exports);
extern void InitNativeApiKv(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_DEVICE
extern void InitDeviceModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_GEO
extern void InitLocationModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_SENSOR
extern void InitVibratorModule(JSIValue exports);
extern void InitSensorModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_BRIGHTNESS
extern void InitBrightnessModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_BATTERY
extern void InitBatteryModule(JSIValue exports);
#endif
#ifdef FEATURE_MODULE_CONFIGURATION
extern void InitLocaleModule(JSIValue exports);
#endif
#ifdef FEATURE_ACELITE_SYSTEM_CAPABILITY
extern void InitCapabilityModule(JSIValue exports);
#endif
// Config information for built-in JS modules of OHOS platform
const Module OHOS_MODULES[] = {
#ifdef ENABLE_MODULE_REQUIRE_TEST
{"sample", InitSampleModule},
#endif
{"app", InitAppModule},
#ifdef FEATURE_MODULE_AUDIO
{"audio", InitAudioModule},
#endif // FEATURE_MODULE_AUDIO
#ifdef FEATURE_ACELITE_DFX_MODULE
{"dfx", InitDfxModule},
#endif // FEATURE_ACELITE_DFX_MODULE
{"router", InitRouterModule},
#ifdef ENABLE_MODULE_CIPHER
{"cipher", InitCipherModule},
#endif
#ifdef FEATURE_MODULE_DIALOG
{"prompt", InitDialogModule},
#endif // FEATURE_MODULE_DIALOG
#ifdef FEATURE_MODULE_STORAGE
{"file", InitNativeApiFs},
{"storage", InitNativeApiKv},
#endif
#ifdef FEATURE_MODULE_DEVICE
{"device", InitDeviceModule},
#endif
#ifdef FEATURE_MODULE_GEO
{"geolocation", InitLocationModule},
#endif
#ifdef FEATURE_MODULE_SENSOR
{"vibrator", InitVibratorModule},
{"sensor", InitSensorModule},
#endif
#ifdef FEATURE_MODULE_BRIGHTNESS
{"brightness", InitBrightnessModule},
#endif
#ifdef FEATURE_MODULE_BATTERY
{"battery", InitBatteryModule},
#endif
#ifdef FEATURE_MODULE_CONFIGURATION
{"configuration", InitLocaleModule},
#endif
#ifdef FEATURE_ACELITE_SYSTEM_CAPABILITY
{"capability", InitCapabilityModule},
#endif
};
} // namespace ACELite
} // namespace OHOS
#endif // OHOS_ACELITE_OHOS_MODULE_CONFIG_H
+55
View File
@@ -0,0 +1,55 @@
#Copyright (c) 2021 Huawei Device Co., Ltd.
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import("//build/lite/config/component/lite_component.gni")
ace_common_root = "//foundation/ace/ace_engine_lite/frameworks/common"
ace_interface_root =
"//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin"
ace_target_root = "//foundation/ace/ace_engine_lite/frameworks/targets"
native_engine_root = "//foundation/ace/ace_engine_lite/frameworks/native_engine"
lite_component("ace_native_engine_lite") {
features = [ ":ace_native_engine" ]
}
shared_library("ace_native_engine") {
include_dirs = [
"$ace_common_root/log",
"$ace_common_root/memory",
"$ace_interface_root/async",
"$ace_interface_root/base",
"$ace_interface_root/jsi",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/jerryscript/jerry-core/include",
]
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "liteos_m") {
include_dirs += [ "$ace_target_root/liteos_a" ]
} else if (ohos_kernel_type == "linux") {
include_dirs += [ "$ace_target_root/linux" ]
}
cflags = [ "-Wall" ]
cflags_cc = cflags
sources = [
"$native_engine_root/async/js_async_work.cpp",
"$native_engine_root/async/message_queue_utils.cpp",
"$native_engine_root/jsi/jsi.cpp",
]
public_deps = [
"$ace_common_root:ace_common_lite",
"//third_party/jerryscript/jerry-core:jerry-core_shared",
]
}
@@ -0,0 +1,134 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_async_work.h"
#include "ace_log.h"
namespace OHOS {
namespace ACELite {
// Initialization of static variables
QueueHandler JsAsyncWork::appQueuehandler_ = nullptr;
FatalHandleFunc JsAsyncWork::isFatalErrorHitted_ = nullptr;
FatalHandleFunc JsAsyncWork::isAppExiting_ = nullptr;
#if (defined(__LINUX__) || defined(__LITEOS_A__))
PostUITaskFunc JsAsyncWork::postUITask_ = nullptr;
#endif
void JsAsyncWork::SetAppQueueHandler(const QueueHandler handler)
{
appQueuehandler_ = handler;
}
bool JsAsyncWork::DispatchToLoop(AbilityMsgId msgId, void *data)
{
if ((appQueuehandler_ == nullptr) || (msgId >= MSG_ID_MAX) ||
(isFatalErrorHitted_ != nullptr && isFatalErrorHitted_()) ||
(isAppExiting_ != nullptr && isAppExiting_())) {
// For the cases fatal error handling or the JS task is exiting, do not allow any async work dispatching,
// as the messages after DESTROY will never be handled.
return false;
}
AbilityInnerMsg innerMsg;
innerMsg.msgId = msgId;
innerMsg.data = data;
int8_t ret = MessageQueueUtils::PutMessage(appQueuehandler_, static_cast<void *>(&innerMsg), 0);
return (ret == MSGQ_OK);
}
bool JsAsyncWork::DispatchAsyncWork(AsyncWorkHandler workHandler, void *data)
{
return DispatchAsyncWorkInner(workHandler, nullptr, data);
}
bool JsAsyncWork::DispatchAsyncWork(AsyncHandler handler, void *data)
{
return DispatchAsyncWorkInner(nullptr, handler, data);
}
bool JsAsyncWork::DispatchAsyncWorkInner(AsyncWorkHandler workHandler, AsyncHandler handler, void *data)
{
if (((workHandler == nullptr) && (handler == nullptr)) ||
(isFatalErrorHitted_ != nullptr && isFatalErrorHitted_())) {
HILOG_ERROR(HILOG_MODULE_ACE, "JsAsyncWork:DispatchAsyncWork parameters invalid or fatal error!");
return false;
}
#if (defined(__LINUX__) || defined(__LITEOS_A__))
if ((workHandler != nullptr) && (postUITask_ != nullptr)) {
auto task1 = [workHandler, data]() {
workHandler(data);
};
return postUITask_(task1);
}
if ((handler != nullptr) && (postUITask_ != nullptr)) {
auto task2 = [handler, data]() {
handler(data, ERR_OK);
};
return postUITask_(task2);
}
return false;
#else
AsyncWork* asyncWork = new AsyncWork();
if (asyncWork == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "JsAsyncWork:DispatchAsyncWork create async work failed!");
return false;
}
asyncWork->workHandler = workHandler;
asyncWork->handler = handler;
asyncWork->data = data;
bool ret = DispatchToLoop(ASYNCWORK, static_cast<void *>(asyncWork));
if (!ret) {
HILOG_ERROR(HILOG_MODULE_ACE, "JsAsyncWork:DispatchAsyncWork failed!, handler[%{private}p]",
asyncWork->workHandler);
delete(asyncWork);
asyncWork = nullptr;
}
return ret;
#endif
}
void JsAsyncWork::ExecuteAsyncWork(AsyncWork *&asyncWork, int8_t statusCode)
{
if (asyncWork == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "JsAsyncWork:ExecuteAsyncWork parameters invalid!");
return;
}
AsyncWorkHandler workHandler = asyncWork->workHandler;
if (workHandler != nullptr) {
workHandler(asyncWork->data);
}
AsyncHandler handler = asyncWork->handler;
if (handler != nullptr) {
handler(asyncWork->data, statusCode);
}
delete asyncWork;
asyncWork = nullptr;
}
void JsAsyncWork::SetFatalHandleFunc(FatalHandleFunc isFatalErrorHitted, FatalHandleFunc isAppExiting)
{
isFatalErrorHitted_ = isFatalErrorHitted;
isAppExiting_ = isAppExiting;
}
#if (defined(__LINUX__) || defined(__LITEOS_A__))
void JsAsyncWork::SetPostUITaskFunc(PostUITaskFunc postUITask)
{
postUITask_ = postUITask;
}
#endif
} // namespace ACELite
} // namespace OHOS
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "message_queue_utils.h"
#include "ace_log.h"
#include "acelite_config.h"
#ifdef OHOS_ACELITE_PRODUCT_WATCH
#include "cmsis_os2.h"
#endif
namespace OHOS {
namespace ACELite {
QueueHandler MessageQueueUtils::CreateMessageQueue(uint32_t capacity, uint32_t msgSize)
{
if (capacity == 0 || msgSize == 0) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:CreateMessageQueue parameters invalid!");
return nullptr;
}
#if (defined(__LINUX__) || defined(__LITEOS__))
HILOG_WARN(HILOG_MODULE_ACE, "todo call linux createMessageQueue interface here!");
return nullptr;
#else
osMessageQueueId_t queueId = osMessageQueueNew(capacity, msgSize, nullptr);
return static_cast<QueueHandler>(queueId);
#endif
}
int8_t MessageQueueUtils::DeleteMessageQueue(QueueHandler handler)
{
if (handler == nullptr) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:DeleteMessageQueue parameters invalid!");
return MSGQ_FAIL;
}
#if (defined(__LINUX__) || defined(__LITEOS__))
HILOG_WARN(HILOG_MODULE_ACE, "todo call linux deleteMessageQueue interface here!");
return MSGQ_FAIL;
#else
osMessageQueueId_t queueId = static_cast<osMessageQueueId_t>(handler);
if (osMessageQueueDelete(queueId) != osOK) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:DeleteMessageQueue failed!");
return MSGQ_FAIL;
}
return MSGQ_OK;
#endif
}
int8_t MessageQueueUtils::PutMessage(QueueHandler handler, const void* msgPtr, uint32_t timeOut)
{
if ((handler == nullptr) || (msgPtr == nullptr)) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:PutMessage parameters invalid!");
return MSGQ_FAIL;
}
#if (defined(__LINUX__) || defined(__LITEOS__))
HILOG_WARN(HILOG_MODULE_ACE, "todo call linux putmsg interface here!");
return MSGQ_FAIL;
#else
osMessageQueueId_t queueId = static_cast<osMessageQueueId_t>(handler);
if (osMessageQueuePut(queueId, msgPtr, 0, timeOut) != osOK) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:PutMessage failed!");
return MSGQ_FAIL;
}
return MSGQ_OK;
#endif
}
int8_t MessageQueueUtils::GetMessage(QueueHandler handler, void* msgPtr, uint32_t timeOut)
{
if ((handler == nullptr) || (msgPtr == nullptr)) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:GetMessage parameters invalid!");
return MSGQ_FAIL;
}
#if (defined(__LINUX__) || defined(__LITEOS__))
HILOG_WARN(HILOG_MODULE_ACE, "todo call linux getmsg interface here!");
return MSGQ_FAIL;
#else
osMessageQueueId_t queueId = static_cast<osMessageQueueId_t>(handler);
if (osMessageQueueGet(queueId, msgPtr, 0, timeOut) != osOK) {
HILOG_ERROR(HILOG_MODULE_ACE, "MessageQueueUtils:GetMessage failed!");
return MSGQ_FAIL;
}
return MSGQ_OK;
#endif
}
} // namespace ACELite
} // namespace OHOS
@@ -0,0 +1,33 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_JSI_CONFIG_H
#define OHOS_ACELITE_JSI_CONFIG_H
/*
* Usage:
* #if DISABLED(LOG_OUTPUT)
* #if ENABLED(LOG_OUTPUT)
*/
#define ENABLED(CONFIGURATION) ((CONFIGURATION) == 1)
#define DISABLED(CONFIGURATION) ((CONFIGURATION) != 1)
/**
* JS engine macro for engine adapter layer.
*/
#ifndef ENABLE_JERRY
#define ENABLE_JERRY 1
#endif
#endif // OHOS_ACELITE_JSI_CONFIG_H
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_ACELITE_JSI_INTERNAL_H
#define OHOS_ACELITE_JSI_INTERNAL_H
#include "jsi_config.h"
#if defined(ENABLE_JERRY)
#include "jerryscript.h"
#endif
/**
* Macros for conversions between jsi-values and jerry-values.
*/
#if defined (ENABLE_JERRY)
#define AS_JERRY_VALUE(jsiValue) (jerry_value_t)(uintptr_t) jsiValue
#define AS_JLENGTH_VALUE(jsiValue) (jerry_length_t)(uintptr_t) jsiValue
#define AS_JSI_VALUE(jValue) (JSIValue)(uintptr_t) jValue
#endif
/**
* A convenience macro to create jerry-values.
*/
#if defined (ENABLE_JERRY)
#define JERRY_CREATE(var, create) jerry_value_t var = (create);
#endif
/**
* Key words for native module callbacks.
*/
constexpr char ON_TERMINATE[] = "onTerminate";
constexpr char ON_DESTROY_HANDLER[] = "onDestroyHandler";
constexpr char ON_TERMINATE_HANDLER[] = "onTerminateHandler";
#endif // OHOS_ACELITE_JSI_INTERNAL_H
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
#Copyright (c) 2021 Huawei Device Co., Ltd.
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import("//build/lite/config/test.gni")
import("//foundation/ace/ace_engine_lite/test/ace_test_config.gni")
unittest("js_frameworks_test_jsiinterface") {
output_extension = "bin"
output_dir = test_output_root
configs = [ "$ace_lite_root/test:test_common_config" ]
sources = [ "common/jsi_interface_tdd_test.cpp" ]
deps = ace_test_deps
}
group("jsi_unittest") {
deps = [ ":js_frameworks_test_jsiinterface" ]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ACELITE_JSI_INTERFACE_TDD_TEST_H
#define ACELITE_JSI_INTERFACE_TDD_TEST_H
#ifdef TDD_ASSERTIONS
#include <climits>
#include <gtest/gtest.h>
#endif
#include "acelite_config.h"
#include "jerryscript.h"
#include "js_config.h"
#include "jsi.h"
#include "test_common.h"
namespace OHOS {
namespace ACELite {
#ifdef TDD_ASSERTIONS
using namespace std;
using namespace testing::ext;
class JsiInterfaceTddTest : public testing::Test {
#else
class JsiInterfaceTddTest {
#endif
public:
JsiInterfaceTddTest();
~JsiInterfaceTddTest(){};
void SetUp();
void TearDown();
static void OnDestroy(int8_t statusCode);
static void OnTerminate(int8_t statusCode);
static JSIValue Setter(const JSIValue thisVal, const JSIValue args[], uint8_t argsNum);
static JSIValue Getter(const JSIValue thisVal, const JSIValue args[], uint8_t argsNum);
static JSIValue Function(const JSIValue thisVal, const JSIValue args[], uint8_t argsNum);
void JSIInterfaceTest001();
void JSIInterfaceTest002();
void JSIInterfaceTest003();
void JSIInterfaceTest004();
void JSIInterfaceTest005();
void JSIInterfaceTest006();
void JSIInterfaceTest007();
void JSIInterfaceTest008();
void JSIInterfaceTest009();
void JSIInterfaceTest010();
#if ENABLED(JS_FWK_SYMBOL)
void JSIInterfaceTest011();
#endif // ENABLED(JS_FWK_SYMBOL)
void JSIInterfaceTest012();
void JSIInterfaceTest013();
void JSIInterfaceTest014();
void JSIInterfaceTest015();
void JSIInterfaceTest016();
void JSIInterfaceTest017();
#if ENABLED(JS_FWK_TYPEDARRAY)
void JSIInterfaceTest018();
void JSIInterfaceTest019();
#endif // ENABLED(JS_FWK_TYPEDARRAY)
void JSIInterfaceTest020();
void JSIInterfaceTest021();
void JSIInterfaceTest022();
void JSIInterfaceTest023();
void RunTests();
};
} // namespace ACELite
} // namespace OHOS
#endif // ACELITE_JSI_INTERFACE_TDD_TEST_H
+27 -13
View File
@@ -14,16 +14,16 @@
*/
#include "js_async_work.h"
#include "ace_log.h"
#include "fatal_handler.h"
#include "js_fwk_common.h"
#if (defined(__LINUX__) || defined(__LITEOS__))
#include "ace_ability.h"
#endif
namespace OHOS {
namespace ACELite {
// Initialization of static variables
QueueHandler JsAsyncWork::appQueuehandler_ = nullptr;
FatalHandleFunc JsAsyncWork::isFatalErrorHitted_ = nullptr;
FatalHandleFunc JsAsyncWork::isAppExiting_ = nullptr;
#if (defined(__LINUX__) || defined(__LITEOS_A__))
PostUITaskFunc JsAsyncWork::postUITask_ = nullptr;
#endif
void JsAsyncWork::SetAppQueueHandler(const QueueHandler handler)
{
@@ -33,8 +33,8 @@ void JsAsyncWork::SetAppQueueHandler(const QueueHandler handler)
bool JsAsyncWork::DispatchToLoop(AbilityMsgId msgId, void *data)
{
if ((appQueuehandler_ == nullptr) || (msgId >= MSG_ID_MAX) ||
(FatalHandler::GetInstance().IsFatalErrorHitted()) ||
(FatalHandler::GetInstance().IsAppExiting())) {
(isFatalErrorHitted_ != nullptr && isFatalErrorHitted_()) ||
(isAppExiting_ != nullptr && isAppExiting_())) {
// For the cases fatal error handling or the JS task is exiting, do not allow any async work dispatching,
// as the messages after DESTROY will never be handled.
return false;
@@ -59,23 +59,24 @@ bool JsAsyncWork::DispatchAsyncWork(AsyncHandler handler, void *data)
bool JsAsyncWork::DispatchAsyncWorkInner(AsyncWorkHandler workHandler, AsyncHandler handler, void *data)
{
if (((workHandler == nullptr) && (handler == nullptr)) || (FatalHandler::GetInstance().IsFatalErrorHitted())) {
if (((workHandler == nullptr) && (handler == nullptr)) ||
(isFatalErrorHitted_ != nullptr && isFatalErrorHitted_())) {
HILOG_ERROR(HILOG_MODULE_ACE, "JsAsyncWork:DispatchAsyncWork parameters invalid or fatal error!");
return false;
}
#if (defined(__LINUX__) || defined(__LITEOS__))
if (workHandler != nullptr) {
#if (defined(__LINUX__) || defined(__LITEOS_A__))
if ((workHandler != nullptr) && (postUITask_ != nullptr)) {
auto task1 = [workHandler, data]() {
workHandler(data);
};
return AceAbility::PostUITask(task1);
return postUITask_(task1);
}
if (handler != nullptr) {
if ((handler != nullptr) && (postUITask_ != nullptr)) {
auto task2 = [handler, data]() {
handler(data, ERR_OK);
};
return AceAbility::PostUITask(task2);
return postUITask_(task2);
}
return false;
#else
@@ -116,5 +117,18 @@ void JsAsyncWork::ExecuteAsyncWork(AsyncWork *&asyncWork, int8_t statusCode)
delete asyncWork;
asyncWork = nullptr;
}
void JsAsyncWork::SetFatalHandleFunc(FatalHandleFunc isFatalErrorHitted, FatalHandleFunc isAppExiting)
{
isFatalErrorHitted_ = isFatalErrorHitted;
isAppExiting_ = isAppExiting;
}
#if (defined(__LINUX__) || defined(__LITEOS_A__))
void JsAsyncWork::SetPostUITaskFunc(PostUITaskFunc postUITask)
{
postUITask_ = postUITask;
}
#endif
} // namespace ACELite
} // namespace OHOS
@@ -40,6 +40,16 @@ FatalHandler &FatalHandler::GetInstance()
return instance;
}
bool FatalHandler::IsErrorHittedWrapper()
{
return FatalHandler::GetInstance().IsFatalErrorHitted();
}
bool FatalHandler::IsAppExitingWrapper()
{
return FatalHandler::GetInstance().IsAppExiting();
}
static void HandleFatal(int errorCode)
{
#ifdef FEATURE_FATAL_ERROR_HANDLING
@@ -28,6 +28,8 @@ class FatalHandler final : public MemoryHeap {
public:
ACE_DISALLOW_COPY_AND_MOVE(FatalHandler);
static FatalHandler& GetInstance();
static bool IsErrorHittedWrapper();
static bool IsAppExitingWrapper();
const char* GetErrorStr(int errorCode) const;
void RegisterFatalHandler(JSAbility *ability);
void SetFatalError(int errorCode);
@@ -28,6 +28,10 @@
#include "js_async_work.h"
#include "js_profiler.h"
#include "product_adapter.h"
#if (defined(__LINUX__) || defined(__LITEOS_A__))
#include "ace_ability.h"
#endif
#include "module_manager.h"
namespace OHOS {
namespace ACELite {
@@ -73,6 +77,13 @@ void JSAbility::Launch(const char * const abilityPath, const char * const bundle
return;
}
#ifndef MOCK_JS_ASYNC_WORK
JsAsyncWork::SetFatalHandleFunc(FatalHandler::IsErrorHittedWrapper, FatalHandler::IsAppExitingWrapper);
#endif
#if (defined(__LINUX__) || defined(__LITEOS_A__))
JsAsyncWork::SetPostUITaskFunc(AceAbility::PostUITask);
#endif
ModuleManager::GetInstance()->SetBundleNameGetter(JSAbility::GetPackageName);
DumpNativeMemoryUsage();
jsAbilityImpl_ = new JSAbilityImpl();
if (jsAbilityImpl_ == nullptr) {
@@ -344,5 +344,10 @@ void ModuleManager::SetPrivateModulesGetter(PrivateModulesGetter getter)
{
privateModulesGetter_ = getter;
}
void ModuleManager::SetBundleNameGetter(BundleNameGetter getter)
{
bundleNameGetter_ = getter;
}
} // namespace ACELite
} // namespace OHOS
+16 -1
View File
@@ -22,6 +22,11 @@
namespace OHOS {
namespace ACELite {
/**
* Function pointer type used for getting current bundle name.
*/
typedef const char *(*BundleNameGetter)();
/**
* @brief module manager for module load.
*/
@@ -67,6 +72,7 @@ public:
* @param: the hook
*/
void SetProductModulesGetter(ProductModulesGetter getter);
/**
* @brief: Set private modules getter hook.
*
@@ -74,6 +80,13 @@ public:
*/
void SetPrivateModulesGetter(PrivateModulesGetter getter);
/**
* @brief: Set bundle name getter hook.
*
* @param: the hook
*/
void SetBundleNameGetter(BundleNameGetter getter);
private:
struct CallbackNode : public MemoryHeap {
ACE_DISALLOW_COPY_AND_MOVE(CallbackNode);
@@ -96,7 +109,8 @@ private:
: onDestroyHead_(nullptr),
onTerminateHead_(nullptr),
productModulesGetter_(nullptr),
privateModulesGetter_(nullptr)
privateModulesGetter_(nullptr),
bundleNameGetter_(nullptr)
{
}
virtual ~ModuleManager() {}
@@ -151,6 +165,7 @@ private:
CallbackNode *onTerminateHead_;
ProductModulesGetter productModulesGetter_;
PrivateModulesGetter privateModulesGetter_;
BundleNameGetter bundleNameGetter_;
};
} // namespace ACELite
} // namespace OHOS
+11 -5
View File
@@ -29,12 +29,17 @@ config("ace_lite_config") {
ohos_static_library("ace_lite") {
public_configs = [ ":ace_lite_config" ]
sources = ace_lite_sources
sources += [ "//foundation/ace/ace_engine_lite/frameworks/src/core/modules/presets/feature_ability_module.cpp" ]
sources -= [
"//foundation/ace/ace_engine_lite/frameworks/src/core/async/js_async_work.cpp",
"//foundation/ace/ace_engine_lite/frameworks/src/core/async/message_queue_utils.cpp",
"//foundation/ace/ace_engine_lite/frameworks/src/core/context/ace_ability.cpp",
sources += [
"$ACE_LITE_COMMON_PATH/log/ace_log.cpp",
"$ACE_LITE_COMMON_PATH/memory/ace_mem_base.cpp",
"$ACE_LITE_COMMON_PATH/memory/cache/cache_manager.cpp",
"$ACE_LITE_COMMON_PATH/memory/mem_proc.cpp",
"$ACE_LITE_COMMON_PATH/memory/memory_heap.cpp",
"$MODULE_MANAGER_PATH/module_manager.cpp",
"$NATIVE_ENGINE_PATH/jsi/jsi.cpp",
"//foundation/ace/ace_engine_lite/frameworks/src/core/modules/presets/feature_ability_module.cpp",
]
sources -= [ "//foundation/ace/ace_engine_lite/frameworks/src/core/context/ace_ability.cpp" ]
cflags_cc = [
"-Wall",
"-D_INC_STRING_S",
@@ -55,6 +60,7 @@ ohos_static_library("ace_lite") {
"TARGET_SIMULATOR",
"JS_ENGINE_EXTERNAL_CONTEXT",
"SCREENSIZE_SPECIFIED",
"MOCK_JS_ASYNC_WORK",
]
if (is_debug == "debug") {
defines += [ "JS_PROFILER=1" ]
+19 -11
View File
@@ -37,16 +37,19 @@ LOSCFG_TEST_JS_BUILD {
ROOT_PATH = ../../../../../../../..
ACELITE_FRAMEWORK_PATH = ../../../..
ACELITE_CORE_PATH = $${ACELITE_FRAMEWORK_PATH}/src/core
ACELITE_COMMON_PATH = $${ACELITE_FRAMEWORK_PATH}/common
ACELITE_NATIVE_ENGINE_PATH = $${ACELITE_FRAMEWORK_PATH}/native_engine
ACELITE_MODULE_MANAGER_PATH = $${ACELITE_FRAMEWORK_PATH}/module_manager
SOURCES += \
$${ACELITE_CORE_PATH}/animation/transition_impl.cpp \
$${ACELITE_CORE_PATH}/async/js_async_work.cpp \
#$${ACELITE_CORE_PATH}/async/message_queue_utils.cpp \
$${ACELITE_CORE_PATH}/base/ace_log.cpp \
$${ACELITE_CORE_PATH}/base/ace_mem_base.cpp \
$${ACELITE_NATIVE_ENGINE_PATH}/async/js_async_work.cpp \
#$${ACELITE_NATIVE_ENGINE_PATH}/async/message_queue_utils.cpp \
$${ACELITE_COMMON_PATH}/log/ace_log.cpp \
$${ACELITE_COMMON_PATH}/memory/ace_mem_base.cpp \
$${ACELITE_CORE_PATH}/base/dft_impl.cpp \
$${ACELITE_CORE_PATH}/base/async_task_manager.cpp \
$${ACELITE_CORE_PATH}/base/cache/cache_manager.cpp \
$${ACELITE_COMMON_PATH}/memory/cache/cache_manager.cpp \
$${ACELITE_CORE_PATH}/base/dfx_assist.cpp \
$${ACELITE_CORE_PATH}/base/event_util.cpp \
$${ACELITE_CORE_PATH}/base/js_debugger_config.cpp \
@@ -55,8 +58,8 @@ SOURCES += \
$${ACELITE_CORE_PATH}/base/lazy_load_manager.cpp \
$${ACELITE_CORE_PATH}/base/lazy_load_watcher.cpp \
$${ACELITE_CORE_PATH}/base/locale_util.cpp \
$${ACELITE_CORE_PATH}/base/mem_proc.cpp \
$${ACELITE_CORE_PATH}/base/memory_heap.cpp \
$${ACELITE_COMMON_PATH}/memory/mem_proc.cpp \
$${ACELITE_COMMON_PATH}/memory/memory_heap.cpp \
$${ACELITE_CORE_PATH}/base/number_parser.cpp \
$${ACELITE_CORE_PATH}/base/product_adapter.cpp \
$${ACELITE_CORE_PATH}/base/string_util.cpp \
@@ -107,11 +110,11 @@ SOURCES += \
$${ACELITE_CORE_PATH}/dialog/js_dialog.cpp \
$${ACELITE_CORE_PATH}/directive/descriptor_utils.cpp \
$${ACELITE_CORE_PATH}/directive/directive_watcher_callback.cpp \
$${ACELITE_CORE_PATH}/jsi/jsi.cpp \
$${ACELITE_NATIVE_ENGINE_PATH}/jsi/jsi.cpp \
$${ACELITE_CORE_PATH}/modules/app_module.cpp \
$${ACELITE_CORE_PATH}/modules/dfx_module.cpp \
$${ACELITE_CORE_PATH}/modules/dialog_module.cpp \
$${ACELITE_CORE_PATH}/modules/module_manager.cpp \
$${ACELITE_MODULE_MANAGER_PATH}/module_manager.cpp \
$${ACELITE_CORE_PATH}/modules/presets/cjson_parser.cpp \
$${ACELITE_CORE_PATH}/modules/presets/console_log_impl.cpp \
$${ACELITE_CORE_PATH}/modules/presets/console_module.cpp \
@@ -191,13 +194,18 @@ INCLUDEPATH += \
$${ACELITE_CORE_PATH} \
$${ACELITE_CORE_PATH}/animation \
$${ACELITE_CORE_PATH}/base \
$${ACELITE_CORE_PATH}/base/cache \
$${ACELITE_COMMON_PATH}/log \
$${ACELITE_COMMON_PATH}/memory \
$${ACELITE_COMMON_PATH}/memory/cache \
$${ACELITE_COMMON_PATH}/utils \
$${ACELITE_CORE_PATH}/components \
$${ACELITE_CORE_PATH}/context \
$${ACELITE_CORE_PATH}/directive \
$${ACELITE_CORE_PATH}/router \
$${ACELITE_CORE_PATH}/jsi \
$${ACELITE_NATIVE_ENGINE_PATH} \
$${ACELITE_NATIVE_ENGINE_PATH}/jsi \
$${ACELITE_CORE_PATH}/modules \
$${ACELITE_MODULE_MANAGER_PATH} \
$${ACELITE_CORE_PATH}/router \
$${ACELITE_CORE_PATH}/stylemgr \
$${ACELITE_CORE_PATH}/wrapper \
@@ -18,6 +18,9 @@
#include "message_queue_utils.h"
#include "memory_heap.h"
#if (defined(__LINUX__) || defined(__LITEOS_A__))
#include <functional>
#endif
namespace OHOS {
namespace ACELite {
@@ -32,6 +35,12 @@ typedef void (*AsyncWorkHandler)(void* data);
*/
typedef void (*AsyncHandler)(void* data, int8_t statusCode);
typedef bool (*FatalHandleFunc)();
#if (defined(__LINUX__) || defined(__LITEOS_A__))
typedef bool (*PostUITaskFunc)(std::function<void()> task);
#endif
struct AsyncWork : public MemoryHeap {
AsyncWorkHandler workHandler;
AsyncHandler handler;
@@ -103,6 +112,12 @@ public:
*/
static void ExecuteAsyncWork(AsyncWork *&asyncWork, int8_t statusCode = ERR_OK);
static void SetFatalHandleFunc(FatalHandleFunc isFatalErrorHitted, FatalHandleFunc isAppExiting);
#if (defined(__LINUX__) || defined(__LITEOS_A__))
static void SetPostUITaskFunc(PostUITaskFunc postUITask);
#endif
// Error code used for async work processing
static const int8_t ERR_OK = 0;
static const int8_t ERR_FAIL = -1;
@@ -110,6 +125,11 @@ public:
private:
static bool DispatchAsyncWorkInner(AsyncWorkHandler workHandler, AsyncHandler handler, void *data);
static QueueHandler appQueuehandler_;
static FatalHandleFunc isFatalErrorHitted_;
static FatalHandleFunc isAppExiting_;
#if (defined(__LINUX__) || defined(__LITEOS_A__))
static PostUITaskFunc postUITask_;
#endif
};
} // namespace ACELite
} // namespace OHOS
+2 -3
View File
@@ -14,13 +14,12 @@
import("//build/lite/config/test.gni")
import("//foundation/ace/ace_engine_lite/test/ace_test_config.gni")
cache_manager_unittest_root =
"$ace_lite_root/frameworks/src/core/base/cache/test/unittest"
cache_manager_unittest_root = "$ACE_LITE_COMMON_PATH/memory/cache/test/unittest"
components_unittest_root =
"$ace_lite_root/frameworks/src/core/components/test/unittest"
context_unittest_root =
"$ace_lite_root/frameworks/src/core/context/test/unittest"
jsi_unittest_root = "$ace_lite_root/frameworks/src/core/jsi/test/unittest"
jsi_unittest_root = "$NATIVE_ENGINE_PATH/jsi/test/unittest"
modules_unittest_root =
"$ace_lite_root/frameworks/src/core/modules/test/unittest"
stylemgr_unittest_root =
+3 -2
View File
@@ -51,13 +51,11 @@ ace_test_includes = [
"$ace_lite_root/frameworks/src/core",
"$ace_lite_root/frameworks/src/core/animation",
"$ace_lite_root/frameworks/src/core/base",
"$ace_lite_root/frameworks/src/core/base/cache",
"$ace_lite_root/frameworks/src/core/components",
"$ace_lite_root/frameworks/src/core/components/test/unittest/common",
"$ace_lite_root/frameworks/src/core/context",
"$ace_lite_root/frameworks/src/core/directive",
"$ace_lite_root/frameworks/src/core/router",
"$ace_lite_root/frameworks/src/core/jsi",
"$ace_lite_root/frameworks/src/core/modules",
"$ace_lite_root/frameworks/src/core/modules/presets",
"$ace_lite_root/frameworks/src/core/router",
@@ -74,6 +72,9 @@ ace_test_defines = [
]
ace_test_deps = [
"$ACE_LITE_COMMON_PATH:ace_common_lite",
"$MODULE_MANAGER_PATH:ace_module_manager_lite",
"$NATIVE_ENGINE_PATH:ace_native_engine_lite",
"${aafwk_lite_path}/frameworks/ability_lite:aafwk_abilitykit_lite",
"${appexecfwk_lite_path}/frameworks/bundle_lite:bundle",
"//foundation/ace/ace_engine_lite/frameworks:ace_lite",
+3 -3
View File
@@ -24,16 +24,17 @@ unittest("js_frameworks_tdd_door") {
]
sources = all_acelite_source_files
sources += [
"$ACE_LITE_COMMON_PATH/memory/cache/test/unittest/common/cache_manager_tdd_test.cpp",
"$NATIVE_ENGINE_PATH/jsi/test/unittest/common/jsi_interface_tdd_test.cpp",
"$ace_lite_root/frameworks/src/core/components/test/unittest/common/root_component_mock.cpp",
"$ace_lite_root/test/moduletest/common/base_test.cpp",
"$ace_lite_root/test/moduletest/common/basic_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/list_tdd_test.cpp",
"$ace_lite_src_core/base/cache/test/unittest/common/cache_manager_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/arc_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/div_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/horizonprogress_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/image_src_path_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/jsbundle_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/list_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/marquee_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/opacity_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/percent_tdd_test.cpp",
@@ -42,7 +43,6 @@ unittest("js_frameworks_tdd_door") {
"$ace_lite_src_core/components/test/unittest/common/switch_tdd_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/text_tdd_exception_test.cpp",
"$ace_lite_src_core/components/test/unittest/common/text_tdd_test.cpp",
"$ace_lite_src_core/jsi/test/unittest/common/jsi_interface_tdd_test.cpp",
"$ace_lite_src_core/modules/presets/test/unittest/common/console_module_test.cpp",
"$ace_lite_src_core/modules/presets/test/unittest/common/date_time_module_tdd_test.cpp",
"$ace_lite_src_core/modules/presets/test/unittest/common/number_format_module_tdd_test.cpp",