1 /**
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "guard_driver.h"
17
18 #include "abc2program_compiler.h"
19 #include "assembly-emitter.h"
20 #include "program_dump.h"
21 #include "utils/logger.h"
22
23 #include "configs/guard_context.h"
24 #include "guard4program.h"
25 #include "util/assert_util.h"
26
27 namespace {
28 constexpr std::string_view TAG = "[Guard_Driver]";
29
Dump(const panda::pandasm::Program & program,const std::string & paFilePath)30 void Dump(const panda::pandasm::Program &program, const std::string &paFilePath)
31 {
32 std::ofstream ofs;
33 ofs.open(paFilePath, std::ios::trunc | std::ios::out);
34 panda::abc2program::PandasmProgramDumper dumper;
35 dumper.Dump(ofs, program);
36 ofs.close();
37 }
38 } // namespace
39
Run(int argc,const char ** argv)40 void panda::guard::GuardDriver::Run(int argc, const char **argv)
41 {
42 const auto context = GuardContext::GetInstance();
43 context->Init(argc, argv);
44 LOG(INFO, PANDAGUARD) << TAG << "guard context init success";
45
46 auto options = context->GetGuardOptions();
47 if (options->DisableObfuscation()) {
48 LOG(INFO, PANDAGUARD) << TAG << "obfuscation is disabled";
49 return;
50 }
51
52 abc2program::Abc2ProgramCompiler compiler;
53 bool status = compiler.OpenAbcFile(options->GetAbcFilePath());
54 PANDA_GUARD_ASSERT_PRINT(!status, TAG, ErrorCode::GENERIC_ERROR,
55 "abc to program, open abc file failed" << options->GetAbcFilePath());
56
57 auto program = std::move(*compiler.CompileAbcFile());
58 LOG(INFO, PANDAGUARD) << TAG << "abc to program success";
59
60 context->CreateGraphContext(compiler.GetAbcFile());
61
62 ProgramGuard::GuardProgram(program);
63 LOG(INFO, PANDAGUARD) << TAG << "guard for program success";
64
65 if (context->IsDebugMode() && !options->GetObfPaFilePath().empty()) {
66 Dump(program, options->GetObfPaFilePath());
67 LOG(INFO, PANDAGUARD) << TAG << "program to pa success";
68 }
69
70 status = pandasm::AsmEmitter::Emit(options->GetObfAbcFilePath(), program, nullptr, nullptr, true, nullptr,
71 options->GetTargetApiVersion(), options->GetTargetApiSubVersion());
72 PANDA_GUARD_ASSERT_PRINT(!status, TAG, ErrorCode::GENERIC_ERROR,
73 "program to abc failed" << pandasm::AsmEmitter::GetLastError());
74 LOG(INFO, PANDAGUARD) << TAG << "program to abc success";
75
76 context->Finalize();
77 }
78