资源调优和资源泄漏是应用开发中常见且难以快速解决的两类问题。在HarmonyOS应用开发过程中,这些问题通常难以利用常规调试手段(如hilog流水日志、/proc/[pid]/smaps、/proc/meminfo、/proc/memview、hidumper --mem [pid])直接定位和处理。
为快速解决上述两类痛点问题,HarmonyOS通过Performance Analysis Kit开放的HiDebug资源采集接口(OH_HiDebug_StartProfiler()/OH_HiDebug_StopProfiler()),提供线上资源分配栈采集功能,帮助开发者高效实现问题的自诊断与自闭环。
本文将介绍以下内容:
为帮助开发人员快速定位进程内的资源泄漏问题,HarmonyOS提供了HiDebug资源采集能力(OH_HiDebug_StartProfiler())。开发者可调用OH_HiDebug_StartProfiler()/OH_HiDebug_StopProfiler()接口,针对指定资源类型启动采集,系统在采集窗口内记录资源分配的调用栈与统计信息,并将结果输出为.htrace文件。
受采集规格约束限制,本API不保证采集请求一定成功。调用本API会对当前应用进程及整机性能功耗产生影响,包括但不限于CPU、内存占用升高,丢帧卡顿、发热。集成时必须谨慎评估性能功耗开销,建立严格的条件触发策略(如仅在特定灰度范围内、应用资源超基线阈值时触发,并配置合理的采集参数以兼顾性能功耗平衡)后再决策是否开启。严禁在生产环境下盲目或高频次触发。
开发者可将生成的.htrace文件导入DevEco Studio中Profiler工具进行关联分析,按调用栈分组统计,频率最高的调用栈即为泄漏嫌疑点,从而加速定位泄漏代码位置,降低定界定位成本。
OH_HiDebug_StartProfiler()支持以下资源类型:
类型枚举 | 值 | 资源类型 | 资源创建方式 |
|---|---|---|---|
OH_RES_TYPE_FD | 0 | 文件描述符(FD) | 通过open/fopen、epoll、eventfd、socket、pipe、dup等创建的文件描述符。 |
OH_RES_TYPE_THREAD | 1 | 线程 | 通过线程函数创建的线程(如pthread_create)。 |
OH_RES_TYPE_NATIVE | 2 | Native内存(包含堆内存和映射区内存) | 通过malloc/calloc/realloc/new分配的堆内存(NativeHeap); 通过mmap映射的映射区内存(包含so等文件映射以及匿名映射)。 |
OH_RES_TYPE_GPU | 3 | GPU内存 | 通过图形标准API(如opengles、vulkan、opencl)创建的纹理(texture)、缓冲区(buffer)等内存。 |
OH_RES_TYPE_GLOBAL_HANDLE | 4 | 全局句柄(Global Handle) | 在Native侧通过napi_create_reference创建的ArkTS对象全局引用(napi_ref)。 |
资源泄漏通常是因为在生命周期结束时未正确释放已分配的资源,常见原因包括:
资源采集生成文件类型如下表所示:
文件类型 | 介绍 |
|---|---|
.htrace | 记录采集时间窗口内资源分配的调用栈与统计信息,包含分配频次、栈深度、归属线程等。 可导入DevEco Studio中Profiler工具,按调用栈分组统计,定位泄漏嫌疑点。 |
采集配额约束
采集配额分整机与应用两级管控:
整机级(所有应用共享):每日最多采集4次,超出配额时返回HIDEBUG_RES_PROF_DAILY_QUOTA_EXCEEDED。同一时刻最高支持4个不同应用并行采集,超出配额时返回HIDEBUG_RES_PROF_PROCESS_OVERLIMIT。
采集负载熔断机制
当系统触发以下任一负载保护条件时,将拒绝采集请求并返回相应错误码:
采集并发冲突约束
本API与开发者工具(DevEco Studio中Profiler工具/hiprofiler_cmd)或系统采集任务存在排他性,发生冲突时系统将拒绝采集请求并返回HIDEBUG_RES_PROF_CONFLICT,使用前先退出相关工具或任务。
采集文件老化管控
每种资源类型的采集文件均受以下滚动老化约束:
采集性能功耗与触发策略
受上述采集规格与约束限制,本API不保证采集请求一定成功。调用本API会对当前应用进程及整机性能功耗产生影响,包括但不限于CPU、内存占用升高,丢帧卡顿、发热。集成时必须谨慎评估性能功耗开销,建立严格的条件触发策略(如仅在特定灰度范围内、应用资源超基线阈值时触发,并配置合理的采集参数以兼顾性能功耗平衡)后再决策是否开启。严禁在生产环境下盲目或高频次触发。
采集接口调用约束
场景描述
开发人员观测到应用出现资源泄漏迹象,具体表现为:Native内存持续增长、/proc/self/fd条目数异常增多,以及 /proc/self/status 中 Threads 值持续上升,需定位泄漏代码并分析其调用栈。
开发步骤
Native侧在CMakeLists.txt中链接HiDebug NDK:
target_link_libraries(entry PUBLIC libace_napi.z.so libohhidebug.so)
ArkTS侧引入PerformanceAnalysisKit与Native模块:
import { hilog, hidebug } from '@kit.PerformanceAnalysisKit';
import resourceProfiling from 'libentry.so'; ResourceProfilerManager是对OH_HiDebug_StartProfiler()/OH_HiDebug_StopProfiler()的单例封装,统一管理采集状态与回调,对外暴露采集接口与统一轮询接口。其公开接口签名如下:
class ResourceProfilerManager {
public:
static ResourceProfilerManager &GetInstance()
{
static ResourceProfilerManager instance;
return instance;
}
// Basic profiling interface with custom config
HiDebug_ErrorCode StartProfiling(
OH_HiDebug_ResourceType type,
OH_HiDebug_ResProfilerConfig& config,
std::function<void(OH_HiDebug_ProfilingResult*)> userCallback);
// Basic profiling interface with default config
HiDebug_ErrorCode StartProfiling(
OH_HiDebug_ResourceType type,
std::function<void(OH_HiDebug_ProfilingResult*)> userCallback);
HiDebug_ErrorCode StopProfiling();
// Unified polling detection interface
// Polls multiple resource types; triggers profiling for the matching type
// when any one exceeds its threshold.
// Skips triggering if a profiling task is already running.
void StartUnifiedPolling(std::function<void(const char* resultPath, OH_HiDebug_ResourceType type)> onResult);
void StopUnifiedPolling();
private:
static void InternalProfilingCallback(OH_HiDebug_ProfilingResult* result);
// Polling loop implementation
void PollingLoop(std::function<void(const char* resultPath, OH_HiDebug_ResourceType type)> onResult);
// Resource leak detection sub-functions
static bool CheckNativeLeak(uint64_t nativeBaseline, OH_HiDebug_ResourceType &outType);
static bool CheckGpuLeak(uint64_t gpuBaseline, OH_HiDebug_ResourceType &outType);
static bool CheckFdLeak(int fdLimit, OH_HiDebug_ResourceType &outType);
static bool CheckThreadLeak(int threadLimit, OH_HiDebug_ResourceType &outType);
// Dispatch the over-baseline check for the given resource type.
static bool IsOverBaseline(OH_HiDebug_ResourceType type);
// Polling item used by the unified polling loop.
struct PollingItem {
OH_HiDebug_ResourceType type;
uint32_t intervalSec;
bool needDoubleConfirm;
std::chrono::steady_clock::time_point nextCheck;
int overCount;
};
// Process one polling item; returns true if profiling was started.
bool PollingStep(PollingItem &item, std::chrono::steady_clock::time_point now,
std::chrono::steady_clock::time_point &nearest,
std::function<void(const char*, OH_HiDebug_ResourceType)> onResult);
// Profiling state members
std::atomic<bool> m_isProfiling{false};
std::function<void(OH_HiDebug_ProfilingResult*)> m_userCallback;
// Polling state members
std::atomic<bool> m_isPolling{false};
std::thread m_pollingThread;
}; OH_HiDebug_ResProfilerConfig各参数含义如下:
参数 | 类型 | 默认值 | 含义 |
|---|---|---|---|
maxDuration | uint32_t | 180 | 采集时长上限(秒),到期自动停止 |
filterSize | uint32_t | 256 | 过滤器大小 |
maxStackDepth | uint32_t | 30 | 最大栈深度 |
sampleInterval | uint32_t | 384 | 采样间隔(字节) |
statisticsInterval | uint32_t | 10 | 统计间隔(秒) |
默认配置已在开发实践示例代码中内置,开发者亦可按场景自定义。完整实现(含轮询主循环、阈值检测、回调处理)参考示例代码。
调用startUnifiedPolling即可启动C++后台线程,对FD/Thread/Native/GPU四类资源按各自周期轮询(Native每200s、其余每60s);Native与GPU需连续2次超阈值、FD与Thread单次超阈值即自动触发采集,并通过回调返回结果文件路径:
resourceProfiling.startUnifiedPolling((path: string, type: number) => {
let typeName = 'Unknown';
switch (type) {
case 0: typeName = 'FD'; break;
case 1: typeName = 'Thread'; break;
case 2: typeName = 'Native Mem'; break;
case 3: typeName = 'GPU Mem'; break;
case 4: typeName = 'Global Handle'; break;
default: typeName = `Type ${type}`; break;
}
const msg = `[${typeName}] Profiling Finished!\nPath: ${path}`;
hilog.info(0x3300, 'ResourceProfiling', msg);
this.log = msg;
this.status = 'Idle';
}); 统一轮询内置阈值与触发策略:FD数量5000个、线程数700个、Native内存3GB、GPU内存2.3GB;Native每200s轮询且需连续2次超阈值、GPU每60s轮询且需连续2次超阈值、FD与Thread每60s轮询且单次超阈值即触发采集。
Global Handle泄漏由ArkTS侧独立检测。通过hidebug.getAppVMMemoryInfo()获取VM堆信息,当已使用占比超过70%时触发Global Handle采集:
// VM heap memory detection threshold (70%)
const VM_HEAP_THRESHOLD = 0.7;
let vmTimer: number = -1;
// ...
function detectVMHeapLeak(): void {
try {
const vmInfo = hidebug.getAppVMMemoryInfo();
const heapUsed = hidebug.getAppVMObjectUsedSize();
if (vmInfo.totalHeap > 0 && (heapUsed / vmInfo.totalHeap) > VM_HEAP_THRESHOLD) {
// Call NAPI startProfiling to detect global handle leak
const ret: number = resourceProfiling.startProfiling(RES_TYPE_GLOBAL_HANDLE,
'{"maxDuration":' + String(PROFILE_MAX_DURATION) +
',"filterSize":' + String(PROFILE_FILTER_SIZE) +
',"maxStackDepth":' + String(PROFILE_MAX_STACK_DEPTH) +
',"sampleInterval":' + String(PROFILE_SAMPLE_INTERVAL) +
',"statisticsInterval":' + String(PROFILE_STATISTICS_INTERVAL) + '}');
if (ret === HIDEBUG_RES_PROF_SUCCESS) {
// Set timeout to stop profiling after the max duration
setTimeout(() => {
resourceProfiling.stopProfiling();
}, PROFILE_DURATION_MS);
}
}
} catch (e) {
hilog.error(0x3300, 'ResourceProfiling',
'VM heap detection failed. code: %{public}d, msg: %{public}s', e.code, e.message);
}
} 当能定位到可疑的业务函数时,可在其执行前后手动启停采集,精确覆盖该业务窗口内的资源分配:
HiDebug_ErrorCode ResourceProfilerManager::StartProfiling(
OH_HiDebug_ResourceType type,
OH_HiDebug_ResProfilerConfig& config,
std::function<void(OH_HiDebug_ProfilingResult*)> userCallback)
{
if (!userCallback) {
return HIDEBUG_RES_PROF_INVALID_ARG;
}
if (m_isProfiling.load()) {
return HIDEBUG_RES_PROF_ALREADY_STARTED;
}
m_userCallback = std::move(userCallback);
HiDebug_ErrorCode ret = OH_HiDebug_StartProfiler(type, &config, &InternalProfilingCallback);
if (ret == HIDEBUG_RES_PROF_SUCCESS) {
m_isProfiling.store(true);
}
return ret;
}
HiDebug_ErrorCode ResourceProfilerManager::StartProfiling(
OH_HiDebug_ResourceType type,
std::function<void(OH_HiDebug_ProfilingResult*)> userCallback)
{
OH_HiDebug_ResProfilerConfig config = {};
config.maxDuration = PROFILER_MAX_DURATION_SEC;
config.filterSize = PROFILER_FILTER_SIZE;
config.maxStackDepth = PROFILER_MAX_STACK_DEPTH;
config.sampleInterval = PROFILER_SAMPLE_INTERVAL_MS;
config.statisticsInterval = PROFILER_STATS_INTERVAL_SEC;
return StartProfiling(type, config, std::move(userCallback));
}
HiDebug_ErrorCode ResourceProfilerManager::StopProfiling()
{
if (!m_isProfiling.load()) {
return HIDEBUG_RES_PROF_NOT_STARTED;
}
HiDebug_ErrorCode ret = OH_HiDebug_StopProfiler();
if (ret == HIDEBUG_RES_PROF_SUCCESS) {
m_isProfiling.store(false);
}
return ret;
} 采集完成后,回调中的result->filePath即为结果文件沙箱路径,格式如:/data/storage/el2/base/files/<类型>-<被采集应用进程名>-<进程号>-<时间戳>.htrace。
示例:/data/storage/el2/base/files/native-com.example.resourceleakprofilingdemo-33367-20260708_113011.htrace。
文件导出:参考应用沙箱路径和真实物理路径的对应关系。
抓取到所需维测数据后,停止轮询与定时检测:
// Stop polling and VM detection when the page is destroyed
if (vmTimer !== -1) {
clearInterval(vmTimer);
}
resourceProfiling.stopUnifiedPolling(); 将.htrace文件修改后缀为.txt,导入DevEco Studio中Profiler工具。按调用栈分组统计,出现频次最高的调用栈即为泄漏嫌疑点,调用栈分析方法可参考内存分析介绍。分析要点如下:
资源类型 | 触发采集条件 (推荐值) | 检测间隔 (推荐值) | 参考建议 |
|---|---|---|---|
文件描述符(FD) | 超过5000个 | 60s |
|
线程 | 超过700个 | 60s |
|
Native内存(包含堆内存和映射区内存) | 超过3GB | 200s |
|
GPU内存 | 超过2.3GB | 60s |
|
全局句柄(Global Handle) | VM堆内存使用率超过70% | 60s |
|
本推荐值基于12GB RAM设备。对于其他RAM大小的设备,请根据实际运行情况调整采集阈值。