1 /**
2 * Copyright (c) 2022 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 "source_file.h"
17
18 #include "bytecode_instruction-inl.h"
19 #include "code_data_accessor.h"
20 #include "method_data_accessor-inl.h"
21 #include "tooling/pt_location.h"
22
23 #include <algorithm>
24 #include <cstdint>
25 #include <fstream>
26 #include <sstream>
27 #include <utility>
28
29 namespace panda::tooling::inspector {
SourceFile(size_t scriptId,const char * fileName,const panda_file::File * pandaFile,panda_file::DebugInfoExtractor debugInfo)30 SourceFile::SourceFile(size_t scriptId, const char *fileName, const panda_file::File *pandaFile,
31 panda_file::DebugInfoExtractor debugInfo)
32 : scriptId_(scriptId), fileName_(fileName), pandaFile_(pandaFile), debugInfo_(std::move(debugInfo))
33 {
34 std::stringstream buffer;
35 buffer << std::ifstream(fileName).rdbuf();
36
37 sourceCode_ = buffer.str();
38 if (!sourceCode_.empty() && sourceCode_.back() != '\n') {
39 sourceCode_.push_back('\n');
40 }
41 }
42
EnumerateLocations(size_t lineNumber,const std::function<bool (PtLocation)> & function) const43 void SourceFile::EnumerateLocations(size_t lineNumber, const std::function<bool(PtLocation)> &function) const
44 {
45 for (auto methodId : debugInfo_.GetMethodIdList()) {
46 auto &table = debugInfo_.GetLineNumberTable(methodId);
47
48 auto iter = std::lower_bound(table.begin(), table.end(), lineNumber,
49 [](auto &entry, auto line) { return entry.line - 1 < line; });
50 if (iter == table.end() || iter->line - 1 != lineNumber) {
51 continue;
52 }
53
54 uint32_t startOffset = iter->offset;
55 uint32_t endOffset = (++iter != table.end()) ? iter->offset : ~0U;
56
57 auto codeId = panda_file::MethodDataAccessor(*pandaFile_, methodId).GetCodeId();
58 if (!codeId) {
59 continue;
60 }
61
62 panda_file::CodeDataAccessor cda(*pandaFile_, *codeId);
63
64 for (auto bytecodeOffset = startOffset; bytecodeOffset < endOffset;) {
65 if (!function(PtLocation(pandaFile_->GetFilename().c_str(), methodId, bytecodeOffset))) {
66 return;
67 }
68
69 BytecodeInstruction inst(cda.GetInstructions() + bytecodeOffset);
70 if (inst.IsTerminator()) {
71 break;
72 }
73
74 bytecodeOffset += inst.GetSize();
75 }
76 }
77 }
78 } // namespace panda::tooling::inspector
79