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