hiperf代码更新】

Signed-off-by: dong_lihua <dong_lihua@hoperun.com>
This commit is contained in:
dong_lihua 2021-12-29 09:26:17 -05:00 committed by chang_jian
parent 87ecacbb21
commit 47ba87d9b6
57 changed files with 588 additions and 308 deletions

168
.clang-format Executable file
View File

@ -0,0 +1,168 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: Consecutive
AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BreakBeforeBraces: WebKit
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: true
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 100
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
StatementAttributeLikeMacros:
- Q_EMIT
IncludeBlocks: Preserve
#IncludeCategories:
# - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
# Priority: 1
# SortPriority: 0
# CaseSensitive: false
# - Regex: '^(<|"(gtest|gmock|isl|json)/)'
# Priority: 2
# SortPriority: 0
# CaseSensitive: false
# - Regex: '.*'
# Priority: 3
# SortPriority: 0
# CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
# 3.8.1
IndentCaseLabels: true
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequires: false
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 4
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 1000
PenaltyIndentedWhitespace: 0
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceAroundPointerQualifiers: Before
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
Standard: c++17
TabWidth: 4

View File

@ -61,6 +61,7 @@ Note:If the text contains special characters, please escape them according to th
<filteritem type="filepath" name="test/unittest/resource/testdata/.*" desc="test resource file, no license header"/>
<filteritem type="filepath" name="test/unittest/resource/testdata/dwarf/.*" desc="test resource file, no license header"/>
<filteritem type="filepath" name="test/unittest/resource/testdata/report/.*" desc="test resource file, no license header"/>
<filteritem type="filepath" name="test/fuzztest/resource/testdata/.*" desc="test resource file, no license header"/>
</filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies" >
<filteritem type="filepath" name="test/unittest/resource/testdata/.*" desc="test resource file, no copyright header"/>
@ -103,6 +104,7 @@ Note:If the text contains special characters, please escape them according to th
<filteritem type="filepath" name="test/unittest/resource/testdata/report/.*" desc="the binary file for test, the file is self-developed"/>
<filteritem type="filepath" name="test/unittest/resource/testdata/symbols_file_test_elf32" desc="the binary file for test, the file is self-developed"/>
<filteritem type="filepath" name="test/unittest/resource/testdata/symbols_file_test_elf64" desc="the binary file for test, the file is self-developed"/>
<filteritem type="filepath" name="test/fuzztest/resource/testdata/elf_test" desc="the binary file for test, the file is self-developed"/>
</filefilter>
</filefilterlist>
</oatconfig>

File diff suppressed because one or more lines are too long

20
clang_format_all.bat Executable file
View File

@ -0,0 +1,20 @@
@rem Copyright (c) 2020-2021 Huawei Device Co., Ltd.
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@echo off
:: clang-format.exe -style="file" -fallback-style="LLVM" "include\subcommand_list.h"
for /r %%i in (*.h *.cpp) do (
clang-format.exe -style="file" -fallback-style="LLVM" -i --verbose %%i
)
pause

18
clang_format_all.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/bash
# 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.
set -e
echo "formatting C/C++ code ..."
find $@ -name '*.h' -o -name '*.cpp' | xargs clang-format-12 -style="file" -fallback-style="LLVM" -i --verbose

View File

