• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019, 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 "aidl_language.h"
18 #include "aidl_typenames.h"
19 #include "logging.h"
20 
21 #include <stdlib.h>
22 #include <algorithm>
23 #include <iostream>
24 #include <limits>
25 #include <memory>
26 
27 #include <android-base/parsedouble.h>
28 #include <android-base/parseint.h>
29 #include <android-base/strings.h>
30 
31 using android::base::ConsumeSuffix;
32 using android::base::EndsWith;
33 using android::base::Join;
34 using android::base::Split;
35 using android::base::StartsWith;
36 using std::string;
37 using std::unique_ptr;
38 using std::vector;
39 
40 template <typename T>
CLZ(T x)41 constexpr int CLZ(T x) {
42   // __builtin_clz(0) is undefined
43   if (x == 0) return sizeof(T) * 8;
44   return (sizeof(T) == sizeof(uint64_t)) ? __builtin_clzl(x) : __builtin_clz(x);
45 }
46 
47 template <typename T>
48 class OverflowGuard {
49  public:
OverflowGuard(T value)50   OverflowGuard(T value) : mValue(value) {}
Overflowed() const51   bool Overflowed() const { return mOverflowed; }
52 
operator +()53   T operator+() { return +mValue; }
operator -()54   T operator-() {
55     if (isMin()) {
56       mOverflowed = true;
57       return 0;
58     }
59     return -mValue;
60   }
operator !()61   T operator!() { return !mValue; }
operator ~()62   T operator~() { return ~mValue; }
63 
operator +(T o)64   T operator+(T o) {
65     T out;
66     mOverflowed = __builtin_add_overflow(mValue, o, &out);
67     return out;
68   }
operator -(T o)69   T operator-(T o) {
70     T out;
71     mOverflowed = __builtin_sub_overflow(mValue, o, &out);
72     return out;
73   }
operator *(T o)74   T operator*(T o) {
75     T out;
76 #ifdef _WIN32
77     // ___mulodi4 not on windows https://bugs.llvm.org/show_bug.cgi?id=46669
78     // we should still get an error here from ubsan, but the nice error
79     // is needed on linux for aidl_parser_fuzzer, where we are more
80     // concerned about overflows elsewhere in the compiler in addition to
81     // those in interfaces.
82     out = mValue * o;
83 #else
84     mOverflowed = __builtin_mul_overflow(mValue, o, &out);
85 #endif
86     return out;
87   }
operator /(T o)88   T operator/(T o) {
89     if (o == 0 || (isMin() && o == -1)) {
90       mOverflowed = true;
91       return 0;
92     }
93     return static_cast<T>(mValue / o);
94   }
operator %(T o)95   T operator%(T o) {
96     if (o == 0 || (isMin() && o == -1)) {
97       mOverflowed = true;
98       return 0;
99     }
100     return static_cast<T>(mValue % o);
101   }
operator |(T o)102   T operator|(T o) { return mValue | o; }
operator ^(T o)103   T operator^(T o) { return mValue ^ o; }
operator &(T o)104   T operator&(T o) { return mValue & o; }
operator <(T o)105   T operator<(T o) { return mValue < o; }
operator >(T o)106   T operator>(T o) { return mValue > o; }
operator <=(T o)107   T operator<=(T o) { return mValue <= o; }
operator >=(T o)108   T operator>=(T o) { return mValue >= o; }
operator ==(T o)109   T operator==(T o) { return mValue == o; }
operator !=(T o)110   T operator!=(T o) { return mValue != o; }
operator >>(T o)111   T operator>>(T o) {
112     if (o < 0 || o >= static_cast<T>(sizeof(T) * 8) || mValue < 0) {
113       mOverflowed = true;
114       return 0;
115     }
116     return static_cast<T>(mValue >> o);
117   }
operator <<(T o)118   T operator<<(T o) {
119     if (o < 0 || mValue < 0 || o > CLZ(mValue) || o >= static_cast<T>(sizeof(T) * 8)) {
120       mOverflowed = true;
121       return 0;
122     }
123     return static_cast<T>(mValue << o);
124   }
operator ||(T o)125   T operator||(T o) { return mValue || o; }
operator &&(T o)126   T operator&&(T o) { return mValue && o; }
127 
128  private:
isMin()129   bool isMin() { return mValue == std::numeric_limits<T>::min(); }
130 
131   T mValue;
132   bool mOverflowed = false;
133 };
134 
135 // some compilers don't provide __builtin_add_overflow for bool
136 // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71479
137 template <>
operator +(bool o)138 bool OverflowGuard<bool>::operator+(bool o) {
139   if (mValue && o) {
140     mOverflowed = true;
141     return false;
142   }
143   return mValue || o;
144 }
145 
146 template <>
operator -(bool o)147 bool OverflowGuard<bool>::operator-(bool o) {
148   if (!mValue && o) {
149     mOverflowed = true;
150     return true;
151   }
152   return mValue && !o;
153 }
154 
155 template <>
operator *(bool o)156 bool OverflowGuard<bool>::operator*(bool o) {
157   return mValue && o;
158 }
159 
160 template <typename T>
processGuard(const OverflowGuard<T> & guard,const AidlConstantValue & context)161 bool processGuard(const OverflowGuard<T>& guard, const AidlConstantValue& context) {
162   if (guard.Overflowed()) {
163     AIDL_ERROR(context) << "Constant expression computation overflows.";
164     return false;
165   }
166   return true;
167 }
168 
169 // TODO: factor out all these macros
170 #define SHOULD_NOT_REACH() AIDL_FATAL(AIDL_LOCATION_HERE) << "Should not reach."
171 #define OPEQ(__y__) (string(op_) == string(__y__))
172 #define COMPUTE_UNARY(T, __op__)         \
173   if (op == string(#__op__)) {           \
174     OverflowGuard<T> guard(val);         \
175     *out = __op__ guard;                 \
176     return processGuard(guard, context); \
177   }
178 #define COMPUTE_BINARY(T, __op__)        \
179   if (op == string(#__op__)) {           \
180     OverflowGuard<T> guard(lval);        \
181     *out = guard __op__ rval;            \
182     return processGuard(guard, context); \
183   }
184 #define OP_IS_BIN_ARITHMETIC (OPEQ("+") || OPEQ("-") || OPEQ("*") || OPEQ("/") || OPEQ("%"))
185 #define OP_IS_BIN_BITFLIP (OPEQ("|") || OPEQ("^") || OPEQ("&"))
186 #define OP_IS_BIN_COMP \
187   (OPEQ("<") || OPEQ(">") || OPEQ("<=") || OPEQ(">=") || OPEQ("==") || OPEQ("!="))
188 #define OP_IS_BIN_SHIFT (OPEQ(">>") || OPEQ("<<"))
189 #define OP_IS_BIN_LOGICAL (OPEQ("||") || OPEQ("&&"))
190 
191 // NOLINT to suppress missing parentheses warnings about __def__.
192 #define SWITCH_KIND(__cond__, __action__, __def__) \
193   switch (__cond__) {                              \
194     case Type::BOOLEAN:                            \
195       __action__(bool);                            \
196     case Type::INT8:                               \
197       __action__(int8_t);                          \
198     case Type::INT32:                              \
199       __action__(int32_t);                         \
200     case Type::INT64:                              \
201       __action__(int64_t);                         \
202     default:                                       \
203       __def__; /* NOLINT */                        \
204   }
205 
206 template <class T>
handleUnary(const AidlConstantValue & context,const string & op,T val,int64_t * out)207 bool handleUnary(const AidlConstantValue& context, const string& op, T val, int64_t* out) {
208   COMPUTE_UNARY(T, +)
209   COMPUTE_UNARY(T, -)
210   COMPUTE_UNARY(T, !)
211   COMPUTE_UNARY(T, ~)
212   AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
213   return false;
214 }
215 template <>
handleUnary(const AidlConstantValue & context,const string & op,bool val,int64_t * out)216 bool handleUnary<bool>(const AidlConstantValue& context, const string& op, bool val, int64_t* out) {
217   COMPUTE_UNARY(bool, +)
218   COMPUTE_UNARY(bool, -)
219   COMPUTE_UNARY(bool, !)
220 
221   if (op == "~") {
222     AIDL_ERROR(context) << "Bitwise negation of a boolean expression is always true.";
223     return false;
224   }
225   AIDL_FATAL(context) << "Could not handleUnary for " << op << " " << val;
226   return false;
227 }
228 
229 template <class T>
handleBinaryCommon(const AidlConstantValue & context,T lval,const string & op,T rval,int64_t * out)230 bool handleBinaryCommon(const AidlConstantValue& context, T lval, const string& op, T rval,
231                         int64_t* out) {
232   COMPUTE_BINARY(T, +)
233   COMPUTE_BINARY(T, -)
234   COMPUTE_BINARY(T, *)
235   COMPUTE_BINARY(T, /)
236   COMPUTE_BINARY(T, %)
237   COMPUTE_BINARY(T, |)
238   COMPUTE_BINARY(T, ^)
239   COMPUTE_BINARY(T, &)
240   // comparison operators: return 0 or 1 by nature.
241   COMPUTE_BINARY(T, ==)
242   COMPUTE_BINARY(T, !=)
243   COMPUTE_BINARY(T, <)
244   COMPUTE_BINARY(T, >)
245   COMPUTE_BINARY(T, <=)
246   COMPUTE_BINARY(T, >=)
247 
248   AIDL_FATAL(context) << "Could not handleBinaryCommon for " << lval << " " << op << " " << rval;
249   return false;
250 }
251 
252 template <class T>
handleShift(const AidlConstantValue & context,T lval,const string & op,T rval,int64_t * out)253 bool handleShift(const AidlConstantValue& context, T lval, const string& op, T rval, int64_t* out) {
254   // just cast rval to int64_t and it should fit.
255   COMPUTE_BINARY(T, >>)
256   COMPUTE_BINARY(T, <<)
257 
258   AIDL_FATAL(context) << "Could not handleShift for " << lval << " " << op << " " << rval;
259   return false;
260 }
261 
handleLogical(const AidlConstantValue & context,bool lval,const string & op,bool rval,int64_t * out)262 bool handleLogical(const AidlConstantValue& context, bool lval, const string& op, bool rval,
263                    int64_t* out) {
264   COMPUTE_BINARY(bool, ||);
265   COMPUTE_BINARY(bool, &&);
266 
267   AIDL_FATAL(context) << "Could not handleLogical for " << lval << " " << op << " " << rval;
268   return false;
269 }
270 
isValidLiteralChar(char c)271 static bool isValidLiteralChar(char c) {
272   return !(c <= 0x1f ||  // control characters are < 0x20
273            c >= 0x7f ||  // DEL is 0x7f
274            c == '\\');   // Disallow backslashes for future proofing.
275 }
276 
PrintCharLiteral(char c)277 static std::string PrintCharLiteral(char c) {
278   std::ostringstream os;
279   switch (c) {
280     case '\0':
281       os << "\\0";
282       break;
283     case '\'':
284       os << "\\'";
285       break;
286     case '\\':
287       os << "\\\\";
288       break;
289     case '\a':
290       os << "\\a";
291       break;
292     case '\b':
293       os << "\\b";
294       break;
295     case '\f':
296       os << "\\f";
297       break;
298     case '\n':
299       os << "\\n";
300       break;
301     case '\r':
302       os << "\\r";
303       break;
304     case '\t':
305       os << "\\t";
306       break;
307     case '\v':
308       os << "\\v";
309       break;
310     default:
311       if (std::isprint(static_cast<unsigned char>(c))) {
312         os << c;
313       } else {
314         os << "\\x" << std::hex << std::uppercase << static_cast<int>(c);
315       }
316   }
317   return os.str();
318 }
319 
ParseFloating(std::string_view sv,double * parsed)320 bool ParseFloating(std::string_view sv, double* parsed) {
321   // float literal should be parsed successfully.
322   android::base::ConsumeSuffix(&sv, "f");
323   return android::base::ParseDouble(std::string(sv).data(), parsed);
324 }
325 
ParseFloating(std::string_view sv,float * parsed)326 bool ParseFloating(std::string_view sv, float* parsed) {
327   // we only care about float literal (with suffix "f").
328   if (!android::base::ConsumeSuffix(&sv, "f")) {
329     return false;
330   }
331   return android::base::ParseFloat(std::string(sv).data(), parsed);
332 }
333 
IsCompatibleType(Type type,const string & op)334 bool AidlUnaryConstExpression::IsCompatibleType(Type type, const string& op) {
335   // Verify the unary type here
336   switch (type) {
337     case Type::BOOLEAN:  // fall-through
338     case Type::INT8:     // fall-through
339     case Type::INT32:    // fall-through
340     case Type::INT64:
341       return true;
342     case Type::FLOATING:
343       return (op == "+" || op == "-");
344     default:
345       return false;
346   }
347 }
348 
AreCompatibleOperandTypes(Type t1,Type t2)349 bool AidlBinaryConstExpression::AreCompatibleOperandTypes(Type t1, Type t2) {
350   switch (t1) {
351     case Type::ARRAY:
352       if (t2 == Type::ARRAY) {
353         return true;
354       }
355       break;
356     case Type::STRING:
357       if (t2 == Type::STRING) {
358         return true;
359       }
360       break;
361     case Type::FLOATING:
362       // TODO: b/313951203, check op for supported floating operands (+ - * / < > <= >= == !=)
363       return false;
364     case Type::BOOLEAN:  // fall-through
365     case Type::INT8:     // fall-through
366     case Type::INT32:    // fall-through
367     case Type::INT64:
368       switch (t2) {
369         case Type::BOOLEAN:  // fall-through
370         case Type::INT8:     // fall-through
371         case Type::INT32:    // fall-through
372         case Type::INT64:
373           return true;
374           break;
375         default:
376           break;
377       }
378       break;
379     default:
380       break;
381   }
382 
383   return false;
384 }
385 
AreCompatibleArrayTypes(Type t1,Type t2)386 bool AidlBinaryConstExpression::AreCompatibleArrayTypes(Type t1, Type t2) {
387   // treat floating type differently here, because float array is supported but not operand
388   if (t1 == Type::FLOATING && t2 == Type::FLOATING) return true;
389 
390   return AreCompatibleOperandTypes(t1, t2);
391 }
392 
393 // Returns the promoted kind for both operands
UsualArithmeticConversion(Type left,Type right)394 AidlConstantValue::Type AidlBinaryConstExpression::UsualArithmeticConversion(Type left,
395                                                                              Type right) {
396   // These are handled as special cases
397   // TODO: b/313951203, remove this after support string and floating operands
398   AIDL_FATAL_IF(left == Type::STRING || right == Type::STRING, AIDL_LOCATION_HERE);
399   AIDL_FATAL_IF(left == Type::FLOATING || right == Type::FLOATING, AIDL_LOCATION_HERE);
400 
401   // Kinds in concern: bool, (u)int[8|32|64]
402   if (left == right) return left;  // easy case
403   if (left == Type::BOOLEAN) return right;
404   if (right == Type::BOOLEAN) return left;
405 
406   return left < right ? right : left;
407 }
408 
409 // Returns the promoted integral type where INT32 is the smallest type
IntegralPromotion(Type in)410 AidlConstantValue::Type AidlBinaryConstExpression::IntegralPromotion(Type in) {
411   return (Type::INT32 < in) ? in : Type::INT32;
412 }
413 
Default(const AidlTypeSpecifier & specifier)414 AidlConstantValue* AidlConstantValue::Default(const AidlTypeSpecifier& specifier) {
415   AidlLocation location = specifier.GetLocation();
416 
417   // allocation of int[0] is a bit wasteful in Java
418   if (specifier.IsArray()) {
419     return nullptr;
420   }
421 
422   const std::string name = specifier.GetName();
423   if (name == "boolean") {
424     return Boolean(location, false);
425   }
426   if (name == "char") {
427     return Character(location, "'\\0'");  // literal to be used in backends
428   }
429   if (name == "byte" || name == "int" || name == "long") {
430     return Integral(location, "0");
431   }
432   if (name == "float") {
433     return Floating(location, "0.0f");
434   }
435   if (name == "double") {
436     return Floating(location, "0.0");
437   }
438   return nullptr;
439 }
440 
Boolean(const AidlLocation & location,bool value)441 AidlConstantValue* AidlConstantValue::Boolean(const AidlLocation& location, bool value) {
442   return new AidlConstantValue(location, Type::BOOLEAN, value ? "true" : "false");
443 }
444 
Character(const AidlLocation & location,const std::string & value)445 AidlConstantValue* AidlConstantValue::Character(const AidlLocation& location,
446                                                 const std::string& value) {
447   static const char* kZeroString = "'\\0'";
448 
449   // We should have better supports for escapes in the future, but for now
450   // allow only what is needed for defaults.
451   if (value != kZeroString) {
452     AIDL_FATAL_IF(value.size() != 3 || value[0] != '\'' || value[2] != '\'', location) << value;
453 
454     if (!isValidLiteralChar(value[1])) {
455       AIDL_ERROR(location) << "Invalid character literal " << PrintCharLiteral(value[1]);
456       return new AidlConstantValue(location, Type::ERROR, value);
457     }
458   }
459 
460   return new AidlConstantValue(location, Type::CHARACTER, value);
461 }
462 
Floating(const AidlLocation & location,const std::string & value)463 AidlConstantValue* AidlConstantValue::Floating(const AidlLocation& location,
464                                                const std::string& value) {
465   return new AidlConstantValue(location, Type::FLOATING, value);
466 }
467 
IsHex(const string & value)468 bool AidlConstantValue::IsHex(const string& value) {
469   return StartsWith(value, "0x") || StartsWith(value, "0X");
470 }
471 
ParseIntegral(const string & value,int64_t * parsed_value,Type * parsed_type)472 bool AidlConstantValue::ParseIntegral(const string& value, int64_t* parsed_value,
473                                       Type* parsed_type) {
474   if (parsed_value == nullptr || parsed_type == nullptr) {
475     return false;
476   }
477 
478   std::string_view value_view = value;
479   const bool is_byte = ConsumeSuffix(&value_view, "u8");
480   const bool is_unsigned_int = ConsumeSuffix(&value_view, "u32");
481   const bool is_long = ConsumeSuffix(&value_view, "l") || ConsumeSuffix(&value_view, "L");
482   const bool is_unsigned_long = ConsumeSuffix(&value_view, "u64");
483 
484   if (is_byte + is_long + is_unsigned_int + is_unsigned_long > 1) return false;
485 
486   const std::string value_substr = ({
487     std::string raw_value_substr = std::string(value_view);
488     // remove "_" in integral constant
489     const std::vector<std::string> value_pieces = Split(raw_value_substr, "_");
490     if (std::any_of(value_pieces.begin(), value_pieces.end(),
491                     [](const auto& s) { return s.empty(); })) {
492       return false;
493     }
494     Join(value_pieces, "");
495   });
496 
497   *parsed_value = 0;
498   *parsed_type = Type::ERROR;
499 
500   if (IsHex(value)) {
501     // AIDL considers 'const int foo = 0xffffffff' as -1, but if we want to
502     // handle that when computing constant expressions, then we need to
503     // represent 0xffffffff as a uint32_t. However, AIDL only has signed types;
504     // so we parse as an unsigned int when possible and then cast to a signed
505     // int. One example of this is in ICameraService.aidl where a constant int
506     // is used for bit manipulations which ideally should be handled with an
507     // unsigned int.
508     //
509     // Note, for historical consistency, we need to consider small hex values
510     // as an integral type. Recognizing them as INT8 could break some files,
511     // even though it would simplify this code.
512     if (is_byte) {
513       uint8_t raw_value8;
514       if (!android::base::ParseUint<uint8_t>(value_substr, &raw_value8)) {
515         return false;
516       }
517       *parsed_value = static_cast<int8_t>(raw_value8);
518       *parsed_type = Type::INT8;
519     } else if (uint32_t raw_value32;
520                (!is_long || is_unsigned_int) &&
521                android::base::ParseUint<uint32_t>(value_substr, &raw_value32)) {
522       *parsed_value = static_cast<int32_t>(raw_value32);
523       *parsed_type = Type::INT32;
524     } else if (uint64_t raw_value64;
525                android::base::ParseUint<uint64_t>(value_substr, &raw_value64)) {
526       *parsed_value = static_cast<int64_t>(raw_value64);
527       *parsed_type = Type::INT64;
528     } else {
529       return false;
530     }
531     return true;
532   }
533 
534   if (is_unsigned_long) {
535     if (uint64_t raw_value64; android::base::ParseUint<uint64_t>(value_substr, &raw_value64)) {
536       *parsed_value = static_cast<int64_t>(raw_value64);
537       *parsed_type = Type::INT64;
538       return true;
539     } else {
540       return false;
541     }
542   }
543   if (!android::base::ParseInt<int64_t>(value_substr, parsed_value)) {
544     return false;
545   }
546 
547   if (is_byte) {
548     if (*parsed_value > UINT8_MAX || *parsed_value < 0) {
549       return false;
550     }
551     *parsed_value = static_cast<int8_t>(*parsed_value);
552     *parsed_type = Type::INT8;
553   } else if (is_unsigned_int) {
554     if (*parsed_value > UINT32_MAX || *parsed_value < 0) {
555       return false;
556     }
557     *parsed_value = static_cast<int32_t>(*parsed_value);
558     *parsed_type = Type::INT32;
559   } else if (is_long) {
560     *parsed_type = Type::INT64;
561   } else {
562     // guess literal type.
563     if (*parsed_value <= INT8_MAX && *parsed_value >= INT8_MIN) {
564       *parsed_type = Type::INT8;
565     } else if (*parsed_value <= INT32_MAX && *parsed_value >= INT32_MIN) {
566       *parsed_type = Type::INT32;
567     } else {
568       *parsed_type = Type::INT64;
569     }
570   }
571   return true;
572 }
573 
Integral(const AidlLocation & location,const string & value)574 AidlConstantValue* AidlConstantValue::Integral(const AidlLocation& location, const string& value) {
575   AIDL_FATAL_IF(value.empty(), location);
576 
577   Type parsed_type;
578   int64_t parsed_value = 0;
579   bool success = ParseIntegral(value, &parsed_value, &parsed_type);
580   if (!success) {
581     return nullptr;
582   }
583 
584   return new AidlConstantValue(location, parsed_type, parsed_value, value);
585 }
586 
Array(const AidlLocation & location,std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values)587 AidlConstantValue* AidlConstantValue::Array(
588     const AidlLocation& location, std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values) {
589   AIDL_FATAL_IF(values == nullptr, location);
590   // Reconstruct literal value
591   std::vector<std::string> str_values;
592   for (const auto& v : *values) {
593     str_values.push_back(v->value_);
594   }
595   return new AidlConstantValue(location, Type::ARRAY, std::move(values),
596                                "{" + Join(str_values, ", ") + "}");
597 }
598 
String(const AidlLocation & location,const string & value)599 AidlConstantValue* AidlConstantValue::String(const AidlLocation& location, const string& value) {
600   AIDL_FATAL_IF(value.size() == 0, "If this is unquoted, we need to update the index log");
601   AIDL_FATAL_IF(value[0] != '\"', "If this is unquoted, we need to update the index log");
602 
603   for (size_t i = 0; i < value.length(); ++i) {
604     if (!isValidLiteralChar(value[i])) {
605       AIDL_ERROR(location) << "Found invalid character '" << value[i] << "' at index " << i - 1
606                            << " in string constant '" << value << "'";
607       return new AidlConstantValue(location, Type::ERROR, value);
608     }
609   }
610 
611   return new AidlConstantValue(location, Type::STRING, value);
612 }
613 
ValueString(const AidlTypeSpecifier & type,const ConstantValueDecorator & decorator) const614 string AidlConstantValue::ValueString(const AidlTypeSpecifier& type,
615                                       const ConstantValueDecorator& decorator) const {
616   if (type.IsGeneric()) {
617     AIDL_ERROR(type) << "Generic type cannot be specified with a constant literal.";
618     return "";
619   }
620   if (!is_evaluated_) {
621     // TODO(b/142722772) CheckValid() should be called before ValueString()
622     bool success = CheckValid();
623     success &= evaluate();
624     if (!success) {
625       // the detailed error message shall be printed in evaluate
626       return "";
627     }
628   }
629   if (!is_valid_) {
630     AIDL_ERROR(this) << "Invalid constant value: " + value_;
631     return "";
632   }
633 
634   std::vector<std::string> alternatives;
635 
636   const AidlDefinedType* defined_type = type.GetDefinedType();
637   if (defined_type && final_type_ != Type::ARRAY) {
638     const AidlEnumDeclaration* enum_type = defined_type->AsEnumDeclaration();
639     if (!enum_type) {
640       AIDL_ERROR(this) << "Invalid type (" << defined_type->GetCanonicalName()
641                        << ") for a const value (" << value_ << ")";
642       return "";
643     }
644     if (type_ != Type::REF) {
645       AIDL_ERROR(this) << "Invalid value (" << value_ << ") for enum "
646                        << enum_type->GetCanonicalName();
647       return "";
648     }
649     return decorator(type, value_);
650   }
651 
652   const string& type_string = type.Signature();
653   int err = 0;
654 
655   switch (final_type_) {
656     case Type::CHARACTER:
657       if (type_string == "char") {
658         return decorator(type, final_string_value_);
659       }
660       err = -1;
661       break;
662     case Type::STRING:
663       if (type_string == "String") {
664         return decorator(type, final_string_value_);
665       }
666       err = -1;
667       break;
668     case Type::BOOLEAN:  // fall-through
669     case Type::INT8:     // fall-through
670     case Type::INT32:    // fall-through
671     case Type::INT64:
672       if (type_string == "byte") {
673         if (final_value_ > INT8_MAX || final_value_ < INT8_MIN) {
674           err = -1;
675 
676           if (final_value_ >= 0 && final_value_ <= UINT8_MAX && IsLiteral()) {
677             alternatives.push_back(value_ + "u8");
678           }
679           break;
680         }
681         return decorator(type, std::to_string(static_cast<int8_t>(final_value_)));
682       } else if (type_string == "int") {
683         if (final_value_ > INT32_MAX || final_value_ < INT32_MIN) {
684           err = -1;
685           if (final_value_ >= 0 && final_value_ <= UINT32_MAX && IsLiteral()) {
686             alternatives.push_back(value_ + "u32");
687           }
688           break;
689         }
690         return decorator(type, std::to_string(static_cast<int32_t>(final_value_)));
691       } else if (type_string == "long") {
692         return decorator(type, std::to_string(final_value_));
693       } else if (type_string == "boolean") {
694         return decorator(type, final_value_ ? "true" : "false");
695       }
696       err = -1;
697       break;
698     case Type::ARRAY: {
699       if (!type.IsArray()) {
700         err = -1;
701         break;
702       }
703       vector<string> value_strings;
704       value_strings.reserve(values_.size());
705       bool success = true;
706 
707       for (const auto& value : values_) {
708         string value_string;
709         type.ViewAsArrayBase([&](const auto& base_type) {
710           value_string = value->ValueString(base_type, decorator);
711         });
712         if (value_string.empty()) {
713           success = false;
714           break;
715         }
716         value_strings.push_back(value_string);
717       }
718       if (!success) {
719         err = -1;
720         break;
721       }
722       if (type.IsFixedSizeArray()) {
723         auto size =
724             std::get<FixedSizeArray>(type.GetArray()).dimensions.front()->EvaluatedValue<int32_t>();
725         if (values_.size() != static_cast<size_t>(size)) {
726           AIDL_ERROR(this) << "Expected an array of " << size << " elements, but found one with "
727                            << values_.size() << " elements";
728           err = -1;
729           break;
730         }
731       }
732       return decorator(type, value_strings);
733     }
734     case Type::FLOATING: {
735       if (type_string == "double") {
736         double parsed_value;
737         if (!ParseFloating(value_, &parsed_value)) {
738           AIDL_ERROR(this) << "Could not parse " << value_;
739           err = -1;
740           break;
741         }
742         return decorator(type, std::to_string(parsed_value));
743       }
744       if (type_string == "float") {
745         float parsed_value;
746         if (!ParseFloating(value_, &parsed_value)) {
747           AIDL_ERROR(this) << "Could not parse " << value_;
748           err = -1;
749           break;
750         }
751         return decorator(type, std::to_string(parsed_value) + "f");
752       }
753       err = -1;
754       break;
755     }
756     default:
757       err = -1;
758       break;
759   }
760 
761   std::string alternative_help;
762   if (!alternatives.empty()) {
763     alternative_help = " Did you mean: " + Join(alternatives, ", ") + "?";
764   }
765 
766   AIDL_FATAL_IF(err == 0, this);
767   AIDL_ERROR(this) << "Invalid type specifier for " << ToString(final_type_) << ": " << type_string
768                    << " (" << value_ << ")." << alternative_help;
769   return "";
770 }
771 
CheckValid() const772 bool AidlConstantValue::CheckValid() const {
773   // Nothing needs to be checked here. The constant value will be validated in
774   // the constructor or in the evaluate() function.
775   if (is_evaluated_) return is_valid_;
776 
777   switch (type_) {
778     case Type::BOOLEAN:    // fall-through
779     case Type::INT8:       // fall-through
780     case Type::INT32:      // fall-through
781     case Type::INT64:      // fall-through
782     case Type::CHARACTER:  // fall-through
783     case Type::STRING:     // fall-through
784     case Type::REF:        // fall-through
785     case Type::FLOATING:   // fall-through
786     case Type::UNARY:      // fall-through
787     case Type::BINARY:
788       is_valid_ = true;
789       break;
790     case Type::ARRAY:
791       is_valid_ = true;
792       for (const auto& v : values_) is_valid_ &= v->CheckValid();
793       break;
794     case Type::ERROR:
795       return false;
796     default:
797       AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
798       return false;
799   }
800 
801   return true;
802 }
803 
Evaluate() const804 bool AidlConstantValue::Evaluate() const {
805   if (CheckValid()) {
806     return evaluate();
807   } else {
808     return false;
809   }
810 }
811 
evaluate() const812 bool AidlConstantValue::evaluate() const {
813   if (is_evaluated_) {
814     return is_valid_;
815   }
816   int err = 0;
817   is_evaluated_ = true;
818 
819   switch (type_) {
820     case Type::ARRAY: {
821       Type array_type = Type::ERROR;
822       bool success = true;
823       for (const auto& value : values_) {
824         success = value->CheckValid();
825         if (success) {
826           success = value->evaluate();
827           if (!success) {
828             AIDL_ERROR(this) << "Invalid array element: " << value->value_;
829             break;
830           }
831           if (array_type == Type::ERROR) {
832             array_type = value->final_type_;
833           } else if (!AidlBinaryConstExpression::AreCompatibleArrayTypes(array_type,
834                                                                          value->final_type_)) {
835             AIDL_ERROR(this) << "Incompatible array element type: " << ToString(value->final_type_)
836                              << ". Expecting type compatible with " << ToString(array_type);
837             success = false;
838             break;
839           }
840         } else {
841           break;
842         }
843       }
844       if (!success) {
845         err = -1;
846         break;
847       }
848       final_type_ = type_;
849       break;
850     }
851     case Type::BOOLEAN:
852       if ((value_ != "true") && (value_ != "false")) {
853         AIDL_ERROR(this) << "Invalid constant boolean value: " << value_;
854         err = -1;
855         break;
856       }
857       final_value_ = (value_ == "true") ? 1 : 0;
858       final_type_ = type_;
859       break;
860     case Type::INT8:   // fall-through
861     case Type::INT32:  // fall-through
862     case Type::INT64:
863       // Parsing happens in the constructor
864       final_type_ = type_;
865       break;
866     case Type::CHARACTER:  // fall-through
867     case Type::STRING:
868       final_string_value_ = value_;
869       final_type_ = type_;
870       break;
871     case Type::FLOATING:
872       // Just parse on the fly in ValueString
873       final_type_ = type_;
874       break;
875     default:
876       AIDL_FATAL(this) << "Unrecognized constant value type: " << ToString(type_);
877       err = -1;
878   }
879 
880   return (err == 0) ? true : false;
881 }
882 
IsLiteral() const883 bool AidlConstantValue::IsLiteral() const {
884   return !AidlCast<AidlUnaryConstExpression>(*this) &&
885          !AidlCast<AidlBinaryConstExpression>(*this) && !AidlCast<AidlConstantReference>(*this);
886 }
887 
ToString(Type type)888 string AidlConstantValue::ToString(Type type) {
889   switch (type) {
890     case Type::BOOLEAN:
891       return "a literal boolean";
892     case Type::INT8:
893       return "an int8 literal";
894     case Type::INT32:
895       return "an int32 literal";
896     case Type::INT64:
897       return "an int64 literal";
898     case Type::ARRAY:
899       return "a literal array";
900     case Type::CHARACTER:
901       return "a literal char";
902     case Type::STRING:
903       return "a literal string";
904     case Type::REF:
905       return "a reference";
906     case Type::FLOATING:
907       return "a literal float";
908     case Type::UNARY:
909       return "a unary expression";
910     case Type::BINARY:
911       return "a binary expression";
912     case Type::ERROR:
913       AIDL_FATAL(AIDL_LOCATION_HERE) << "aidl internal error: error type failed to halt program";
914       return "";
915     default:
916       AIDL_FATAL(AIDL_LOCATION_HERE)
917           << "aidl internal error: unknown constant type: " << static_cast<int>(type);
918       return "";  // not reached
919   }
920 }
921 
AidlConstantReference(const AidlLocation & location,const std::string & value)922 AidlConstantReference::AidlConstantReference(const AidlLocation& location, const std::string& value)
923     : AidlConstantValue(location, Type::REF, value) {
924   const auto pos = value.find_last_of('.');
925   if (pos == string::npos) {
926     field_name_ = value;
927   } else {
928     ref_type_ = std::make_unique<AidlTypeSpecifier>(location, value.substr(0, pos),
929                                                     /*array=*/std::nullopt, /*type_params=*/nullptr,
930                                                     Comments{});
931     field_name_ = value.substr(pos + 1);
932   }
933 }
934 
Resolve(const AidlDefinedType * scope) const935 const AidlConstantValue* AidlConstantReference::Resolve(const AidlDefinedType* scope) const {
936   if (resolved_) return resolved_;
937 
938   const AidlDefinedType* defined_type;
939   if (ref_type_) {
940     defined_type = ref_type_->GetDefinedType();
941   } else {
942     defined_type = scope;
943   }
944 
945   if (!defined_type) {
946     // This can happen when "const reference" is used in an unsupported way,
947     // but missed in checks there. It works as a safety net.
948     AIDL_ERROR(*this) << "Can't resolve the reference (" << value_ << ")";
949     return nullptr;
950   }
951 
952   if (auto enum_decl = defined_type->AsEnumDeclaration(); enum_decl) {
953     for (const auto& e : enum_decl->GetEnumerators()) {
954       if (e->GetName() == field_name_) {
955         return resolved_ = e->GetValue();
956       }
957     }
958   } else {
959     for (const auto& c : defined_type->GetConstantDeclarations()) {
960       if (c->GetName() == field_name_) {
961         return resolved_ = &c->GetValue();
962       }
963     }
964   }
965   AIDL_ERROR(*this) << "Can't find " << field_name_ << " in " << defined_type->GetName();
966   return nullptr;
967 }
968 
CheckValid() const969 bool AidlConstantReference::CheckValid() const {
970   if (is_evaluated_) return is_valid_;
971   AIDL_FATAL_IF(!resolved_, this) << "Should be resolved first: " << value_;
972   is_valid_ = resolved_->CheckValid();
973   return is_valid_;
974 }
975 
evaluate() const976 bool AidlConstantReference::evaluate() const {
977   if (is_evaluated_) return is_valid_;
978   AIDL_FATAL_IF(!resolved_, this) << "Should be resolved first: " << value_;
979   is_evaluated_ = true;
980 
981   resolved_->evaluate();
982   is_valid_ = resolved_->is_valid_;
983   final_type_ = resolved_->final_type_;
984   if (is_valid_) {
985     if (final_type_ == Type::STRING) {
986       final_string_value_ = resolved_->final_string_value_;
987     } else {
988       final_value_ = resolved_->final_value_;
989     }
990   }
991   return is_valid_;
992 }
993 
CheckValid() const994 bool AidlUnaryConstExpression::CheckValid() const {
995   if (is_evaluated_) return is_valid_;
996   AIDL_FATAL_IF(unary_ == nullptr, this);
997 
998   is_valid_ = unary_->CheckValid();
999   if (!is_valid_) {
1000     final_type_ = Type::ERROR;
1001     return false;
1002   }
1003 
1004   return AidlConstantValue::CheckValid();
1005 }
1006 
evaluate() const1007 bool AidlUnaryConstExpression::evaluate() const {
1008   if (is_evaluated_) {
1009     return is_valid_;
1010   }
1011   is_evaluated_ = true;
1012 
1013   // Recursively evaluate the expression tree
1014   if (!unary_->is_evaluated_) {
1015     // TODO(b/142722772) CheckValid() should be called before ValueString()
1016     bool success = CheckValid();
1017     success &= unary_->evaluate();
1018     if (!success) {
1019       is_valid_ = false;
1020       return false;
1021     }
1022   }
1023   if (!IsCompatibleType(unary_->final_type_, op_)) {
1024     AIDL_ERROR(unary_) << "'" << op_ << "'"
1025                        << " is not compatible with " << ToString(unary_->final_type_)
1026                        << ": " + value_;
1027     is_valid_ = false;
1028     return false;
1029   }
1030   if (!unary_->is_valid_) {
1031     AIDL_ERROR(unary_) << "Invalid constant unary expression: " + value_;
1032     is_valid_ = false;
1033     return false;
1034   }
1035   final_type_ = unary_->final_type_;
1036 
1037   if (final_type_ == Type::FLOATING) {
1038     // don't do anything here. ValueString() will handle everything.
1039     is_valid_ = true;
1040     return true;
1041   }
1042 
1043 #define CASE_UNARY(__type__) \
1044   return is_valid_ =         \
1045              handleUnary(*this, op_, static_cast<__type__>(unary_->final_value_), &final_value_);
1046 
1047   SWITCH_KIND(final_type_, CASE_UNARY, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
1048               is_valid_ = false; return false;)
1049 }
1050 
CheckValid() const1051 bool AidlBinaryConstExpression::CheckValid() const {
1052   bool success = false;
1053   if (is_evaluated_) return is_valid_;
1054   AIDL_FATAL_IF(left_val_ == nullptr, this);
1055   AIDL_FATAL_IF(right_val_ == nullptr, this);
1056 
1057   success = left_val_->CheckValid();
1058   if (!success) {
1059     final_type_ = Type::ERROR;
1060     AIDL_ERROR(this) << "Invalid left operand in binary expression: " + value_;
1061   }
1062 
1063   success = right_val_->CheckValid();
1064   if (!success) {
1065     AIDL_ERROR(this) << "Invalid right operand in binary expression: " + value_;
1066     final_type_ = Type::ERROR;
1067   }
1068 
1069   if (final_type_ == Type::ERROR) {
1070     is_valid_ = false;
1071     return false;
1072   }
1073 
1074   is_valid_ = true;
1075   return AidlConstantValue::CheckValid();
1076 }
1077 
evaluate() const1078 bool AidlBinaryConstExpression::evaluate() const {
1079   if (is_evaluated_) {
1080     return is_valid_;
1081   }
1082   is_evaluated_ = true;
1083   AIDL_FATAL_IF(left_val_ == nullptr, this);
1084   AIDL_FATAL_IF(right_val_ == nullptr, this);
1085 
1086   // Recursively evaluate the binary expression tree
1087   if (!left_val_->is_evaluated_ || !right_val_->is_evaluated_) {
1088     // TODO(b/142722772) CheckValid() should be called before ValueString()
1089     bool success = CheckValid();
1090     success &= left_val_->evaluate();
1091     success &= right_val_->evaluate();
1092     if (!success) {
1093       is_valid_ = false;
1094       return false;
1095     }
1096   }
1097   if (!left_val_->is_valid_ || !right_val_->is_valid_) {
1098     is_valid_ = false;
1099     return false;
1100   }
1101   is_valid_ = AreCompatibleOperandTypes(left_val_->final_type_, right_val_->final_type_);
1102   if (!is_valid_) {
1103     AIDL_ERROR(this) << "Cannot perform operation '" << op_ << "' on "
1104                      << ToString(right_val_->GetType()) << " and " << ToString(left_val_->GetType())
1105                      << ".";
1106     return false;
1107   }
1108 
1109   bool isArithmeticOrBitflip = OP_IS_BIN_ARITHMETIC || OP_IS_BIN_BITFLIP;
1110 
1111   // Handle String case first
1112   if (left_val_->final_type_ == Type::STRING) {
1113     AIDL_FATAL_IF(right_val_->final_type_ != Type::STRING, this);
1114     if (!OPEQ("+")) {
1115       AIDL_ERROR(this) << "Only '+' is supported for strings, not '" << op_ << "'.";
1116       final_type_ = Type::ERROR;
1117       is_valid_ = false;
1118       return false;
1119     }
1120 
1121     // Remove trailing " from lhs
1122     const string& lhs = left_val_->final_string_value_;
1123     if (lhs.back() != '"') {
1124       AIDL_ERROR(this) << "'" << lhs << "' is missing a trailing quote.";
1125       final_type_ = Type::ERROR;
1126       is_valid_ = false;
1127       return false;
1128     }
1129     const string& rhs = right_val_->final_string_value_;
1130     // Remove starting " from rhs
1131     if (rhs.front() != '"') {
1132       AIDL_ERROR(this) << "'" << rhs << "' is missing a leading quote.";
1133       final_type_ = Type::ERROR;
1134       is_valid_ = false;
1135       return false;
1136     }
1137 
1138     final_string_value_ = string(lhs.begin(), lhs.end() - 1).append(rhs.begin() + 1, rhs.end());
1139     final_type_ = Type::STRING;
1140     return true;
1141   }
1142 
1143   // CASE: + - *  / % | ^ & < > <= >= == !=
1144   if (isArithmeticOrBitflip || OP_IS_BIN_COMP) {
1145     // promoted kind for both operands.
1146     Type promoted = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
1147                                               IntegralPromotion(right_val_->final_type_));
1148     // result kind.
1149     final_type_ = isArithmeticOrBitflip
1150                       ? promoted        // arithmetic or bitflip operators generates promoted type
1151                       : Type::BOOLEAN;  // comparison operators generates bool
1152 
1153 #define CASE_BINARY_COMMON(__type__)                                                        \
1154   return is_valid_ =                                                                        \
1155              handleBinaryCommon(*this, static_cast<__type__>(left_val_->final_value_), op_, \
1156                                 static_cast<__type__>(right_val_->final_value_), &final_value_);
1157 
1158     SWITCH_KIND(promoted, CASE_BINARY_COMMON, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
1159                 is_valid_ = false; return false;)
1160   }
1161 
1162   // CASE: << >>
1163   string newOp = op_;
1164   if (OP_IS_BIN_SHIFT) {
1165     // promoted kind for both operands.
1166     final_type_ = UsualArithmeticConversion(IntegralPromotion(left_val_->final_type_),
1167                                             IntegralPromotion(right_val_->final_type_));
1168     auto numBits = right_val_->final_value_;
1169     if (numBits < 0) {
1170       // shifting with negative number of bits is undefined in C. In AIDL it
1171       // is defined as shifting into the other direction.
1172       newOp = OPEQ("<<") ? ">>" : "<<";
1173       numBits = -numBits;
1174     }
1175 
1176 #define CASE_SHIFT(__type__)                                                                   \
1177   return is_valid_ = handleShift(*this, static_cast<__type__>(left_val_->final_value_), newOp, \
1178                                  static_cast<__type__>(numBits), &final_value_);
1179 
1180     SWITCH_KIND(final_type_, CASE_SHIFT, SHOULD_NOT_REACH(); final_type_ = Type::ERROR;
1181                 is_valid_ = false; return false;)
1182   }
1183 
1184   // CASE: && ||
1185   if (OP_IS_BIN_LOGICAL) {
1186     final_type_ = Type::BOOLEAN;
1187     // easy; everything is bool.
1188     return handleLogical(*this, left_val_->final_value_, op_, right_val_->final_value_,
1189                          &final_value_);
1190   }
1191 
1192   SHOULD_NOT_REACH();
1193   is_valid_ = false;
1194   return false;
1195 }
1196 
1197 // Constructor for integer(byte, int, long)
1198 // Keep parsed integer & literal
AidlConstantValue(const AidlLocation & location,Type parsed_type,int64_t parsed_value,const string & checked_value)1199 AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type parsed_type,
1200                                      int64_t parsed_value, const string& checked_value)
1201     : AidlNode(location),
1202       type_(parsed_type),
1203       value_(checked_value),
1204       final_type_(parsed_type),
1205       final_value_(parsed_value) {
1206   AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
1207   AIDL_FATAL_IF(type_ != Type::INT8 && type_ != Type::INT32 && type_ != Type::INT64, location);
1208 }
1209 
1210 // Constructor for non-integer(String, char, boolean, float, double)
1211 // Keep literal as it is. (e.g. String literal has double quotes at both ends)
AidlConstantValue(const AidlLocation & location,Type type,const string & checked_value)1212 AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
1213                                      const string& checked_value)
1214     : AidlNode(location),
1215       type_(type),
1216       value_(checked_value),
1217       final_type_(type) {
1218   AIDL_FATAL_IF(value_.empty() && type_ != Type::ERROR, location);
1219   switch (type_) {
1220     case Type::INT8:
1221     case Type::INT32:
1222     case Type::INT64:
1223     case Type::ARRAY:
1224       AIDL_FATAL(this) << "Invalid type: " << ToString(type_);
1225       break;
1226     default:
1227       break;
1228   }
1229 }
1230 
1231 // Constructor for array
AidlConstantValue(const AidlLocation & location,Type type,std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values,const std::string & value)1232 AidlConstantValue::AidlConstantValue(const AidlLocation& location, Type type,
1233                                      std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values,
1234                                      const std::string& value)
1235     : AidlNode(location),
1236       type_(type),
1237       values_(std::move(*values)),
1238       value_(value),
1239       is_valid_(false),
1240       is_evaluated_(false),
1241       final_type_(type) {
1242   AIDL_FATAL_IF(type_ != Type::ARRAY, location);
1243 }
1244 
AidlUnaryConstExpression(const AidlLocation & location,const string & op,std::unique_ptr<AidlConstantValue> rval)1245 AidlUnaryConstExpression::AidlUnaryConstExpression(const AidlLocation& location, const string& op,
1246                                                    std::unique_ptr<AidlConstantValue> rval)
1247     : AidlConstantValue(location, Type::UNARY, op + rval->value_),
1248       unary_(std::move(rval)),
1249       op_(op) {
1250   final_type_ = Type::UNARY;
1251 }
1252 
AidlBinaryConstExpression(const AidlLocation & location,std::unique_ptr<AidlConstantValue> lval,const string & op,std::unique_ptr<AidlConstantValue> rval)1253 AidlBinaryConstExpression::AidlBinaryConstExpression(const AidlLocation& location,
1254                                                      std::unique_ptr<AidlConstantValue> lval,
1255                                                      const string& op,
1256                                                      std::unique_ptr<AidlConstantValue> rval)
1257     : AidlConstantValue(location, Type::BINARY, lval->value_ + op + rval->value_),
1258       left_val_(std::move(lval)),
1259       right_val_(std::move(rval)),
1260       op_(op) {
1261   final_type_ = Type::BINARY;
1262 }
1263