1 /*
2 * Copyright (c) 2021-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 "frameworks/bridge/common/utils/source_map.h"
17
18 #include "base/log/log_wrapper.h"
19
20 namespace OHOS::Ace::Framework {
21
22 const char SOURCES[] = "sources";
23 const char NAMES[] = "names";
24 const char MAPPINGS[] = "mappings";
25 const char FILE[] = "file";
26 const char NAMEMAP[] = "nameMap";
27 const char SOURCE_CONTENT[] = "sourceContent";
28 const char SOURCE_ROOT[] = "sourceRoot";
29 const char DELIMITER_COMMA = ',';
30 const char DELIMITER_SEMICOLON = ';';
31 const char DOUBLE_SLASH = '\\';
32 const char WEBPACK[] = "webpack:///";
33 constexpr int32_t AFTER_COLUMN = 0;
34 constexpr int32_t SOURCES_VAL = 1;
35 constexpr int32_t BEFORE_ROW = 2;
36 constexpr int32_t BEFORE_COLUMN = 3;
37 constexpr int32_t NAMES_VAL = 4;
38
Find(int32_t row,int32_t col,bool isColPrecise)39 MappingInfo RevSourceMap::Find(int32_t row, int32_t col, bool isColPrecise)
40 {
41 if (row < 1 || col < 1 || afterPos_.empty()) {
42 return MappingInfo {};
43 }
44 row--;
45 col--;
46 // binary search
47 int32_t left = 0;
48 int32_t right = static_cast<int32_t>(afterPos_.size()) - 1;
49 int32_t res = 0;
50 bool isRightBig = false;
51 if (row > afterPos_[afterPos_.size() - 1].afterRow) {
52 return MappingInfo { row + 1, col + 1, files_[0] };
53 }
54 while (right - left >= 0) {
55 int32_t mid = (right + left) / 2;
56 if ((afterPos_[mid].afterRow == row && afterPos_[mid].afterColumn > col) || afterPos_[mid].afterRow > row) {
57 right = mid - 1;
58 isRightBig = true;
59 } else {
60 res = mid;
61 left = mid + 1;
62 }
63 }
64
65 /*
66 * real:[56:7]->[250:21]
67 * [row:col]->[afterRow:afterColumn]
68 * 0:[53:14]->[237:77]
69 * 1:[53:14]->[237:78]
70 * 2:[56:7]->[250:39]
71 * 3:[56:14]->[250:40]
72 */
73 if (!isColPrecise && isRightBig && right > 0 && afterPos_[right].afterRow < row) {
74 res = right + 1;
75 }
76
77 int32_t sourcesSize = static_cast<int32_t>(sources_.size());
78 if (afterPos_[res].sourcesVal < 0 || afterPos_[res].sourcesVal >= sourcesSize) {
79 return MappingInfo {};
80 }
81 std::string sources = sources_[afterPos_[res].sourcesVal];
82 auto pos = sources.find(WEBPACK);
83 if (pos != std::string::npos) {
84 sources.replace(pos, sizeof(WEBPACK) - 1, "");
85 }
86
87 return MappingInfo {
88 .row = afterPos_[res].beforeRow + 1,
89 .col = afterPos_[res].beforeColumn + 1,
90 .sources = sources,
91 };
92 }
93
GetOriginalNames(const std::string & sourceCode,uint32_t & errorPos) const94 std::string RevSourceMap::GetOriginalNames(const std::string& sourceCode, uint32_t& errorPos) const
95 {
96 if (sourceCode.empty() || sourceCode.find("SourceCode:\n") == std::string::npos) {
97 return sourceCode;
98 }
99 if (nameMap_.size() % 2 != 0) {
100 return sourceCode;
101 }
102 std::string jsCode = sourceCode;
103 int32_t posDiff = 0;
104 for (uint32_t i = 0; i < nameMap_.size(); i += 2) {
105 auto found = jsCode.find(nameMap_[i]);
106 while (found != std::string::npos) {
107 // nameMap_[i + 1] is the original name of nameMap_[i]
108 jsCode.replace(found, nameMap_[i].length(), nameMap_[i + 1]);
109 if (static_cast<uint32_t>(found) < errorPos) {
110 // sum the errorPos differences to adjust position of ^
111 posDiff += static_cast<int32_t>(nameMap_[i + 1].length()) - static_cast<int32_t>(nameMap_[i].length());
112 }
113 // In case there are other variable names not replaced.
114 // example:var e = process.a.b + _ohos_process_1.a.b;
115 found = jsCode.find(nameMap_[i], found + nameMap_[i + 1].length());
116 }
117 }
118 auto lineBreakPos = jsCode.rfind('\n', jsCode.length() - 2);
119 if (lineBreakPos == std::string::npos) {
120 return jsCode;
121 }
122 // adjust position of ^ in dump file
123 if (posDiff < 0) {
124 int32_t flagPos = static_cast<int32_t>(lineBreakPos) + static_cast<int32_t>(errorPos);
125 if (lineBreakPos > 0 && errorPos > 0 && flagPos < 0) {
126 LOGW("Add overflow of sourceCode.");
127 return jsCode;
128 }
129 if (flagPos < static_cast<int32_t>(jsCode.length()) && jsCode[flagPos] == '^' && flagPos + posDiff - 1 > 0) {
130 jsCode.erase(flagPos + posDiff - 1, -posDiff);
131 }
132 } else if (posDiff > 0) {
133 if (lineBreakPos + 1 < jsCode.length() - 1) {
134 jsCode.insert(lineBreakPos + 1, posDiff, ' ');
135 }
136 }
137 return jsCode;
138 }
139
ExtractKeyInfo(const std::string & sourceMap,std::vector<std::string> & sourceKeyInfo)140 void RevSourceMap::ExtractKeyInfo(const std::string& sourceMap, std::vector<std::string>& sourceKeyInfo)
141 {
142 uint32_t cnt = 0;
143 std::string tempStr;
144 for (uint32_t i = 0; i < sourceMap.size(); i++) {
145 // reslove json file
146 if (sourceMap[i] == DOUBLE_SLASH) {
147 i++;
148 tempStr += sourceMap[i];
149 continue;
150 }
151 // cnt is used to represent a pair of double quotation marks: ""
152 if (sourceMap[i] == '"') {
153 cnt++;
154 }
155 if (cnt == 2) {
156 sourceKeyInfo.push_back(tempStr);
157 tempStr = "";
158 cnt = 0;
159 } else if (cnt == 1) {
160 if (sourceMap[i] != '"') {
161 tempStr += sourceMap[i];
162 }
163 }
164 }
165 }
166
Init(const std::string & sourceMap)167 void RevSourceMap::Init(const std::string& sourceMap)
168 {
169 std::vector<std::string> sourceKeyInfo;
170 std::string mark = "";
171
172 ExtractKeyInfo(sourceMap, sourceKeyInfo);
173
174 // first: find the key info and record the temp key info
175 // second: add the detail into the keyinfo
176 for (auto keyInfo : sourceKeyInfo) {
177 if (keyInfo == SOURCES || keyInfo == NAMES || keyInfo == MAPPINGS || keyInfo == FILE ||
178 keyInfo == SOURCE_CONTENT || keyInfo == SOURCE_ROOT || keyInfo == NAMEMAP) {
179 // record the temp key info
180 mark = keyInfo;
181 } else if (mark == SOURCES) {
182 sources_.push_back(keyInfo);
183 } else if (mark == NAMES) {
184 names_.push_back(keyInfo);
185 } else if (mark == MAPPINGS) {
186 mappings_.push_back(keyInfo);
187 } else if (mark == FILE) {
188 files_.push_back(keyInfo);
189 } else if (mark == NAMEMAP) {
190 nameMap_.push_back(keyInfo);
191 } else {
192 continue;
193 }
194 }
195
196 if (mappings_.empty()) {
197 LOGW("Decode sourcemap fail, mapping: %{public}s is empty", sourceMap.c_str());
198 return;
199 }
200
201 // transform to vector for mapping easily
202 mappings_ = HandleMappings(mappings_[0]);
203
204 // the first bit: the column after transferring.
205 // the second bit: the source file.
206 // the third bit: the row before transferring.
207 // the fourth bit: the column before transferring.
208 // the fifth bit: the variable name.
209 for (const auto& mapping : mappings_) {
210 if (mapping == ";") {
211 // plus a line for each semicolon
212 nowPos_.afterRow++, nowPos_.afterColumn = 0;
213 continue;
214 }
215 // decode each mapping ";QAABC"
216 std::vector<int32_t> ans;
217 if (!VlqRevCode(mapping, ans)) {
218 return;
219 }
220 if (ans.size() == 0) {
221 LOGW("Decode sourcemap fail, mapping: %{public}s is empty", mapping.c_str());
222 break;
223 }
224 if (ans.size() == 1) {
225 nowPos_.afterColumn += ans[AFTER_COLUMN];
226 continue;
227 }
228 // after decode, assgin each value to the position
229 nowPos_.afterColumn += ans[AFTER_COLUMN];
230 nowPos_.sourcesVal += ans[SOURCES_VAL];
231 nowPos_.beforeRow += ans[BEFORE_ROW];
232 nowPos_.beforeColumn += ans[BEFORE_COLUMN];
233 if (ans.size() == 5) {
234 nowPos_.namesVal += ans[NAMES_VAL];
235 }
236 afterPos_.push_back({ nowPos_.beforeRow, nowPos_.beforeColumn, nowPos_.afterRow, nowPos_.afterColumn,
237 nowPos_.sourcesVal, nowPos_.namesVal });
238 }
239 mappings_.clear();
240 mappings_.shrink_to_fit();
241 sourceKeyInfo.clear();
242 sourceKeyInfo.shrink_to_fit();
243 };
244
MergeInit(const std::string & sourceMap,RefPtr<RevSourceMap> & curMapData)245 void RevSourceMap::MergeInit(const std::string& sourceMap,
246 RefPtr<RevSourceMap>& curMapData)
247 {
248 std::vector<std::string> sourceKey;
249 std::string mark = "";
250 ExtractKeyInfo(sourceMap, sourceKey);
251 for (auto sourceKeyInfo : sourceKey) {
252 if (sourceKeyInfo == SOURCES || sourceKeyInfo == NAMES ||
253 sourceKeyInfo == MAPPINGS || sourceKeyInfo == FILE ||
254 sourceKeyInfo == SOURCE_CONTENT || sourceKeyInfo == SOURCE_ROOT) {
255 mark = sourceKeyInfo;
256 } else if (mark == SOURCES) {
257 curMapData->sources_.push_back(sourceKeyInfo);
258 } else if (mark == NAMES) {
259 curMapData->names_.push_back(sourceKeyInfo);
260 } else if (mark == MAPPINGS) {
261 curMapData->mappings_.push_back(sourceKeyInfo);
262 } else if (mark == FILE) {
263 curMapData->files_.push_back(sourceKeyInfo);
264 } else {
265 continue;
266 }
267 }
268
269 if (curMapData->mappings_.empty()) {
270 LOGW("MergeInit decode sourcemap fail, mapping: %{public}s", sourceMap.c_str());
271 return;
272 }
273
274 // transform to vector for mapping easily
275 curMapData->mappings_ = HandleMappings(curMapData->mappings_[0]);
276
277 // the first bit: the column after transferring.
278 // the second bit: the source file.
279 // the third bit: the row before transferring.
280 // the fourth bit: the column before transferring.
281 // the fifth bit: the variable name.
282 for (const auto& mapping : curMapData->mappings_) {
283 if (mapping == ";") {
284 // plus a line for each semicolon
285 curMapData->nowPos_.afterRow++,
286 curMapData->nowPos_.afterColumn = 0;
287 continue;
288 }
289 std::vector<int32_t> ans;
290
291 if (!VlqRevCode(mapping, ans)) {
292 return;
293 }
294 if (ans.size() == 0) {
295 break;
296 }
297 if (ans.size() == 1) {
298 curMapData->nowPos_.afterColumn += ans[AFTER_COLUMN];
299 continue;
300 }
301 // after decode, assgin each value to the position
302 curMapData->nowPos_.afterColumn += ans[AFTER_COLUMN];
303 curMapData->nowPos_.sourcesVal += ans[SOURCES_VAL];
304 curMapData->nowPos_.beforeRow += ans[BEFORE_ROW];
305 curMapData->nowPos_.beforeColumn += ans[BEFORE_COLUMN];
306 if (ans.size() == 5) {
307 curMapData->nowPos_.namesVal += ans[NAMES_VAL];
308 }
309 curMapData->afterPos_.push_back({
310 curMapData->nowPos_.beforeRow,
311 curMapData->nowPos_.beforeColumn,
312 curMapData->nowPos_.afterRow,
313 curMapData->nowPos_.afterColumn,
314 curMapData->nowPos_.sourcesVal,
315 curMapData->nowPos_.namesVal
316 });
317 }
318 curMapData->mappings_.clear();
319 curMapData->mappings_.shrink_to_fit();
320 sourceKey.clear();
321 sourceKey.shrink_to_fit();
322 };
323
324
HandleMappings(const std::string & mapping)325 std::vector<std::string> RevSourceMap::HandleMappings(const std::string& mapping)
326 {
327 std::vector<std::string> keyInfo;
328 std::string tempStr;
329 for (uint32_t i = 0; i < mapping.size(); i++) {
330 if (mapping[i] == DELIMITER_COMMA) {
331 keyInfo.push_back(tempStr);
332 tempStr = "";
333 } else if (mapping[i] == DELIMITER_SEMICOLON) {
334 if (tempStr != "") {
335 keyInfo.push_back(tempStr);
336 }
337 tempStr = "";
338 keyInfo.push_back(";");
339 } else {
340 tempStr += mapping[i];
341 }
342 }
343 if (tempStr != "") {
344 keyInfo.push_back(tempStr);
345 }
346 return keyInfo;
347 };
348
Base64CharToInt(char charCode)349 uint32_t RevSourceMap::Base64CharToInt(char charCode)
350 {
351 if ('A' <= charCode && charCode <= 'Z') {
352 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
353 return charCode - 'A';
354 } else if ('a' <= charCode && charCode <= 'z') {
355 // 26 - 51: abcdefghijklmnopqrstuvwxyz
356 return charCode - 'a' + 26;
357 } else if ('0' <= charCode && charCode <= '9') {
358 // 52 - 61: 0123456789
359 return charCode - '0' + 52;
360 } else if (charCode == '+') {
361 // 62: +
362 return 62;
363 } else if (charCode == '/') {
364 // 63: /
365 return 63;
366 }
367 return 64;
368 };
369
VlqRevCode(const std::string & vStr,std::vector<int32_t> & ans)370 bool RevSourceMap::VlqRevCode(const std::string& vStr, std::vector<int32_t>& ans)
371 {
372 if (vStr.size() == 0) {
373 return false;
374 }
375 const int32_t VLQ_BASE_SHIFT = 5;
376 // binary: 100000
377 uint32_t VLQ_BASE = 1 << VLQ_BASE_SHIFT;
378 // binary: 011111
379 uint32_t VLQ_BASE_MASK = VLQ_BASE - 1;
380 // binary: 100000
381 uint32_t VLQ_CONTINUATION_BIT = VLQ_BASE;
382 uint32_t result = 0;
383 uint32_t shift = 0;
384 bool continuation = 0;
385 for (uint32_t i = 0; i < vStr.size(); i++) {
386 uint32_t digit = Base64CharToInt(vStr[i]);
387 if (digit == 64) {
388 return false;
389 }
390 continuation = digit & VLQ_CONTINUATION_BIT;
391 digit &= VLQ_BASE_MASK;
392 result += digit << shift;
393 if (continuation) {
394 shift += VLQ_BASE_SHIFT;
395 } else {
396 bool isOdd = result & 1;
397 result >>= 1;
398 ans.push_back(isOdd ? -result : result);
399 result = 0;
400 shift = 0;
401 }
402 }
403 if (continuation) {
404 return false;
405 }
406 return true;
407 };
408
409 // The function is used to prase the sourcemap of stage-model project on the previewer and will be abandoned later.
StageModeSourceMapSplit(const std::string & sourceMap,std::unordered_map<std::string,RefPtr<RevSourceMap>> & sourceMaps)410 void RevSourceMap::StageModeSourceMapSplit(const std::string& sourceMap,
411 std::unordered_map<std::string, RefPtr<RevSourceMap>>& sourceMaps)
412 {
413 size_t leftBracket = 0;
414 size_t rightBracket = 0;
415 while ((leftBracket = sourceMap.find(": {", rightBracket)) != std::string::npos) {
416 size_t urlLeft = leftBracket;
417 size_t urlRight = sourceMap.find(" \"", rightBracket) + 3;
418 if (urlRight == std::string::npos) {
419 continue;
420 }
421 std::string key = sourceMap.substr(urlRight, urlLeft - urlRight - 1);
422 rightBracket = sourceMap.find("},", leftBracket);
423 std::string value = sourceMap.substr(leftBracket, rightBracket);
424 RefPtr<RevSourceMap> curMapData = MakeRefPtr<RevSourceMap>();
425 MergeInit(value, curMapData);
426 sourceMaps.emplace(key, curMapData);
427 }
428 }
429 } // namespace OHOS::Ace::Framework
430