@ -138,9 +138,6 @@ USED_FUNCTION void LoopFunction(milliseconds timeOutMS, const Option &option)
auto now = std::chrono::steady_clock::now();
auto sleepTime = now + seconds(1);
int count = 0;
int a {};
int b {};
int c {};
while (std::chrono::steady_clock::now() < (now + timeOutMS)) {
if (option.sleepms > 0) {
if (std::chrono::steady_clock::now() >= sleepTime) {
@ -158,9 +155,15 @@ USED_FUNCTION void LoopFunction(milliseconds timeOutMS, const Option &option)
LoopBranch();
}
a = b++ * c++;
b = a++ * c++;
c = b++ * a++;
std::default_random_engine rnd;
int a = rnd();
int b = rnd();
int c = rnd();
a = (a++) * (b++) * (c++);
if (a == 0) {
continue;
}
if (!option.nonew) {
auto p = new unsigned int;

View File

@ -37,5 +37,9 @@ int main(const int argc, const char *argv[])
sleep(wartTime);
}
printf("demo stop \n");
if (temp != nullptr) {
free(temp);
temp = nullptr;
}
return 0;
};

View File

@ -15,7 +15,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.huawei.ohos.app'
//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
ohos {
signingConfigs {
debug {

View File

@ -1,5 +1,4 @@
apply plugin: 'com.huawei.ohos.hap'
//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
ohos {
compileSdkVersion 7
defaultConfig {

View File

@ -21,6 +21,7 @@ declare_args() {
hiperf_target_host = false
hiperf_target_static = false
hiperf_test_coverage = false
hiperf_test_fuzz = false
hiperf_sanitize = false
hiperf_check_time = false
hiperf_use_libunwind = true

View File

@ -1,67 +0,0 @@
/*
* 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 ARM_RAW_EVENT_TYPE_TABLE_H
#define ARM_RAW_EVENT_TYPE_TABLE_H
// clang-format off
{0x0, "raw-sw-incr"},
{0x1, "raw-l1-icache-refill"},
{0x2, "raw-l1-itlb-refill"},
{0x3, "raw-l1-dcache-refill"},
{0x4, "raw-l1-dcache"},
{0x5, "raw-l1-dtlb-refill"},
{0x6, "raw-load-retired"},
{0x7, "raw-store-retired"},
{0x8, "raw-instruction-retired"},
{0x9, "raw-exception-taken"},
{0xa, "raw-exception-return"},
{0xb, "raw-cid-write-retired"},
{0xc, "raw-pc-write-retired"},
{0xd, "raw-br-immed-retired"},
{0xe, "raw-br-return-retired"},
{0xf, "raw-unaligned-ldst-retired"},
{0x10, "raw-br-mis-pred"},
{0x11, "raw-cpu-cycles"},
{0x12, "raw-br-pred"},
{0x13, "raw-mem-access"},
{0x14, "raw-l1-icache"},
{0x15, "raw-l1-dcache-wb"},
{0x16, "raw-l2-dcache"},
{0x17, "raw-l2-dcache-refill"},
{0x18, "raw-l2-dcache-wb"},
{0x19, "raw-bus-access"},
{0x1a, "raw-memory-error"},
{0x1b, "raw-inst-spec"},
{0x1c, "raw-ttbr-write-retired"},
{0x1d, "raw-bus-cycles"},
{0x1f, "raw-l1-dcache-allocate"},
{0x20, "raw-l2-dcache-allocate"},
{0x21, "raw-br-retired"},
{0x22, "raw-br-mis-pred-retired"},
{0x23, "raw-stall-frontend"},
{0x24, "raw-stall-backend"},
{0x25, "raw-l1-dtlb"},
{0x26, "raw-l1-itlb"},
{0x27, "raw-l2-icache"},
{0x28, "raw-l2-icache-refill"},
{0x29, "raw-l3-dcache-allocate"},
{0x2a, "raw-l3-dcache-refill"},
{0x2b, "raw-l3-dcache"},
{0x2c, "raw-l3-dcache-wb"},
{0x2d, "raw-l2-dtlb-refill"},
{0x2e, "raw-l2-itlb-refill"},
{0x2f, "raw-l2-dtlb"},
{0x30, "raw-l2-itlb"},
#endif

View File

@ -56,10 +56,12 @@ enum DebugLevel {
#ifdef HIPERF_DEBUG
#if is_ohos || is_double_framework
const std::string DEFAULT_UT_LOG_DIR = "/data/local/tmp/";
const std::string DEFAULT_LOG_PATH = "/data/local/tmp/hiperf_log.txt";
#elif is_mingw
const std::string DEFAULT_LOG_PATH = ".\\hiperf_log.txt";
#elif is_linux
const std::string DEFAULT_UT_LOG_DIR = "./";
const std::string DEFAULT_LOG_PATH = "hiperf_log.txt";
#else
#error unkow os
@ -113,6 +115,11 @@ public:
mutable std::chrono::microseconds logSprintfTimes_ = std::chrono::microseconds::zero();
#endif
// used in UT
bool OpenLog(const std::string & = "", const std::string & = "w");
bool RestoreLog();
void Reset();
private:
bool ShouldLog(DebugLevel debugLevel, const std::string &logTag) const;
DebugLevel GetLogLevelByName(const std::string &) const;
@ -122,12 +129,10 @@ private:
int HiLog(std::string &buffer) const;
static std::unique_ptr<DebugLogger> logInstance_;
std::string logFileBuffer_;
mutable std::mutex logMutex_;
mutable std::recursive_mutex logMutex_;
static DebugLevel debugLevel_;
const std::chrono::steady_clock::time_point timeStamp_;
bool OpenLog();
FILE *file_ = nullptr;
bool mixLogOutput_ = false; // log mix to std
bool enableHilog_ = false;

View File

@ -98,7 +98,54 @@ static const ConfigTable PERF_SW_CONFIGS = {
{PERF_COUNT_SW_BPF_OUTPUT, "sw-bpf-output"},
};
static const ConfigTable PERF_RAW_CONFIGS = {
#include "arm_raw_event_type_table.h"
{0x0, "raw-sw-incr"},
{0x1, "raw-l1-icache-refill"},
{0x2, "raw-l1-itlb-refill"},
{0x3, "raw-l1-dcache-refill"},
{0x4, "raw-l1-dcache"},
{0x5, "raw-l1-dtlb-refill"},
{0x6, "raw-load-retired"},
{0x7, "raw-store-retired"},
{0x8, "raw-instruction-retired"},
{0x9, "raw-exception-taken"},
{0xa, "raw-exception-return"},
{0xb, "raw-cid-write-retired"},
{0xc, "raw-pc-write-retired"},
{0xd, "raw-br-immed-retired"},
{0xe, "raw-br-return-retired"},
{0xf, "raw-unaligned-ldst-retired"},
{0x10, "raw-br-mis-pred"},
{0x11, "raw-cpu-cycles"},
{0x12, "raw-br-pred"},
{0x13, "raw-mem-access"},
{0x14, "raw-l1-icache"},
{0x15, "raw-l1-dcache-wb"},
{0x16, "raw-l2-dcache"},
{0x17, "raw-l2-dcache-refill"},
{0x18, "raw-l2-dcache-wb"},
{0x19, "raw-bus-access"},
{0x1a, "raw-memory-error"},
{0x1b, "raw-inst-spec"},
{0x1c, "raw-ttbr-write-retired"},
{0x1d, "raw-bus-cycles"},
{0x1f, "raw-l1-dcache-allocate"},
{0x20, "raw-l2-dcache-allocate"},
{0x21, "raw-br-retired"},
{0x22, "raw-br-mis-pred-retired"},
{0x23, "raw-stall-frontend"},
{0x24, "raw-stall-backend"},
{0x25, "raw-l1-dtlb"},
{0x26, "raw-l1-itlb"},
{0x27, "raw-l2-icache"},
{0x28, "raw-l2-icache-refill"},
{0x29, "raw-l3-dcache-allocate"},
{0x2a, "raw-l3-dcache-refill"},
{0x2b, "raw-l3-dcache"},
{0x2c, "raw-l3-dcache-wb"},
{0x2d, "raw-l2-dtlb-refill"},
{0x2e, "raw-l2-itlb-refill"},
{0x2f, "raw-l2-dtlb"},
{0x30, "raw-l2-itlb"},
};
static ConfigTable PERF_TRACEPOINT_CONFIGS = {

View File

@ -65,6 +65,7 @@ public:
// clang-format on
{
}
~SubCommandDump() override;
bool OnSubCommand(std::vector<std::string> &args) override;
bool ParseOption(std::vector<std::string> &args) override;

View File

@ -90,9 +90,9 @@ private:
bool helpOption_ {false};
PerfEventParanoid request_ = USER;
bool CheckOptionPid(std::vector<pid_t> pids);
static __u64 FindEventCount(
static bool FindEventCount(
const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
const std::string &configName, const __u64 group_id, double &scale);
const std::string &configName, const __u64 group_id, __u64 &eventcount, double &scale);
static void GetComments(
const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
std::map<std::string, std::string> &comments);
@ -121,4 +121,4 @@ bool RegisterSubCommandStat(void);
} // namespace HiPerf
} // namespace Developtools
} // namespace OHOS
#endif
#endif

View File

@ -80,9 +80,9 @@ struct Symbol {
: funcVaddr_(vaddr),
fileVaddr_(vaddr),
len_(len),
name_(memHolder.HoldStringView(name)),
demangle_(memHolder.HoldStringView(demangle)),
module_(memHolder.HoldStringView(module)) {};
name_(MemoryHold::Get().HoldStringView(name)),
demangle_(MemoryHold::Get().HoldStringView(demangle)),
module_(MemoryHold::Get().HoldStringView(module)) {};
Symbol(uint64_t vaddr, uint64_t len, const std::string &name, const std::string &module)
: Symbol(vaddr, len, name, name, module) {};
@ -142,7 +142,7 @@ struct Symbol {
} else {
sstream << comm_ << "@0x" << std::hex << taskVaddr_;
}
unknow_ = memHolder.HoldStringView(sstream.str());
unknow_ = MemoryHold::Get().HoldStringView(sstream.str());
}
return unknow_;
}

View File

@ -90,13 +90,11 @@ namespace HiPerf {
const std::string EMPTY_STRING = "";
// string function
static class StringViewMemoryHold {
class MemoryHold {
public:
~StringViewMemoryHold()
~MemoryHold()
{
for (auto &p : holder_) {
delete[] p;
}
Clean();
}
const char *HoldStringView(std::string_view view)
{
@ -110,10 +108,23 @@ public:
holder_.emplace_back(p);
return p;
};
// only use in UT
void Clean()
{
for (auto &p : holder_) {
delete[] p;
}
holder_.clear();
}
static MemoryHold &Get()
{
static MemoryHold instance;
return instance;
}
private:
std::vector<char *> holder_;
} memHolder;
};
std::string StringReplace(std::string source, const std::string &from, const std::string &to);
@ -158,7 +169,7 @@ bool StringStartsWith(const std::string &string, const std::string &with);
bool StringEndsWith(const std::string &string, const std::string &with);
bool IsSameCommand(std::string cmdLine, std::string cmdName);
bool IsSameCommand(const std::string &cmdLine, const std::string &cmdName);
std::vector<pid_t> GetSubthreadIDs(const pid_t pid);
@ -318,4 +329,4 @@ int munmap(void *addr, size_t);
#endif
#endif
#endif
#endif

View File

@ -14,10 +14,11 @@
import("//build/ohos.gni")
import("//developtools/hiperf/hiperf.gni")
config("hiperf_client_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"include" ,
"${hiperf_path}/include",
]
}
@ -27,10 +28,28 @@ ohos_shared_library("hiperf_client") {
public_configs = [ ":hiperf_client_config" ]
sources = [ "src/hiperf_client.cpp" ]
defines = []
if (is_linux) {
if(is_linux) {
defines += [ "CONFIG_NO_HILOG" ]
} else {
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
]
}
subsystem_name = "developtools"
part_name = "hiperf"
}
ohos_static_library("hiperf_client_static") {
public_configs = [ ":hiperf_client_config" ]
sources = [ "src/hiperf_client.cpp" ]
defines = []
if(is_linux) {
defines += [ "CONFIG_NO_HILOG" ]
} else {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
]
}
subsystem_name = "developtools"

View File

@ -309,8 +309,7 @@ private:
std::string outputFileName_ = "";
std::string executeCommandPath_ = "";
bool ready_ = false;
pid_t myPid_ = false;
pid_t myTid_ = false;
pid_t myPid_ = -1;
bool debug_ = false;
bool debugMuch_ = false;
bool hilog_ = false;

View File

@ -306,12 +306,6 @@ bool Client::Setup(std::string outputDir)
myPid_ = getpid();
#ifndef gettid
myTid_ = syscall(SYS_gettid);
#else
myTid_ = gettid();
#endif
// every thing check ok
ready_ = true;
@ -456,7 +450,7 @@ bool Client::WaitCommandReply(std::chrono::milliseconds timeOut)
if (polled > 0) {
while (true) {
char c;
size_t result = TEMP_FAILURE_RETRY(read(serverToClientFd_, &c, 1));
ssize_t result = TEMP_FAILURE_RETRY(read(serverToClientFd_, &c, 1));
if (result <= 0) {
HIPERF_HILOGD(MODULE_CPP_API, "read failed from pipe");
return false; // read fial means not ok

View File

@ -29,11 +29,13 @@ ohos_shared_library("hiperf_client_napi") {
configs = [ ":hiperf_client_napi_config" ]
sources = [ "hiperf_client_napi.cpp" ]
deps = [
"${innerkits_path}/native:hiperf_client",
"//foundation/ace/napi:ace_napi",
"${innerkits_path}/native:hiperf_client",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
]
output_name = "hiperf_napi"
relative_install_dir = "module"

View File

@ -469,12 +469,11 @@ static napi_value GetOptionVecString(napi_env env, napi_callback_info info)
static napi_value StartWithOption(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
bool result = false;
// for js api , we always use hilog
g_hiperfClient->EnableHilog();
result = g_hiperfClient->Setup(g_hiperfRecordOption->GetOutputFileName());
bool result = g_hiperfClient->Setup(g_hiperfRecordOption->GetOutputFileName());
if (result) {
const HiperfClient::RecordOption *option = g_hiperfRecordOption.get();
result = g_hiperfClient->Start(*option);
@ -501,13 +500,12 @@ static napi_value Start(napi_env env, napi_callback_info info)
static napi_value Setup(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
bool result = false;
std::string outputPath = GetJsStringFromOption(env, info);
// for js api , we always use hilog
g_hiperfClient->EnableHilog();
result = g_hiperfClient->Setup(outputPath);
bool result = g_hiperfClient->Setup(outputPath);
NAPI_CALL(env, napi_create_int32(env, result, &napiValue));
HIPERF_HILOGD(MODULE_JS_NAPI, "%{public}d", result);

View File

@ -19,7 +19,8 @@
}
],
"test_list": [
"//developtools/hiperf/test:hiperf_unittest"
"//developtools/hiperf/test:hiperf_unittest",
"//developtools/hiperf/test:hiperf_fuzztest"
]
}
}

View File

@ -71,11 +71,10 @@ void CallStack::dumpUDI(unw_dyn_info_t &di)
bool CallStack::fillUDI(unw_dyn_info_t &di, SymbolsFile &symbolsFile, const MemMapItem &mmap,
const VirtualThread &thread)
{
uint64_t fdeTableElfOffset, fdeTableSize, ehFrameHdrElfOffset;
uint64_t SectionVaddr, SectionSize, SectionFileOffset;
di.start_ip = mmap.begin_;
di.end_ip = mmap.end_;
#ifndef target_cpu_arm
uint64_t fdeTableElfOffset, fdeTableSize, ehFrameHdrElfOffset;
if ((UNW_INFO_FORMAT_REMOTE_TABLE == di.format) &&
symbolsFile.GetHDRSectionInfo(ehFrameHdrElfOffset, fdeTableElfOffset, fdeTableSize)) {
/*
@ -118,8 +117,11 @@ bool CallStack::fillUDI(unw_dyn_info_t &di, SymbolsFile &symbolsFile, const MemM
HLOGV(" fdeTableElfOffset: 0x%016" PRIx64 "", fdeTableElfOffset);
HLOGV(" fdeTableSize: 0x%016" PRIx64 "", fdeTableSize);
return true;
} else {
HLOGD("SymbolsFile::GetHDRSectionInfo() failed");
}
#else
uint64_t SectionVaddr, SectionSize, SectionFileOffset;
if ((UNW_INFO_FORMAT_ARM_EXIDX == di.format) &&
symbolsFile.GetSectionInfo(ARM_EXIDX, SectionVaddr, SectionSize, SectionFileOffset)) {
const MemMapItem *targetMmap = thread.FindMapByFileInfo(mmap.name_, SectionFileOffset);
@ -140,6 +142,8 @@ bool CallStack::fillUDI(unw_dyn_info_t &di, SymbolsFile &symbolsFile, const MemM
// GetSectionInfo return true, but SectionVaddr || SectionSize is 0 ???
HLOG_ASSERT(SectionVaddr != 0 && SectionSize != 0);
return true;
} else {
HLOGD("SymbolsFile::GetSectionInfo() failed");
}
#endif
return false;
@ -161,9 +165,6 @@ int CallStack::FindUnwindTable(SymbolsFile *symbolsFile, const MemMapItem &mmap,
dsoUnwDynInfoMap &dynFileMap = dynInfoProcessMap[unwindInfoPtr->thread.pid_];
// find use dso name as key
if (dynFileMap.find(symbolsFile->filePath_) == dynFileMap.end()) {
// we make a option empty value first
std::optional<unw_dyn_info_t> &odi = dynFileMap[symbolsFile->filePath_];
unw_dyn_info_t newdi;
memset_s(&newdi, sizeof(unw_dyn_info_t), 0, sizeof(unw_dyn_info_t));
#ifdef target_cpu_arm
@ -175,7 +176,12 @@ int CallStack::FindUnwindTable(SymbolsFile *symbolsFile, const MemMapItem &mmap,
#endif
if (fillUDI(newdi, *symbolsFile, mmap, unwindInfoPtr->thread)) {
dumpUDI(newdi);
// we make a option empty value first
std::optional<unw_dyn_info_t> &odi = dynFileMap[symbolsFile->filePath_];
odi = newdi;
} else {
HLOGV("fillUDI failed()");
return -UNW_EUNSPEC;
}
}
@ -265,10 +271,8 @@ int CallStack::AccessMem([[maybe_unused]] unw_addr_space_t as, unw_word_t addr,
unw_word_t *valuePoint, int writeOperation, void *arg)
{
UnwindInfo *unwindInfoPtr = static_cast<UnwindInfo *>(arg);
size_t stackOffset = 0;
*valuePoint = 0;
HLOGDUMMY("try access addr 0x%" UNW_WORD_PFLAG " ", addr);
HLOG_ASSERT(writeOperation == 0);
/* Check overflow. */
@ -290,7 +294,7 @@ int CallStack::AccessMem([[maybe_unused]] unw_addr_space_t as, unw_word_t addr,
return -UNW_EUNSPEC;
}
} else {
stackOffset = addr - unwindInfoPtr->callStack.stackPoint_;
size_t stackOffset = addr - unwindInfoPtr->callStack.stackPoint_;
*valuePoint = *(unw_word_t *)&unwindInfoPtr->callStack.stack_[stackOffset];
HLOGM("access_mem addr %p val %" UNW_WORD_PFLAG ", from stack offset %zu",
reinterpret_cast<void *>(addr), *valuePoint, stackOffset);
@ -580,11 +584,10 @@ size_t CallStack::ExpendCallStack(pid_t tid, std::vector<CallFrame> &callFrames,
if (!cachedCallFramesMap_.count(tid)) {
cachedCallFramesMap_[tid].reserve(MAX_CALL_FRAME_EXPEND_CACHE_SIZE);
}
HashList<uint64_t, std::vector<CallFrame>> &cachedCallFrames = cachedCallFramesMap_[tid];
if (callFrames.size() >= 1u) {
// get top (Earliest caller)
HashList<uint64_t, std::vector<CallFrame>> &cachedCallFrames = cachedCallFramesMap_[tid];
HLOGV("find call stack frames in cahce %zu", cachedCallFrames.size());
// compare
using namespace std::rel_ops; // enable complement comparing operators
for (auto itr = cachedCallFrames.begin(); itr < cachedCallFrames.end(); ++itr) {

View File

@ -29,7 +29,6 @@ namespace Developtools {
namespace HiPerf {
DebugLogger::DebugLogger() : timeStamp_(steady_clock::now()), logPath_(DEFAULT_LOG_PATH)
{
logFileBuffer_.resize(LOG_BUFFER_SIZE);
OpenLog();
}
@ -108,11 +107,11 @@ int DebugLogger::Log(DebugLevel level, const std::string &logTag, const char *fm
if (enableHilog_) {
#if is_ohos && !defined(CONFIG_NO_HILOG)
std::lock_guard<std::mutex> lock(logMutex_);
std::lock_guard<std::recursive_mutex> lock(logMutex_);
ret = HiLog(buffer); // to the hilog
#endif
} else if (file_ != nullptr) {
std::lock_guard<std::mutex> lock(logMutex_);
std::lock_guard<std::recursive_mutex> lock(logMutex_);
#ifdef HIPERF_DEBUG_TIME
const auto startWriteTime = steady_clock::now();
#endif
@ -138,8 +137,10 @@ int DebugLogger::Log(DebugLevel level, const std::string &logTag, const char *fm
bool DebugLogger::EnableHiLog(bool enable)
{
enableHilog_ = enable;
if (fprintf(stdout, "change to use hilog\n") < 0) {
// what can we do here ???
if (enable) {
if (fprintf(stdout, "change to use hilog\n") < 0) {
// what can we do here ???
}
}
return enableHilog_;
}
@ -168,8 +169,8 @@ bool DebugLogger::SetMixLogOutput(bool enable)
bool DebugLogger::SetLogPath(const std::string &newLogPath)
{
// make sure not write happend when rename
std::lock_guard<std::mutex> lock(logMutex_);
if (newLogPath.empty()) {
std::lock_guard<std::recursive_mutex> lock(logMutex_);
if (newLogPath.empty() and newLogPath != logPath_) {
return false;
}
if (file_ != nullptr) {
@ -228,12 +229,34 @@ DebugLevel DebugLogger::GetLogLevelByName(const std::string &name) const
return LEVEL_MUCH;
}
bool DebugLogger::OpenLog()
// only use for UT
void DebugLogger::Reset()
{
EnableHiLog(false);
SetLogLevel(LEVEL_VERBOSE);
Disable(false);
SetLogPath(DEFAULT_LOG_PATH);
SetLogTags("");
}
bool DebugLogger::RestoreLog()
{
// use append not write for continually write
return OpenLog(logPath_, "a");
}
bool DebugLogger::OpenLog(const std::string &tempLogPath, const std::string &flags)
{
std::lock_guard<std::recursive_mutex> lock(logMutex_);
if (logDisabled_) {
// don't reopen it when we crash or soemthing else.
return false;
}
if (!tempLogPath.empty()) {
fclose(file_);
file_ = fopen(tempLogPath.c_str(), flags.c_str());
}
if (file_ != nullptr) {
// already open
return true;
@ -247,7 +270,6 @@ bool DebugLogger::OpenLog()
} else {
fseek(file_, 0, SEEK_SET);
// ecach log can save 6ms (29ms -> 23ms)
setvbuf(file_, logFileBuffer_.data(), _IOFBF, logFileBuffer_.size());
fprintf(stdout, "log will save at '%s'\n", logPath_.c_str());
return true;
}

View File

@ -110,7 +110,7 @@ std::unique_ptr<SymbolTable> SymbolTable::MakeUnique(const std::string &symNames
Symbol table '.symtab' contains 2 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 000000009c868f20 356 FUNC GLOBAL DEFAULT 1 com.android.quickstep.vie
1: 000000009c868f20 356 FUNC GLOBAL DEFAULT 1
*/
if ((curPos + entrySize) > secSize) {
break;

View File

@ -101,7 +101,7 @@ int ReportUnwindJson(const char *perfFile, const char *reportFile, const char *s
return -1;
}
static std::unique_ptr<PerfFileReader> GetReader(const std::string fileName)
static std::unique_ptr<PerfFileReader> GetReader(const std::string &fileName)
{
// check if file exist
if (access(fileName.c_str(), F_OK) != 0) {

View File

@ -171,12 +171,15 @@ void PerfRecordSample::ReplaceWithCallStack()
}
// add user context mark
ips_.emplace_back(PERF_CONTEXT_USER);
std::all_of(callFrames_.begin(), callFrames_.end(), [&](const CallFrame &frame) {
bool ret = std::all_of(callFrames_.begin(), callFrames_.end(), [&](const CallFrame &frame) {
ips_.emplace_back(frame.ip_);
return true;
});
HLOGV("combed %zu", callFrames_.size());
if (ret) {
HLOGV("combed %zu", callFrames_.size());
} else {
HLOGV("failed to combed %zu", callFrames_.size());
}
if (sampleType_ & PERF_SAMPLE_REGS_USER) {
data_.reg_nr = 0;

View File

@ -1186,7 +1186,7 @@ void PerfEvents::ReadRecordsFromMmaps()
#endif
// get readable mmap at this time
for (auto &it : cpuMmap_) {
size_t dataSize = it.second.mmapPage->data_head - it.second.mmapPage->data_tail;
ssize_t dataSize = it.second.mmapPage->data_head - it.second.mmapPage->data_tail;
__sync_synchronize(); // this same as rmb in gcc, after reading mmapPage->data_head
if (dataSize <= 0) {
continue;

View File

@ -361,7 +361,6 @@ const std::vector<std::unique_ptr<PerfFileSection>> &PerfFileReader::GetFeatureS
const std::string PerfFileReader::GetFeatureString(const FEATURE feature) const
{
std::string result;
std::string featureName = PerfFileSection::GetFeatureName(feature);
HLOGV("GetFeatureSection %s", featureName.c_str());
if (!IsFeatrureStringSection(feature)) {

View File

@ -246,7 +246,7 @@ bool ReportProtobufFileReader::CheckFileMagic()
bool ReportProtobufFileReader::Dump(std::string fileName, ProtobufReadBack readBack)
{
int defaultIndent = 0;
const int defaultIndent = 0;
fileName_ = fileName;
try {
protobufFileStream_->exceptions(std::ifstream::failbit | std::ifstream::badbit);

View File

@ -109,6 +109,11 @@ bool SubCommandDump::ParseOption(std::vector<std::string> &args)
return CheckInputFile();
}
SubCommandDump::~SubCommandDump()
{
SymbolsFile::onRecording_ = true; // back to default for UT
}
bool SubCommandDump::OnSubCommand(std::vector<std::string> &args)
{
HLOGV("enter");

View File

@ -847,7 +847,7 @@ void SubCommandRecord::ClientCommandHandle()
std::string command;
while (true) {
char c;
size_t result = TEMP_FAILURE_RETRY(read(clientPipeInput_, &c, 1));
ssize_t result = TEMP_FAILURE_RETRY(read(clientPipeInput_, &c, 1));
if (result <= 0) {
HLOGD("server :read from pipe file failed");
break;
@ -995,7 +995,7 @@ bool SubCommandRecord::WaitFifoReply(int fd)
if (polled > 0) {
while (true) {
char c;
size_t result = TEMP_FAILURE_RETRY(read(fd, &c, 1));
ssize_t result = TEMP_FAILURE_RETRY(read(fd, &c, 1));
if (result <= 0) {
HLOGD("read from fifo file(%s) failed", CONTROL_FIFO_FILE_S2C.c_str());
break;
@ -1255,9 +1255,11 @@ void SubCommandRecord::AddMemTotalFeature()
continue;
}
it++;
uint64_t memTotal = std::stoul(*it);
fileWriter_->AddU64Feature(FEATURE::TOTAL_MEM, memTotal);
if ((it + 1) != subStrs.end()) {
uint64_t memTotal = std::stoul(*(it + 1));
fileWriter_->AddU64Feature(FEATURE::TOTAL_MEM, memTotal);
}
break;
}
}

View File

@ -561,6 +561,8 @@ SubCommandReport::~SubCommandReport()
if (output_ != nullptr && output_ != stdout) {
fclose(output_);
}
SymbolsFile::onRecording_ = true; // back to default for UT
}
bool SubCommandReport::OnSubCommand(std::vector<std::string> &args)

View File

@ -139,19 +139,20 @@ void SubCommandStat::Report(
}
}
__u64 SubCommandStat::FindEventCount(
bool SubCommandStat::FindEventCount(
const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
const std::string &configName, const __u64 group_id, double &scale)
const std::string &configName, const __u64 group_id, __u64 &eventCount, double &scale)
{
auto itr = countEvents.find(configName);
if (itr != countEvents.end() && itr->second->id == group_id) {
if (itr->second->time_running < itr->second->time_enabled
&& itr->second->time_running != 0) {
if (itr->second->time_running < itr->second->time_enabled &&
itr->second->time_running != 0) {
scale = static_cast<double>(itr->second->time_enabled) / itr->second->time_running;
}
return itr->second->eventCount;
eventCount = itr->second->eventCount;
return true;
}
return 0;
return false;
}
std::string SubCommandStat::GetCommentConfigName(
@ -221,10 +222,10 @@ void SubCommandStat::GetComments(
if (configName == commentConfigName && it->second->eventCount != 0) {
std::string cpuSyclesName = GetCommentConfigName(it->second, "hw-cpu-cycles");
double otherScale = 1.0;
__u64 cpuCyclesCount =
FindEventCount(countEvents, cpuSyclesName, it->second->id, otherScale);
if (cpuCyclesCount != 0
|| (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) {
__u64 cpuCyclesCount = 0;
bool other = FindEventCount(countEvents, cpuSyclesName, it->second->id, cpuCyclesCount,
otherScale);
if (other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) {
double cpi = static_cast<double>(cpuCyclesCount) / it->second->eventCount;
comments[configName] = StringPrintf("%lf cycles per instruction", cpi);
continue;
@ -234,13 +235,14 @@ void SubCommandStat::GetComments(
if (configName == commentConfigName) {
std::string branchInsName = GetCommentConfigName(it->second, "hw-branch-instructions");
double otherScale = 1.0;
__u64 branchInstructionsCount =
FindEventCount(countEvents, branchInsName, it->second->id, otherScale);
if (branchInstructionsCount != 0
|| (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) {
__u64 branchInstructionsCount = 0;
bool other = FindEventCount(countEvents, branchInsName, it->second->id,
branchInstructionsCount, otherScale);
if ((other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) &&
branchInstructionsCount != 0) {
double miss_rate =
static_cast<double>(it->second->eventCount) / branchInstructionsCount;
comments[configName] = StringPrintf("%lf%% miss rate", miss_rate * ONE_HUNDRED);
comments[configName] = StringPrintf("%lf miss rate", miss_rate * ONE_HUNDRED);
continue;
}
}
@ -290,14 +292,12 @@ bool SubCommandStat::FindRunningTime(
bool SubCommandStat::CheckOptionPid(std::vector<pid_t> pids)
{
int rc = 0;
if (pids.empty()) {
return true;
}
for (auto pid : pids) {
rc = kill(pid, 0);
int rc = kill(pid, 0);
if (rc == -1 || rc == ESRCH) {
printf("not exit pid = %d\n", pid);
return false;
@ -494,4 +494,4 @@ bool SubCommandStat::CheckOptions(const std::vector<pid_t> &pids)
}
} // namespace HiPerf
} // namespace Developtools
} // namespace OHOS
} // namespace OHOS

View File

@ -58,11 +58,11 @@ size_t SubStringCount(const std::string &source, const std::string &sub)
std::vector<std::string> StringSplit(std::string source, std::string split)
{
size_t pos = 0;
std::vector<std::string> result;
// find
if (!split.empty()) {
size_t pos = 0;
while ((pos = source.find(split)) != std::string::npos) {
// split
std::string token = source.substr(0, pos);
@ -223,7 +223,7 @@ std::string PlatformPathConvert(const std::string &path)
std::string ReadFileToString(const std::string &fileName)
{
std::ifstream inputString(fileName, std::ios::in);
if (!inputString) {
if (!inputString or !inputString.is_open()) {
return EMPTY_STRING;
}
std::istreambuf_iterator<char> firstIt = {inputString};
@ -411,7 +411,7 @@ std::vector<std::string> GetSubDirs(const std::string &basePath)
return result;
}
bool IsSameCommand(std::string cmdLine, std::string cmdName)
bool IsSameCommand(const std::string &cmdLine, const std::string &cmdName)
{
std::vector<std::string> cmdpaths = StringSplit(cmdLine, "/");
if (!cmdpaths.empty()) {
@ -550,4 +550,4 @@ int munmap(void *addr, size_t)
*/
return !UnmapViewOfFile(addr);
}
#endif
#endif

View File

@ -64,7 +64,7 @@ common_deps = [
"${hiperf_path}/:hiperf_platform_common",
"${hiperf_path}/:hiperf_platform_host",
"${hiperf_path}/:hiperf_platform_linux",
"${hiperf_path}/interfaces/innerkits/native:hiperf_client",
"${hiperf_path}/interfaces/innerkits/native:hiperf_client_static",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
@ -180,10 +180,14 @@ group("hiperf_test") {
":hiperf_fuzztest(${host_toolchain})",
":hiperf_unittest(${host_toolchain})",
]
} else {
} else if (hiperf_test_fuzz){
deps = [
":hiperf_fuzztest",
":hiperf_unittest",
]
} else {
deps = [
":hiperf_unittest",
]
}
}

View File

@ -1 +1,16 @@
/*
* 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.
*/
FUZZ

View File

@ -48,7 +48,7 @@ bool FuzzCommandLine(const char *subcommand, const uint8_t *data, size_t size)
}
}
#ifdef DEBUG_HIPERF_FUZZ
std::cout << " size " << argv.size() << " subcommand " << subcommand << std::endl;
std::cout << " size " << argv.size() << std::endl;
#endif
hiperf_fuzzer_main(static_cast<int>(argv.size()), argv.data());

View File

@ -1 +1,16 @@
/*
* 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.
*/
FUZZ

View File

@ -1 +1,16 @@
/*
* 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.
*/
FUZZ

View File

@ -1 +1,16 @@
/*
* 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.
*/
FUZZ

View File

@ -63,14 +63,14 @@ public:
static std::unique_ptr<PerfFileReaderFuzzer> Instance(const std::string &fileName,
const uint8_t *data, size_t size)
{
FILE *fp = fopen(fileName.c_str(), "rb");
std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(fileName.c_str(), "rb"), fclose);
if (fp == nullptr) {
HLOGE("fail to open file %s", fileName.c_str());
return nullptr;
}
std::unique_ptr<PerfFileReaderFuzzer> reader =
std::make_unique<PerfFileReaderFuzzer>(fileName, fp);
std::make_unique<PerfFileReaderFuzzer>(fileName, fp.get());
reader->dataPtr_ = reinterpret_cast<const char *>(data);
reader->dataSize_ = size;

View File

@ -1 +1,16 @@
/*
* 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.
*/
FUZZ

View File

@ -30,9 +30,16 @@ public:
default_random_engine rnd_;
};
void CallStackTest::SetUpTestCase() {}
void CallStackTest::SetUpTestCase()
{
DebugLogger::GetInstance()->Reset();
DebugLogger::GetInstance()->OpenLog(DEFAULT_UT_LOG_DIR + "CallStackTest.txt");
}
void CallStackTest::TearDownTestCase() {}
void CallStackTest::TearDownTestCase()
{
DebugLogger::GetInstance()->RestoreLog();
}
void CallStackTest::SetUp() {}
@ -531,26 +538,13 @@ HWTEST_F(CallStackTest, GetUnwErrorName, TestSize.Level1)
HWTEST_F(CallStackTest, ExpendCallStackSmall, TestSize.Level1)
{
CallStack callStack;
StdoutRecord stdoutRecord;
std::string stringOut;
std::vector<CallFrame> stack0 = {};
std::vector<CallFrame> stack1 = {{0x1, 0x1}};
std::vector<CallFrame> stack2 = {{0x1, 0x1}, {0x2, 0x2}};
ScopeDebugLevel tempLogLevel(LEVEL_MUCH, true);
stdoutRecord.Start();
ASSERT_EQ(callStack.ExpendCallStack(0, stack0), 0u);
ASSERT_EQ(callStack.ExpendCallStack(0, stack1), 0u);
ASSERT_EQ(callStack.ExpendCallStack(0, stack1), 0u);
ASSERT_EQ(callStack.ExpendCallStack(0, stack2, 2), 0u);
stringOut = stdoutRecord.Stop();
// for stack0
EXPECT_EQ(stringOut.find("new callstack is too small") != std::string::npos, true);
// for stack2 , 2
EXPECT_EQ(stringOut.find("cache callstack is too small") != std::string::npos, true);
}
/**
* @tc.name: UnwindCallStack

View File

@ -25,10 +25,10 @@ using namespace OHOS::HiviewDFX;
namespace OHOS {
namespace Developtools {
namespace HiPerf {
#ifdef DEFAULT_LOG_LEVEL
DebugLevel DebugLogger::debugLevel_ = DEFAULT_LOG_LEVEL;
bool DebugLogger::logDisabled_ = false;
#endif
class DebugLoggerTest : public testing::Test {
public:
static void SetUpTestCase(void);
@ -40,9 +40,15 @@ public:
std::random_device rd_;
};
void DebugLoggerTest::SetUpTestCase() {}
void DebugLoggerTest::SetUpTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void DebugLoggerTest::TearDownTestCase() {}
void DebugLoggerTest::TearDownTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void DebugLoggerTest::SetUp() {}

View File

@ -40,15 +40,18 @@ public:
void HiperfClientTest::SetUpTestCase() {}
void HiperfClientTest::TearDownTestCase() {}
void HiperfClientTest::TearDownTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void HiperfClientTest::SetUp() {}
void HiperfClientTest::TearDown() {
void HiperfClientTest::TearDown()
{
this_thread::sleep_for(1s);
}
/**
* @tc.name:
* @tc.desc: record

View File

@ -217,7 +217,10 @@ attr 1:
}
void HiperfLibReportTest::SetUpTestCase() {}
void HiperfLibReportTest::TearDownTestCase() {}
void HiperfLibReportTest::TearDownTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void HiperfLibReportTest::SetUp() {}

View File

@ -39,12 +39,19 @@ public:
default_random_engine rnd_;
};
void OptionDebugTest::SetUpTestCase() {}
void OptionDebugTest::SetUpTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void OptionDebugTest::TearDownTestCase() {}
void OptionDebugTest::TearDownTestCase()
{
DebugLogger::GetInstance()->Reset();
}
void OptionDebugTest::SetUp()
{
Option::ClearMainOptions();
SubCommand::RegisterSubCommand(TEST_CMD_NOTHING,
std::make_unique<SubCommandTest>(TEST_CMD_NOTHING));
RegisterMainCommandDebug();
@ -94,9 +101,9 @@ HWTEST_F(OptionDebugTest, TestRegisterMainCommandDebug, TestSize.Level1)
{
// see RegisterMainCommandDebug
#if is_ohos
EXPECT_GE(Option::GetMainOptions().size(), 9u);
EXPECT_EQ(Option::GetMainOptions().size(), 8u);
#else
EXPECT_GE(Option::GetMainOptions().size(), 8u);
EXPECT_EQ(Option::GetMainOptions().size(), 7u);
#endif
}

View File

@ -66,6 +66,7 @@ void SubCommandRecordTest::TearDown()
ASSERT_EQ(SubCommand::GetSubCommands().size(), 1u);
SubCommand::ClearSubCommands();
ASSERT_EQ(SubCommand::GetSubCommands().size(), 0u);
MemoryHold::Get().Clean();
}
void SubCommandRecordTest::TestRecordCommand(const std::string &option, bool expect, bool fixPid)
@ -280,13 +281,13 @@ void SubCommandRecordTest::TestEvents(std::string &opt, std::string &uk)
int testEventCount = MAX_TESTEVENT;
std::string cmdline = opt;
for (auto config : configs) {
if (testEventCount <= 0) {
break;
}
cmdline += config.second;
cmdline += uk;
cmdline += ",";
testEventCount--;
if (testEventCount <= 0) {
break;
}
cmdline += config.second;
cmdline += uk;
cmdline += ",";
testEventCount--;
}
cmdline.pop_back(); // remove the last ','
TestRecordCommand(cmdline);
@ -497,7 +498,6 @@ HWTEST_F(SubCommandRecordTest, CallStackInputErr, TestSize.Level1)
TestRecordCommand("-d 2 -s what ", false);
}
HWTEST_F(SubCommandRecordTest, CallStackDwarfSizeMin, TestSize.Level1)
{
// it will cause some crash in -fprofile-arcs and -ftest-coverage

View File

@ -48,7 +48,8 @@ public:
};
void SubCommandReportTest::SetUpTestCase() {}
void SubCommandReportTest::TearDownTestCase() {}
void SubCommandReportTest::TearDownTestCase() {
}
void SubCommandReportTest::SetUp()
{
@ -61,6 +62,7 @@ void SubCommandReportTest::TearDown()
{
SubCommand::ClearSubCommands();
ASSERT_EQ(SubCommand::GetSubCommands().size(), 0u);
MemoryHold::Get().Clean();
}
bool SubCommandReportTest::FindExpectStr(const std::string &stringOut,

View File

@ -53,7 +53,6 @@ public:
const std::string &groupCounterName) const;
const std::vector<std::string> defaultConfigNames_ = {
"hw-branch-instructions",
"hw-branch-misses",
"hw-cpu-cycles",
"hw-instructions",
@ -1009,7 +1008,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_e3, TestSize.Level1)
std::string cmdstr = "stat -p ";
cmdstr += std::to_string(tid1);
cmdstr += " -e hw-branch-instructions -c 0 -d 3 --dumpoptions";
cmdstr += " -e hw-instructions -c 0 -d 3 --dumpoptions";
StdoutRecord stdoutRecord;
stdoutRecord.Start();
@ -1023,7 +1022,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_e3, TestSize.Level1)
if (HasFailure()) {
printf("output:\n%s", stringOut.c_str());
}
const std::vector<std::string> configNmaes = {"hw-branch-instructions"};
const std::vector<std::string> configNmaes = {"hw-instructions"};
uint effectiveHeadCounter = 0u;
EXPECT_GE(EffectiveCounter(stringOut, configNmaes, effectiveHeadCounter), configNmaes.size());
t1.join();
@ -1078,7 +1077,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g, TestSize.Level1)
std::string cmdstr = "stat -p ";
cmdstr += std::to_string(tid1);
cmdstr += " -g hw-branch-instructions,hw-branch-misses"
cmdstr += " -g hw-branch-misses"
" -g hw-cpu-cycles,hw-instructions"
" -c 0 -d 3 --dumpoptions";
@ -1096,7 +1095,6 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g, TestSize.Level1)
}
const std::vector<std::string> configNmaes = {
"hw-branch-instructions",
"hw-branch-misses",
"hw-cpu-cycles",
"hw-instructions",
@ -1121,7 +1119,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g1, TestSize.Level1)
std::string cmdstr = "stat -p ";
cmdstr += std::to_string(tid1);
cmdstr += " -g hw-branch-instructions,hw-branch-misses"
cmdstr += " -g hw-instructions,hw-branch-misses"
" -c 0 -d 3 --dumpoptions";
StdoutRecord stdoutRecord;
@ -1138,7 +1136,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g1, TestSize.Level1)
}
const std::vector<std::string> configNmaes = {
"hw-branch-instructions",
"hw-instructions",
"hw-branch-misses",
};
uint effectiveHeadCounter = 0u;
@ -1237,7 +1235,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g_uk, TestSize.Level1)
std::string cmdstr = "stat -p ";
cmdstr += std::to_string(tid1);
cmdstr += " -g hw-branch-instructions:k,hw-branch-misses:k"
cmdstr += " -g hw-branch-misses:k"
" -g hw-cpu-cycles:k,hw-instructions:k"
" -c 0 -d 3 --dumpoptions";
@ -1254,7 +1252,6 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g_uk, TestSize.Level1)
printf("output:\n%s", stringOut.c_str());
}
const std::vector<std::string> configNmaes = {
"hw-branch-instructions:k",
"hw-branch-misses:k",
"hw-cpu-cycles:k",
"hw-instructions:k",
@ -1262,7 +1259,7 @@ HWTEST_F(SubCommandStatTest, TestOnSubCommand_g_uk, TestSize.Level1)
// some times 'sw-page-faults' is 0
uint effectiveHeadCounter = 0u;
EXPECT_GE(EffectiveCounter(stringOut, configNmaes, effectiveHeadCounter), configNmaes.size());
CheckGroupCoverage(stringOut, "hw-branch-instructions:k,hw-branch-misses:k");
CheckGroupCoverage(stringOut, "hw-branch-misses:k");
CheckGroupCoverage(stringOut, "hw-cpu-cycles:k,hw-instructions:k");
t1.join();
}

View File

@ -48,9 +48,15 @@ public:
void PrepareUserSymbol();
};
void VirtualRuntimeTest::SetUpTestCase() {}
void VirtualRuntimeTest::SetUpTestCase()
{
DebugLogger::GetInstance()->OpenLog(DEFAULT_UT_LOG_DIR + "VirtualRuntimeTest.txt");
}
void VirtualRuntimeTest::TearDownTestCase() {}
void VirtualRuntimeTest::TearDownTestCase()
{
DebugLogger::GetInstance()->RestoreLog();
}
void VirtualRuntimeTest::SetUp()
{

View File

@ -55,9 +55,15 @@ public:
std::string VirtualThreadTest::myFilePath_;
void VirtualThreadTest::SetUpTestCase() {}
void VirtualThreadTest::SetUpTestCase()
{
DebugLogger::GetInstance()->OpenLog(DEFAULT_UT_LOG_DIR + "VirtualThreadTest.txt");
}
void VirtualThreadTest::TearDownTestCase() {}
void VirtualThreadTest::TearDownTestCase()
{
DebugLogger::GetInstance()->RestoreLog();
}
void VirtualThreadTest::SetUp() {}

View File

@ -70,7 +70,6 @@
<option name="push" value="testdata/report/perf.disable.unwind.hiperf_example_cmd.data -> /data/test/resource/testdata/report/" src="res"/>
<option name="push" value="testdata/report/hiperf_example_cmd -> /data/test/resource/testdata/report/" src="res"/>
<option name="push" value="testdata/report/perf.dwarf.data -> /data/test/resource/testdata/report/" src="res"/>
<option name="push" value="testdata/report/perf.dwarf.data.txt -> /data/test/resource/testdata/report/" src="res"/>
<option name="push" value="testdata/perfnew.data -> /data/test/resource/testdata/" src="res"/>
<option name="push" value="testdata/report_test.data -> /data/test/resource/testdata/" src="res"/>

View File

@ -1,83 +0,0 @@
<<Hiperf Report>>
hostname: localhost
osrelease: 4.19.155+
arch: armv7l
cpudesc: ARMv7 Processor rev 5 (v7l)
cmdline: ./hiperf record -s dwarf -d 10 -o perf.dwarf.data ./hiperf_example_cmd --nowait
hiperf_workloader_cmd: ./hiperf_example_cmd
hiperf_record_time: Thu Jan 1 00:24:46 1970
Event: hw-cpu-cycles (type 0 id 0)
Samples Count: 31718
Event Count: 7050498722
Heating count comm pid tid dso func
1.98% 139942756 hiperf_example_ 385 388 /apex/com.android.runtime/lib/bionic/libc.so je_free
|- 73.69% LoopFunction(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >, Option const&)
CallStack10(int, Option const&)
CallStack9(int, Option const&)
CallStack8(int, Option const&)
CallStack7(int, Option const&)
CallStack6(int, Option const&)
CallStack5(int, Option const&)
CallStack4(int, Option const&)
CallStack3(int, Option const&)
CallStack2(int, Option const&)
CallStack1(int, Option const&)
CallStack0(int, Option const&)
ExampleThread(Option const&)
void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (*)(Option const&), Option> >(void*)
__pthread_start(void*)
__start_thread
|- 12.11% __vfprintf
printf
LoopDummy(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >)
LoopFunction(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >, Option const&)
CallStack10(int, Option const&)
CallStack9(int, Option const&)
CallStack8(int, Option const&)
CallStack7(int, Option const&)
CallStack6(int, Option const&)
CallStack5(int, Option const&)
CallStack4(int, Option const&)
CallStack3(int, Option const&)
CallStack2(int, Option const&)
CallStack1(int, Option const&)
CallStack0(int, Option const&)
ExampleThread(Option const&)
void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (*)(Option const&), Option> >(void*)
__pthread_start(void*)
__start_thread
|- 7.95% /data/local/tmp/hiperf_example_cmd+0x13f3
|- 6.25% hiperf_example_@0x7b1e0bcb
1.74% 122711258 hiperf_example_ 385 388 /data/local/tmp/hiperf_example_cmd LoopFunction(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >, Option const&)
|- 97.99% CallStack10(int, Option const&)
CallStack9(int, Option const&)
CallStack8(int, Option const&)
CallStack7(int, Option const&)
CallStack6(int, Option const&)
CallStack5(int, Option const&)
CallStack4(int, Option const&)
CallStack3(int, Option const&)
CallStack2(int, Option const&)
CallStack1(int, Option const&)
CallStack0(int, Option const&)
ExampleThread(Option const&)
void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (*)(Option const&), Option> >(void*)
__pthread_start(void*)
__start_thread
|- 2.01% LoopFunction(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >, Option const&)
CallStack10(int, Option const&)
CallStack9(int, Option const&)
CallStack8(int, Option const&)
CallStack7(int, Option const&)
CallStack6(int, Option const&)
CallStack5(int, Option const&)
CallStack4(int, Option const&)
CallStack3(int, Option const&)
CallStack2(int, Option const&)
CallStack1(int, Option const&)
CallStack0(int, Option const&)
ExampleThread(Option const&)
void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (*)(Option const&), Option> >(void*)
__pthread_start(void*)
__start_thread

View File

@ -20,6 +20,7 @@ void TestGlobalChildFunction()
{
static volatile int gTestGlobalCounter {0};
std::string gTestString = std::to_string(gTestGlobalCounter++);
printf(gTestString.c_str());
}
void TestGlobalParentFunction()