xref: /aosp_15_r20/art/libdexfile/dex/descriptors_names.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "descriptors_names.h"
18 
19 #include <algorithm>
20 
21 #include "android-base/stringprintf.h"
22 #include "android-base/strings.h"
23 
24 #include "base/macros.h"
25 #include "dex/utf-inl.h"
26 
27 namespace art {
28 
29 using android::base::StringAppendF;
30 
AppendPrettyDescriptor(const char * descriptor,std::string * result)31 void AppendPrettyDescriptor(const char* descriptor, std::string* result) {
32   // Count the number of '['s to get the dimensionality.
33   const char* c = descriptor;
34   size_t dim = 0;
35   while (*c == '[') {
36     dim++;
37     c++;
38   }
39 
40   // Reference or primitive?
41   if (*c == 'L') {
42     // "[[La/b/C;" -> "a.b.C[][]".
43     std::string_view stripped = std::string_view(c + 1);  // Skip the 'L'...
44     if (stripped.ends_with(';')) {
45       stripped.remove_suffix(1u);  // ...and remove the semicolon.
46     }
47     // At this point, `stripped` is of the form "fully/qualified/Type".
48     // Append it to the `*result` and replace all '/'s with '.' in place.
49     size_t old_size = result->size();
50     *result += stripped;
51     std::replace(result->begin() + old_size, result->end(), '/', '.');
52   } else {
53     // "[[B" -> "byte[][]".
54     std::string_view pretty_primitive;
55     switch (*c) {
56       case 'B':
57         pretty_primitive = "byte";
58         break;
59       case 'C':
60         pretty_primitive = "char";
61         break;
62       case 'D':
63         pretty_primitive = "double";
64         break;
65       case 'F':
66         pretty_primitive = "float";
67         break;
68       case 'I':
69         pretty_primitive = "int";
70         break;
71       case 'J':
72         pretty_primitive = "long";
73         break;
74       case 'S':
75         pretty_primitive = "short";
76         break;
77       case 'Z':
78         pretty_primitive = "boolean";
79         break;
80       case 'V':
81         pretty_primitive = "void";
82         break;  // Used when decoding return types.
83       default: result->append(descriptor); return;
84     }
85     result->append(pretty_primitive);
86   }
87 
88   // Finally, add 'dim' "[]" pairs:
89   for (size_t i = 0; i < dim; ++i) {
90     result->append("[]");
91   }
92 }
93 
PrettyDescriptor(const char * descriptor)94 std::string PrettyDescriptor(const char* descriptor) {
95   std::string result;
96   AppendPrettyDescriptor(descriptor, &result);
97   return result;
98 }
99 
InversePrettyDescriptor(const std::string & pretty_descriptor)100 std::string InversePrettyDescriptor(const std::string& pretty_descriptor) {
101   std::string result;
102 
103   // Used to determine the length of the descriptor without trailing "[]"s.
104   size_t l = pretty_descriptor.length();
105 
106   // Determine dimensionality, and append the necessary leading '['s.
107   size_t dim = 0;
108   size_t pos = 0;
109   static const std::string array_indicator = "[]";
110   while ((pos = pretty_descriptor.find(array_indicator, pos)) != std::string::npos) {
111     if (dim == 0) {
112       l = pos;
113     }
114     ++dim;
115     pos += array_indicator.length();
116   }
117   for (size_t i = 0; i < dim; ++i) {
118     result += '[';
119   }
120 
121   // temp_descriptor is now in the form of "some.pretty.Type" or "primitive".
122   std::string temp_descriptor(pretty_descriptor, 0, l);
123   if (temp_descriptor == "byte") {
124     result += 'B';
125   } else if (temp_descriptor == "char") {
126     result += 'C';
127   } else if (temp_descriptor == "double") {
128     result += 'D';
129   } else if (temp_descriptor == "float") {
130     result += 'F';
131   } else if (temp_descriptor == "int") {
132     result += 'I';
133   } else if (temp_descriptor == "long") {
134     result += 'J';
135   } else if (temp_descriptor == "short") {
136     result += 'S';
137   } else if (temp_descriptor == "boolean") {
138     result += 'Z';
139   } else if (temp_descriptor == "void") {
140     result += 'V';
141   } else {
142     result += 'L';
143     std::replace(temp_descriptor.begin(), temp_descriptor.end(), '.', '/');
144     result += temp_descriptor;
145     result += ';';
146   }
147   return result;
148 }
149 
GetJniShortName(const std::string & class_descriptor,const std::string & method)150 std::string GetJniShortName(const std::string& class_descriptor, const std::string& method) {
151   // Remove the leading 'L' and trailing ';'...
152   std::string class_name(class_descriptor);
153   CHECK_EQ(class_name[0], 'L') << class_name;
154   CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
155   class_name.erase(0, 1);
156   class_name.erase(class_name.size() - 1, 1);
157 
158   std::string short_name;
159   short_name += "Java_";
160   short_name += MangleForJni(class_name);
161   short_name += "_";
162   short_name += MangleForJni(method);
163   return short_name;
164 }
165 
166 // See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
MangleForJni(const std::string & s)167 std::string MangleForJni(const std::string& s) {
168   std::string result;
169   size_t char_count = CountModifiedUtf8Chars(s.c_str());
170   const char* cp = &s[0];
171   for (size_t i = 0; i < char_count; ++i) {
172     uint32_t ch = GetUtf16FromUtf8(&cp);
173     if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
174       result.push_back(ch);
175     } else if (ch == '.' || ch == '/') {
176       result += "_";
177     } else if (ch == '_') {
178       result += "_1";
179     } else if (ch == ';') {
180       result += "_2";
181     } else if (ch == '[') {
182       result += "_3";
183     } else {
184       const uint16_t leading = GetLeadingUtf16Char(ch);
185       const uint32_t trailing = GetTrailingUtf16Char(ch);
186 
187       StringAppendF(&result, "_0%04x", leading);
188       if (trailing != 0) {
189         StringAppendF(&result, "_0%04x", trailing);
190       }
191     }
192   }
193   return result;
194 }
195 
DotToDescriptor(const char * class_name)196 std::string DotToDescriptor(const char* class_name) {
197   std::string descriptor(class_name);
198   std::replace(descriptor.begin(), descriptor.end(), '.', '/');
199   if (descriptor.length() > 0 && descriptor[0] != '[') {
200     descriptor = "L" + descriptor + ";";
201   }
202   return descriptor;
203 }
204 
DescriptorToDot(const char * descriptor)205 std::string DescriptorToDot(const char* descriptor) {
206   size_t length = strlen(descriptor);
207   if (length > 1) {
208     if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
209       // Descriptors have the leading 'L' and trailing ';' stripped.
210       std::string result(descriptor + 1, length - 2);
211       std::replace(result.begin(), result.end(), '/', '.');
212       return result;
213     } else {
214       // For arrays the 'L' and ';' remain intact.
215       std::string result(descriptor);
216       std::replace(result.begin(), result.end(), '/', '.');
217       return result;
218     }
219   }
220   // Do nothing for non-class/array descriptors.
221   return descriptor;
222 }
223 
DescriptorToName(const char * descriptor)224 std::string DescriptorToName(const char* descriptor) {
225   size_t length = strlen(descriptor);
226   if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
227     std::string result(descriptor + 1, length - 2);
228     return result;
229   }
230   return descriptor;
231 }
232 
233 // Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
234 static constexpr uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
235   0x00000000,  // 00..1f low control characters; nothing valid
236   0x03ff2011,  // 20..3f space, digits and symbols; valid: ' ', '0'..'9', '$', '-'
237   0x87fffffe,  // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
238   0x07fffffe   // 60..7f lowercase etc.; valid: 'a'..'z'
239 };
240 
241 // Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
242 COLD_ATTR
IsValidPartOfMemberNameUtf8Slow(const char ** pUtf8Ptr)243 static bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
244   /*
245    * It's a multibyte encoded character. Decode it and analyze. We
246    * accept anything that isn't:
247    *   - an improperly encoded low value
248    *   - an improper surrogate pair
249    *   - an encoded '\0'
250    *   - a C1 control character U+0080..U+009f
251    *   - a format character U+200b..U+200f, U+2028..U+202e
252    *   - a special character U+fff0..U+ffff
253    * Prior to DEX format version 040, we also excluded some of the Unicode
254    * space characters:
255    *   - U+00a0, U+2000..U+200a, U+202f
256    * This is all specified in the dex format document.
257    */
258 
259   const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
260   const uint16_t leading = GetLeadingUtf16Char(pair);
261 
262   // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
263   // No further checks are necessary because 4 byte sequences span code
264   // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
265   // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
266   // the surrogate halves are valid and well formed in this instance.
267   if (GetTrailingUtf16Char(pair) != 0) {
268     return true;
269   }
270 
271 
272   // We've encountered a one, two or three byte UTF-8 sequence. The
273   // three byte UTF-8 sequence could be one half of a surrogate pair.
274   switch (leading >> 8) {
275     case 0x00:
276       // It's in the range that has C1 control characters.
277       return (leading >= 0x00a0);
278     case 0xd8:
279     case 0xd9:
280     case 0xda:
281     case 0xdb:
282       {
283         // We found a three byte sequence encoding one half of a surrogate.
284         // Look for the other half.
285         const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
286         const uint16_t trailing = GetLeadingUtf16Char(pair2);
287 
288         return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
289       }
290     case 0xdc:
291     case 0xdd:
292     case 0xde:
293     case 0xdf:
294       // It's a trailing surrogate, which is not valid at this point.
295       return false;
296     case 0x20:
297     case 0xff:
298       // It's in the range that has format characters and specials.
299       switch (leading & 0xfff8) {
300         case 0x2008:
301           return (leading <= 0x200a);
302         case 0x2028:
303           return (leading == 0x202f);
304         case 0xfff0:
305         case 0xfff8:
306           return false;
307       }
308       return true;
309     default:
310       return true;
311   }
312 }
313 
314 /* Return whether the pointed-at modified-UTF-8 encoded character is
315  * valid as part of a member name, updating the pointer to point past
316  * the consumed character. This will consume two encoded UTF-16 code
317  * points if the character is encoded as a surrogate pair. Also, if
318  * this function returns false, then the given pointer may only have
319  * been partially advanced.
320  */
321 ALWAYS_INLINE
IsValidPartOfMemberNameUtf8(const char ** pUtf8Ptr)322 static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
323   uint8_t c = (uint8_t) **pUtf8Ptr;
324   if (LIKELY(c <= 0x7f)) {
325     // It's low-ascii, so check the table.
326     uint32_t wordIdx = c >> 5;
327     uint32_t bitIdx = c & 0x1f;
328     (*pUtf8Ptr)++;
329     return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
330   }
331 
332   // It's a multibyte encoded character. Call a non-inline function
333   // for the heavy lifting.
334   return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
335 }
336 
IsValidMemberName(const char * s)337 bool IsValidMemberName(const char* s) {
338   bool angle_name = false;
339 
340   switch (*s) {
341     case '\0':
342       // The empty string is not a valid name.
343       return false;
344     case '<':
345       angle_name = true;
346       s++;
347       break;
348   }
349 
350   while (true) {
351     switch (*s) {
352       case '\0':
353         return !angle_name;
354       case '>':
355         return angle_name && s[1] == '\0';
356     }
357 
358     if (!IsValidPartOfMemberNameUtf8(&s)) {
359       return false;
360     }
361   }
362 }
363 
364 enum ClassNameType { kName, kDescriptor };
365 template<ClassNameType kType, char kSeparator>
IsValidClassName(const char * s)366 static bool IsValidClassName(const char* s) {
367   int arrayCount = 0;
368   while (*s == '[') {
369     arrayCount++;
370     s++;
371   }
372 
373   if (arrayCount > 255) {
374     // Arrays may have no more than 255 dimensions.
375     return false;
376   }
377 
378   ClassNameType type = kType;
379   if (type != kDescriptor && arrayCount != 0) {
380     /*
381      * If we're looking at an array of some sort, then it doesn't
382      * matter if what is being asked for is a class name; the
383      * format looks the same as a type descriptor in that case, so
384      * treat it as such.
385      */
386     type = kDescriptor;
387   }
388 
389   if (type == kDescriptor) {
390     /*
391      * We are looking for a descriptor. Either validate it as a
392      * single-character primitive type, or continue on to check the
393      * embedded class name (bracketed by "L" and ";").
394      */
395     switch (*(s++)) {
396     case 'B':
397     case 'C':
398     case 'D':
399     case 'F':
400     case 'I':
401     case 'J':
402     case 'S':
403     case 'Z':
404       // These are all single-character descriptors for primitive types.
405       return (*s == '\0');
406     case 'V':
407       // Non-array void is valid, but you can't have an array of void.
408       return (arrayCount == 0) && (*s == '\0');
409     case 'L':
410       // Class name: Break out and continue below.
411       break;
412     default:
413       // Oddball descriptor character.
414       return false;
415     }
416   }
417 
418   /*
419    * We just consumed the 'L' that introduces a class name as part
420    * of a type descriptor, or we are looking for an unadorned class
421    * name.
422    */
423 
424   bool sepOrFirst = true;  // first character or just encountered a separator.
425   for (;;) {
426     uint8_t c = (uint8_t) *s;
427     switch (c) {
428     case '\0':
429       /*
430        * Premature end for a type descriptor, but valid for
431        * a class name as long as we haven't encountered an
432        * empty component (including the degenerate case of
433        * the empty string "").
434        */
435       return (type == kName) && !sepOrFirst;
436     case ';':
437       /*
438        * Invalid character for a class name, but the
439        * legitimate end of a type descriptor. In the latter
440        * case, make sure that this is the end of the string
441        * and that it doesn't end with an empty component
442        * (including the degenerate case of "L;").
443        */
444       return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
445     case '/':
446     case '.':
447       if (c != kSeparator) {
448         // The wrong separator character.
449         return false;
450       }
451       if (sepOrFirst) {
452         // Separator at start or two separators in a row.
453         return false;
454       }
455       sepOrFirst = true;
456       s++;
457       break;
458     default:
459       if (!IsValidPartOfMemberNameUtf8(&s)) {
460         return false;
461       }
462       sepOrFirst = false;
463       break;
464     }
465   }
466 }
467 
IsValidBinaryClassName(const char * s)468 bool IsValidBinaryClassName(const char* s) {
469   return IsValidClassName<kName, '.'>(s);
470 }
471 
IsValidJniClassName(const char * s)472 bool IsValidJniClassName(const char* s) {
473   return IsValidClassName<kName, '/'>(s);
474 }
475 
IsValidDescriptor(const char * s)476 bool IsValidDescriptor(const char* s) {
477   return IsValidClassName<kDescriptor, '/'>(s);
478 }
479 
PrettyDescriptor(Primitive::Type type)480 std::string PrettyDescriptor(Primitive::Type type) {
481   return PrettyDescriptor(Primitive::Descriptor(type));
482 }
483 
484 }  // namespace art
485