1 /*
2  * Copyright (C) 2009 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 <string.h>
18 #include <stdbool.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdarg.h>
22 #include <unistd.h>
23 
24 #include <string>
25 
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 
29 #include "expr.h"
30 
31 // Functions should:
32 //
33 //    - return a malloc()'d string
34 //    - if Evaluate() on any argument returns NULL, return NULL.
35 
BooleanString(const char * s)36 int BooleanString(const char* s) {
37     return s[0] != '\0';
38 }
39 
Evaluate(State * state,Expr * expr)40 char* Evaluate(State* state, Expr* expr) {
41     Value* v = expr->fn(expr->name, state, expr->argc, expr->argv);
42     if (v == NULL) return NULL;
43     if (v->type != VAL_STRING) {
44         ErrorAbort(state, kArgsParsingFailure, "expecting string, got value type %d", v->type);
45         FreeValue(v);
46         return NULL;
47     }
48     char* result = v->data;
49     free(v);
50     return result;
51 }
52 
EvaluateValue(State * state,Expr * expr)53 Value* EvaluateValue(State* state, Expr* expr) {
54     return expr->fn(expr->name, state, expr->argc, expr->argv);
55 }
56 
StringValue(char * str)57 Value* StringValue(char* str) {
58     if (str == NULL) return NULL;
59     Value* v = reinterpret_cast<Value*>(malloc(sizeof(Value)));
60     v->type = VAL_STRING;
61     v->size = strlen(str);
62     v->data = str;
63     return v;
64 }
65 
FreeValue(Value * v)66 void FreeValue(Value* v) {
67     if (v == NULL) return;
68     free(v->data);
69     free(v);
70 }
71 
ConcatFn(const char * name,State * state,int argc,Expr * argv[])72 Value* ConcatFn(const char* name, State* state, int argc, Expr* argv[]) {
73     if (argc == 0) {
74         return StringValue(strdup(""));
75     }
76     char** strings = reinterpret_cast<char**>(malloc(argc * sizeof(char*)));
77     int i;
78     for (i = 0; i < argc; ++i) {
79         strings[i] = NULL;
80     }
81     char* result = NULL;
82     int length = 0;
83     for (i = 0; i < argc; ++i) {
84         strings[i] = Evaluate(state, argv[i]);
85         if (strings[i] == NULL) {
86             goto done;
87         }
88         length += strlen(strings[i]);
89     }
90 
91     result = reinterpret_cast<char*>(malloc(length+1));
92     int p;
93     p = 0;
94     for (i = 0; i < argc; ++i) {
95         strcpy(result+p, strings[i]);
96         p += strlen(strings[i]);
97     }
98     result[p] = '\0';
99 
100   done:
101     for (i = 0; i < argc; ++i) {
102         free(strings[i]);
103     }
104     free(strings);
105     return StringValue(result);
106 }
107 
IfElseFn(const char * name,State * state,int argc,Expr * argv[])108 Value* IfElseFn(const char* name, State* state, int argc, Expr* argv[]) {
109     if (argc != 2 && argc != 3) {
110         free(state->errmsg);
111         state->errmsg = strdup("ifelse expects 2 or 3 arguments");
112         return NULL;
113     }
114     char* cond = Evaluate(state, argv[0]);
115     if (cond == NULL) {
116         return NULL;
117     }
118 
119     if (BooleanString(cond) == true) {
120         free(cond);
121         return EvaluateValue(state, argv[1]);
122     } else {
123         if (argc == 3) {
124             free(cond);
125             return EvaluateValue(state, argv[2]);
126         } else {
127             return StringValue(cond);
128         }
129     }
130 }
131 
AbortFn(const char * name,State * state,int argc,Expr * argv[])132 Value* AbortFn(const char* name, State* state, int argc, Expr* argv[]) {
133     char* msg = NULL;
134     if (argc > 0) {
135         msg = Evaluate(state, argv[0]);
136     }
137     free(state->errmsg);
138     if (msg) {
139         state->errmsg = msg;
140     } else {
141         state->errmsg = strdup("called abort()");
142     }
143     return NULL;
144 }
145 
AssertFn(const char * name,State * state,int argc,Expr * argv[])146 Value* AssertFn(const char* name, State* state, int argc, Expr* argv[]) {
147     int i;
148     for (i = 0; i < argc; ++i) {
149         char* v = Evaluate(state, argv[i]);
150         if (v == NULL) {
151             return NULL;
152         }
153         int b = BooleanString(v);
154         free(v);
155         if (!b) {
156             int prefix_len;
157             int len = argv[i]->end - argv[i]->start;
158             char* err_src = reinterpret_cast<char*>(malloc(len + 20));
159             strcpy(err_src, "assert failed: ");
160             prefix_len = strlen(err_src);
161             memcpy(err_src + prefix_len, state->script + argv[i]->start, len);
162             err_src[prefix_len + len] = '\0';
163             free(state->errmsg);
164             state->errmsg = err_src;
165             return NULL;
166         }
167     }
168     return StringValue(strdup(""));
169 }
170 
SleepFn(const char * name,State * state,int argc,Expr * argv[])171 Value* SleepFn(const char* name, State* state, int argc, Expr* argv[]) {
172     char* val = Evaluate(state, argv[0]);
173     if (val == NULL) {
174         return NULL;
175     }
176     int v = strtol(val, NULL, 10);
177     sleep(v);
178     return StringValue(val);
179 }
180 
StdoutFn(const char * name,State * state,int argc,Expr * argv[])181 Value* StdoutFn(const char* name, State* state, int argc, Expr* argv[]) {
182     int i;
183     for (i = 0; i < argc; ++i) {
184         char* v = Evaluate(state, argv[i]);
185         if (v == NULL) {
186             return NULL;
187         }
188         fputs(v, stdout);
189         free(v);
190     }
191     return StringValue(strdup(""));
192 }
193 
LogicalAndFn(const char * name,State * state,int argc,Expr * argv[])194 Value* LogicalAndFn(const char* name, State* state,
195                    int argc, Expr* argv[]) {
196     char* left = Evaluate(state, argv[0]);
197     if (left == NULL) return NULL;
198     if (BooleanString(left) == true) {
199         free(left);
200         return EvaluateValue(state, argv[1]);
201     } else {
202         return StringValue(left);
203     }
204 }
205 
LogicalOrFn(const char * name,State * state,int argc,Expr * argv[])206 Value* LogicalOrFn(const char* name, State* state,
207                    int argc, Expr* argv[]) {
208     char* left = Evaluate(state, argv[0]);
209     if (left == NULL) return NULL;
210     if (BooleanString(left) == false) {
211         free(left);
212         return EvaluateValue(state, argv[1]);
213     } else {
214         return StringValue(left);
215     }
216 }
217 
LogicalNotFn(const char * name,State * state,int argc,Expr * argv[])218 Value* LogicalNotFn(const char* name, State* state,
219                     int argc, Expr* argv[]) {
220     char* val = Evaluate(state, argv[0]);
221     if (val == NULL) return NULL;
222     bool bv = BooleanString(val);
223     free(val);
224     return StringValue(strdup(bv ? "" : "t"));
225 }
226 
SubstringFn(const char * name,State * state,int argc,Expr * argv[])227 Value* SubstringFn(const char* name, State* state,
228                    int argc, Expr* argv[]) {
229     char* needle = Evaluate(state, argv[0]);
230     if (needle == NULL) return NULL;
231     char* haystack = Evaluate(state, argv[1]);
232     if (haystack == NULL) {
233         free(needle);
234         return NULL;
235     }
236 
237     char* result = strdup(strstr(haystack, needle) ? "t" : "");
238     free(needle);
239     free(haystack);
240     return StringValue(result);
241 }
242 
EqualityFn(const char * name,State * state,int argc,Expr * argv[])243 Value* EqualityFn(const char* name, State* state, int argc, Expr* argv[]) {
244     char* left = Evaluate(state, argv[0]);
245     if (left == NULL) return NULL;
246     char* right = Evaluate(state, argv[1]);
247     if (right == NULL) {
248         free(left);
249         return NULL;
250     }
251 
252     char* result = strdup(strcmp(left, right) == 0 ? "t" : "");
253     free(left);
254     free(right);
255     return StringValue(result);
256 }
257 
InequalityFn(const char * name,State * state,int argc,Expr * argv[])258 Value* InequalityFn(const char* name, State* state, int argc, Expr* argv[]) {
259     char* left = Evaluate(state, argv[0]);
260     if (left == NULL) return NULL;
261     char* right = Evaluate(state, argv[1]);
262     if (right == NULL) {
263         free(left);
264         return NULL;
265     }
266 
267     char* result = strdup(strcmp(left, right) != 0 ? "t" : "");
268     free(left);
269     free(right);
270     return StringValue(result);
271 }
272 
SequenceFn(const char * name,State * state,int argc,Expr * argv[])273 Value* SequenceFn(const char* name, State* state, int argc, Expr* argv[]) {
274     Value* left = EvaluateValue(state, argv[0]);
275     if (left == NULL) return NULL;
276     FreeValue(left);
277     return EvaluateValue(state, argv[1]);
278 }
279 
LessThanIntFn(const char * name,State * state,int argc,Expr * argv[])280 Value* LessThanIntFn(const char* name, State* state, int argc, Expr* argv[]) {
281     if (argc != 2) {
282         free(state->errmsg);
283         state->errmsg = strdup("less_than_int expects 2 arguments");
284         return NULL;
285     }
286 
287     char* left;
288     char* right;
289     if (ReadArgs(state, argv, 2, &left, &right) < 0) return NULL;
290 
291     bool result = false;
292     char* end;
293 
294     long l_int = strtol(left, &end, 10);
295     if (left[0] == '\0' || *end != '\0') {
296         goto done;
297     }
298 
299     long r_int;
300     r_int = strtol(right, &end, 10);
301     if (right[0] == '\0' || *end != '\0') {
302         goto done;
303     }
304 
305     result = l_int < r_int;
306 
307   done:
308     free(left);
309     free(right);
310     return StringValue(strdup(result ? "t" : ""));
311 }
312 
GreaterThanIntFn(const char * name,State * state,int argc,Expr * argv[])313 Value* GreaterThanIntFn(const char* name, State* state,
314                         int argc, Expr* argv[]) {
315     if (argc != 2) {
316         free(state->errmsg);
317         state->errmsg = strdup("greater_than_int expects 2 arguments");
318         return NULL;
319     }
320 
321     Expr* temp[2];
322     temp[0] = argv[1];
323     temp[1] = argv[0];
324 
325     return LessThanIntFn(name, state, 2, temp);
326 }
327 
Literal(const char * name,State * state,int argc,Expr * argv[])328 Value* Literal(const char* name, State* state, int argc, Expr* argv[]) {
329     return StringValue(strdup(name));
330 }
331 
Build(Function fn,YYLTYPE loc,int count,...)332 Expr* Build(Function fn, YYLTYPE loc, int count, ...) {
333     va_list v;
334     va_start(v, count);
335     Expr* e = reinterpret_cast<Expr*>(malloc(sizeof(Expr)));
336     e->fn = fn;
337     e->name = "(operator)";
338     e->argc = count;
339     e->argv = reinterpret_cast<Expr**>(malloc(count * sizeof(Expr*)));
340     int i;
341     for (i = 0; i < count; ++i) {
342         e->argv[i] = va_arg(v, Expr*);
343     }
344     va_end(v);
345     e->start = loc.start;
346     e->end = loc.end;
347     return e;
348 }
349 
350 // -----------------------------------------------------------------
351 //   the function table
352 // -----------------------------------------------------------------
353 
354 static int fn_entries = 0;
355 static int fn_size = 0;
356 NamedFunction* fn_table = NULL;
357 
RegisterFunction(const char * name,Function fn)358 void RegisterFunction(const char* name, Function fn) {
359     if (fn_entries >= fn_size) {
360         fn_size = fn_size*2 + 1;
361         fn_table = reinterpret_cast<NamedFunction*>(realloc(fn_table, fn_size * sizeof(NamedFunction)));
362     }
363     fn_table[fn_entries].name = name;
364     fn_table[fn_entries].fn = fn;
365     ++fn_entries;
366 }
367 
fn_entry_compare(const void * a,const void * b)368 static int fn_entry_compare(const void* a, const void* b) {
369     const char* na = ((const NamedFunction*)a)->name;
370     const char* nb = ((const NamedFunction*)b)->name;
371     return strcmp(na, nb);
372 }
373 
FinishRegistration()374 void FinishRegistration() {
375     qsort(fn_table, fn_entries, sizeof(NamedFunction), fn_entry_compare);
376 }
377 
FindFunction(const char * name)378 Function FindFunction(const char* name) {
379     NamedFunction key;
380     key.name = name;
381     NamedFunction* nf = reinterpret_cast<NamedFunction*>(bsearch(&key, fn_table, fn_entries,
382             sizeof(NamedFunction), fn_entry_compare));
383     if (nf == NULL) {
384         return NULL;
385     }
386     return nf->fn;
387 }
388 
RegisterBuiltins()389 void RegisterBuiltins() {
390     RegisterFunction("ifelse", IfElseFn);
391     RegisterFunction("abort", AbortFn);
392     RegisterFunction("assert", AssertFn);
393     RegisterFunction("concat", ConcatFn);
394     RegisterFunction("is_substring", SubstringFn);
395     RegisterFunction("stdout", StdoutFn);
396     RegisterFunction("sleep", SleepFn);
397 
398     RegisterFunction("less_than_int", LessThanIntFn);
399     RegisterFunction("greater_than_int", GreaterThanIntFn);
400 }
401 
402 
403 // -----------------------------------------------------------------
404 //   convenience methods for functions
405 // -----------------------------------------------------------------
406 
407 // Evaluate the expressions in argv, giving 'count' char* (the ... is
408 // zero or more char** to put them in).  If any expression evaluates
409 // to NULL, free the rest and return -1.  Return 0 on success.
ReadArgs(State * state,Expr * argv[],int count,...)410 int ReadArgs(State* state, Expr* argv[], int count, ...) {
411     char** args = reinterpret_cast<char**>(malloc(count * sizeof(char*)));
412     va_list v;
413     va_start(v, count);
414     int i;
415     for (i = 0; i < count; ++i) {
416         args[i] = Evaluate(state, argv[i]);
417         if (args[i] == NULL) {
418             va_end(v);
419             int j;
420             for (j = 0; j < i; ++j) {
421                 free(args[j]);
422             }
423             free(args);
424             return -1;
425         }
426         *(va_arg(v, char**)) = args[i];
427     }
428     va_end(v);
429     free(args);
430     return 0;
431 }
432 
433 // Evaluate the expressions in argv, giving 'count' Value* (the ... is
434 // zero or more Value** to put them in).  If any expression evaluates
435 // to NULL, free the rest and return -1.  Return 0 on success.
ReadValueArgs(State * state,Expr * argv[],int count,...)436 int ReadValueArgs(State* state, Expr* argv[], int count, ...) {
437     Value** args = reinterpret_cast<Value**>(malloc(count * sizeof(Value*)));
438     va_list v;
439     va_start(v, count);
440     int i;
441     for (i = 0; i < count; ++i) {
442         args[i] = EvaluateValue(state, argv[i]);
443         if (args[i] == NULL) {
444             va_end(v);
445             int j;
446             for (j = 0; j < i; ++j) {
447                 FreeValue(args[j]);
448             }
449             free(args);
450             return -1;
451         }
452         *(va_arg(v, Value**)) = args[i];
453     }
454     va_end(v);
455     free(args);
456     return 0;
457 }
458 
459 // Evaluate the expressions in argv, returning an array of char*
460 // results.  If any evaluate to NULL, free the rest and return NULL.
461 // The caller is responsible for freeing the returned array and the
462 // strings it contains.
ReadVarArgs(State * state,int argc,Expr * argv[])463 char** ReadVarArgs(State* state, int argc, Expr* argv[]) {
464     char** args = (char**)malloc(argc * sizeof(char*));
465     int i = 0;
466     for (i = 0; i < argc; ++i) {
467         args[i] = Evaluate(state, argv[i]);
468         if (args[i] == NULL) {
469             int j;
470             for (j = 0; j < i; ++j) {
471                 free(args[j]);
472             }
473             free(args);
474             return NULL;
475         }
476     }
477     return args;
478 }
479 
480 // Evaluate the expressions in argv, returning an array of Value*
481 // results.  If any evaluate to NULL, free the rest and return NULL.
482 // The caller is responsible for freeing the returned array and the
483 // Values it contains.
ReadValueVarArgs(State * state,int argc,Expr * argv[])484 Value** ReadValueVarArgs(State* state, int argc, Expr* argv[]) {
485     Value** args = (Value**)malloc(argc * sizeof(Value*));
486     int i = 0;
487     for (i = 0; i < argc; ++i) {
488         args[i] = EvaluateValue(state, argv[i]);
489         if (args[i] == NULL) {
490             int j;
491             for (j = 0; j < i; ++j) {
492                 FreeValue(args[j]);
493             }
494             free(args);
495             return NULL;
496         }
497     }
498     return args;
499 }
500 
ErrorAbortV(State * state,const char * format,va_list ap)501 static void ErrorAbortV(State* state, const char* format, va_list ap) {
502     std::string buffer;
503     android::base::StringAppendV(&buffer, format, ap);
504     free(state->errmsg);
505     state->errmsg = strdup(buffer.c_str());
506     return;
507 }
508 
509 // Use printf-style arguments to compose an error message to put into
510 // *state.  Returns nullptr.
ErrorAbort(State * state,const char * format,...)511 Value* ErrorAbort(State* state, const char* format, ...) {
512     va_list ap;
513     va_start(ap, format);
514     ErrorAbortV(state, format, ap);
515     va_end(ap);
516     return nullptr;
517 }
518 
ErrorAbort(State * state,CauseCode cause_code,const char * format,...)519 Value* ErrorAbort(State* state, CauseCode cause_code, const char* format, ...) {
520     va_list ap;
521     va_start(ap, format);
522     ErrorAbortV(state, format, ap);
523     va_end(ap);
524     state->cause_code = cause_code;
525     return nullptr;
526 }
527