-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPHPAnalyzer.php
More file actions
1279 lines (1212 loc) · 43.3 KB
/
PHPAnalyzer.php
File metadata and controls
1279 lines (1212 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace malmax;
require_once "cli-colors.php";
//function available in apache
if (!function_exists("apache_getenv"))
{
function apache_getenv()
{
return "";
}
}
function timer($what=-1)
{
static $t=0;
if ($what==0)
$t=microtime(true);
else
{
$diff=microtime(true)-$t;
if ($what==1)
printf("%.2fms\n",$diff*1000.0);
elseif ($what==2)
return $diff*1000*1000;
else
return sprintf("%.2f",$diff);
}
}
require_once dirname(__FILE__)."/php-emul/oo.php";
use PHPEmul\Checkpoint;
use PHPEmul\LineLogger;
use PHPEmul\SymbolicVariable;
use PhpParser\Node;
if (!function_exists("set_magic_quotes_runtime"))
{
function set_magic_quotes_runtime() {}
}
// function serialize_mock2($emul,$var)
// {
// #FIXME: temporary workaround on infinite recursion
// if ($emul->off_branch>0)
// return serialize($var);
// else
// return serialize_mock($emul,$var);
// }
// function unserialize_mock2($emul,$var)
// {
// if ($emul->off_branch>0)
// return unserialize($var);
// else
// return unserialize_mock($emul,$var);
// }
abstract class ExecutionMode {
const ONLINE = 1;
const OFFLINE = 2;
}
class PHPAnalyzer extends \PHPEmul\OOEmulator
{
/*
* Includes the file and line information where this process was forked.
* [file_name => line_number]
*/
/**
* A list of statements processed
* @var array
*/
public $statements = [];
public $declared_statements = [];
// Current priority of this execution from the queue
public $current_priority = null;
// When satisfying conditions with in_array(Symbolic_element, Concrete_array)
// return Symbolic variable result or fork for every match in Concrete_array
public $fork_on_symbolic_in_array = false;
/**
* Tracks whether extended logs are provided to the emulation
* Extended logs include the keys for $_POST, $_COOKIE, and $_SESSION variables but not the values.
* In this mode, only these elements are marked as symbolic.
* This flag is used throughout the code to change the behavior of the emulator based on this information.
* @var bool
*/
public $extended_logs_emulation_mode = false;
/**
* Whether to isolate every off-branch from its parent or just run
* the entire off-branches in one isolation.
* Damages the accuracy greatly, but only saves roughly 50% performance.
* @var boolean
*/
public $off_branch_recursive_isolation=true;
/**
* Whether to force down on all paths or not
* @var boolean
*/
public $concolic=false;
/**
* Depth of the off-branch
* @var integer
*/
public $off_branch=0;
/**
* Snapshot stack for restoring them
* @var array
*/
private $snapshot_stack=[];
/**
* Halting problem depth limit
* @var integer
*/
public $off_branch_depth_limit=8;
/**
* Maximum number of times to run each unique off-branch
* @var integer
*/
public $off_branch_execution_limit=1;
/**
* Holds the entry point of off-branches to
* prevent rerun.
* @var array
*/
protected $off_branch_execution=[];
/**
* Postprocessing data
* @var array
*/
public $post_processing=[];
/**
* Whether to isolate post-processing evaluations
* @var boolean
*/
public $post_processing_isolation=false;
/**
* Included files that is not restored after isolation.
* @var array
*/
public $all_files=[];
/**
* Statistics of the analyzer, modified using inc()
* @var array
*/
public $stats=[];
/**
* Holds a list of current active conditions (ifs)
* @var array
*/
public $active_conditions=[];
/**
* List of all includes found in parsed code
* @var array
*/
public $includes=[];
function inc($name,$number=1)
{
$parts=explode("/",$name);
$ref=&$this->stats;
$last_part=array_pop($parts);
foreach ($parts as $part)
{
if (!isset($ref[$part]))
$ref[$part]=[];
$ref=&$ref[$part];
}
if (!isset($ref[$last_part]))
$ref[$last_part]=$number;
else
$ref[$last_part]+=$number;
}
/**
* Default emulator exception handler
* @param Exception $e
* @return [description]
*/
public function exception_handler($e)
{
if (count($this->exception_handlers))
{
$this->call_function(end($this->exception_handlers),[$e]);
$this->terminated=true;
return true;
}
// return $this->error_handler($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
//program output
$this->output("PHP Fatal error: Uncaught Error: ".$e->getMessage()," in ",$this->current_file,":",$this->current_line,PHP_EOL);
$this->output("Stack trace:\n");
$backtrace=$this->print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$this->output($backtrace);
$count=count($this->trace);
$this->output("#",$count," {main}",PHP_EOL);
$this->output(" thrown in ",$this->current_file," on line ",$this->current_line,PHP_EOL);
//emulator output
if ($this->off_branch>0)
{
$this->verbose(strcolor("Off-Branch PHP-Emul Fatal error: Uncaught Error: ".$e->getMessage()." in ".$e->getFile().":".$e->getLine()."\n","yellow"),0);
}
else
{
$this->verbose("PHP-Emul Fatal error: Uncaught Error: ".$e->getMessage()." in ".$e->getFile().":".$e->getLine()."\n",0);
if ($this->verbose>=2 and $this->off_branch==0)
{
$this->verbose("Emulator Backtrace:\n");
echo $e->getTraceAsString(),PHP_EOL;
$this->verbose("Emulation Backtrace:\n");
echo $this->print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
}
$this->terminated=true;
return true;
}
/**
* Overriden error handler to terminate the off-branches
* @param [type] $errno [description]
* @param [type] $errstr [description]
* @param [type] $errfile [description]
* @param [type] $errline [description]
* @return [type] [description]
*/
function error_handler($errno, $errstr, $errfile, $errline)
{
if (count($this->error_handlers) and $errno&end($this->error_handlers)['error_reporting'])
if (false!==$this->call_function(end($this->error_handlers)['handler'],func_get_args())) return true;
$this->stash_ob();
$file=$errfile;
$line=$errline;
$file2=$line2=null;
if (isset($this->current_file)) $file2=$this->current_file;
if (isset($this->current_node)) $line2=$this->current_node->getLine();
$fatal=false;
switch($errno) //http://php.net/manual/en/errorfunc.constants.php
{
case E_USER_NOTICE:
case E_NOTICE:
$str="Notice";
break;
case E_ERROR:
case E_USER_ERROR:
$fatal=true;
$str="Error";
break;
case E_USER_WARNING:
case E_WARNING:
$str="Warning";
break;
default:
$str="Error(".$errno.")"; //unknown error type
}
if ($fatal)
$fatal_str="Fatal ";
else
$fatal_str="";
$this->inc("error/handled/all");
$this->inc("error/handled/{$str}");
if ($this->off_branch==0)
{
$this->inc("error/handled/mainbranch/all");
$this->inc("error/handled/mainbranch/{$str}");
$this->verbose("PHP-Emul {$str}: {$errstr} in {$file} on line {$line} ($file2:$line2)".PHP_EOL,0);
$this->output("PHP {$fatal_str}{$str}: {$errstr} in {$file2} on line {$line2}".PHP_EOL);
}
else
{
$this->inc("error/handled/offbranch/all");
$this->inc("error/handled/offbranch/{$str}");
$this->verbose(
strcolor("Off-Branch PHP-Emul {$str}: {$errstr} in {$file} on line {$line} ($file2:$line2)".PHP_EOL,"yellow")
,3);
}
if ($fatal or $this->strict)
{
$this->terminated=true;
$this->termination_value=-1;
if ($this->verbose>=2 and $this->off_branch==0)
{
$this->verbose("Emulator Backtrace:\n");
debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$this->verbose("Emulation Backtrace:\n");
echo $this->print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
}
$this->restore_ob();
return true;
}
protected function _error($msg,$node=null,$details=true, $errno=0)
{
$this->inc("error/all");
if ($this->off_branch!=0)
{
$this->inc("error/offbranch");
$this->verbose(
strcolor("(Off-Branch) ".$msg." in ".$this->current_file." on line ".$this->current_line.PHP_EOL
,"yellow")
,0);
return ;
}
$this->inc("error/mainbranch");
$this->verbose($msg." in ".$this->current_file." on line ".$this->current_line.PHP_EOL,0);
if ($details)
{
// print_r($node);
if ($this->verbose>=2)
{
$this->verbose("Emulator Backtrace:\n");
debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$this->verbose("Emulation Backtrace:\n");
echo $this->print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
}
if ($this->strict)
{
$this->terminated=true;
$this->termination_value=-2;
}
}
public $verbose_state=['lastVerbosity'=>1,'verbosities'=>[0]];
/**
* When called from another emulation context, can be used to increase all verbose levels
* @var integer
*/
public $verbose_base = 0;
/**
* Overriden verbose to distinguish between off-branch and main branch messages
* @param string $msg
* @param integer $verbosity 1 is basic messages, 0 is always shown, higher means less important
*/
function verbose($msg,$verbosity=1)
{
$verbosity+=$this->verbose_base;
$this->stash_ob(); #don't really need it here, handled at a higher level
// static $lastVerbosity=1;
// static $verbosities=[0];
$lastVerbosity=&$this->verbose_state['lastVerbosity'];
$verbosities=&$this->verbose_state['verbosities'];
$number="";
///Analyzer Part
$statementid=$this->statement_id();
$unique=(!isset($this->statements[$statementid]));
if ($unique)
$msg="✔ {$msg}";
if ($this->off_branch>0)
$msg=strcolor(str_repeat(">",$this->off_branch)." ".$msg,"light green"); //colored
///End Analyzer Part
if ($verbosity>0)
{
if ($verbosity>$lastVerbosity)
for ($i=0;$i<$verbosity-$lastVerbosity;++$i)
$verbosities[]=1;
else
{
if ($verbosity<$lastVerbosity)
for ($i=0;$i<$lastVerbosity-$verbosity;++$i)
array_pop($verbosities);
$verbosities[count($verbosities)-1]++;
}
$lastVerbosity=$verbosity;
$number=implode(".",$verbosities);
}
if ($number and $this->off_branch>0)
$number="($number)";
if ($this->verbose>=$verbosity) {
// echo str_repeat("---",$verbosity)." ".$number." ".$msg;
echo str_repeat("---",$verbosity)." ".$number." ".sprintf("[%d] ", getmypid()).$msg;
}
$this->restore_ob();
}
/**
* Overriden get_declarations counts what it sees
* @param [type] $node [description]
* @return [type] [description]
*/
function get_declarations($node)
{
$this->inc("statements/visited/sum");
$statementid=$this->statement_id($node);
if (isset($this->declared_statements[$statementid]))
$this->declared_statements[$statementid]++;
else
{
$this->inc("statements/visited/unique");
$this->declared_statements[$statementid]=1;
}
return parent::get_declarations($node);
}
/**
* Determines whether or not an expression is statically resolvable or not
* @param Node $node [description]
* @return boolean [description]
*/
function is_statically_resolvable($node)
{
//TODO: manually verified, wordpress only has these.
if ($node instanceof Node\Scalar)
return true;
if ($node instanceof Node\Expr\ConstFetch)
return true;
// if ($node instanceof Node\Expr\Assign)
// return $this->is_statically_resolvable($node->var)
// and $this->is_statically_resolvable($node->expr);
if ($node instanceof Node\Expr\Variable)
if (is_string($node->name) and array_key_exists($node->name, $this->variables))
return true;
if ($node instanceof Node\Expr\BinaryOp\Concat)
return $this->is_statically_resolvable($node->left) and $this->is_statically_resolvable($node->right);
if ($node instanceof Node\Expr\FuncCall)
if (isset($node->name->parts))
{
$name=$node->name->parts[0];
if ($name=="dirname"
or $name=="basename")
return true;
}
if ($node instanceof Node\Expr\UnaryMinus
or $node instanceof Node\Expr\BitwiseNot)
return $this->is_statically_resolvable($node->expr);
return false;
}
/**
* Used after parse to extract stats or static artifacts
* @param Node $node AST
* @return [type] [description]
*/
function node_traverser($node)
{
if (is_array($node))
{
foreach ($node as $n)
$this->node_traverser($n);
return;
}
if ($node instanceof Node)
{
foreach ($node->getSubNodeNames() as $name)
$this->node_traverser($node->$name);
}
//static resolving
if ($this->static)
{
if ($node instanceof Node\Stmt\Const_)
{
foreach ($node->consts as $const)
{
$this->verbose("Constant found in static mode: ".
$const->name."=".$this->evaluate_expression($const->value)."\n");
$this->constant_set($const->name,$this->evaluate_expression($const->value));
}
}
if ($node instanceof Node\Expr\Assign)
{
$this->verbose("Assignment found in static mode: '".$this->print_ast($node)."' \n");
if ($this->is_statically_resolvable($node->expr))
{
$val=$this->evaluate_expression($node->expr);
if ($val!==null)
$this->variable_set($node->var,$val);
// var_dump($this->variables);
}
}
if ($node instanceof Node\Expr\FuncCall)
{
$name=$node->name;
if (isset($name->parts))
$name=$name->parts[0];
if (is_string($name) and $name=="define")
{
$this->verbose("Define found in static mode: '".$this->print_ast($node)."' \n");
$value=$node->args[1]->value;
if ($this->is_statically_resolvable($value))
$this->evaluate_expression($node);
}
}
}
//stats
if ($node instanceof Node\Stmt)
{
$this->inc("statements/parsed");
}
if ($node instanceof Node\Expr)
{
if ($node instanceof Node\Expr\Exit_)
$this->inc("node/exit");
elseif ($node instanceof Node\Expr\Include_)
{
#TODO: record these includes
#TODO: try to evaluate those includes that are not run after the script ends
$name=$this->current_file.":".$node->getLine();
if (isset($this->includes[$name]))
$new="old";
else
$new="new";
// $this->verbose("Include found ({$new}): (".$this->print_ast($node->expr).")\n",3);
// $this->verbose("Include found ({$new}): (".$this->evaluate_expression($node->expr).")\n",3);
$this->includes[$name]=$node;
$this->inc("node/include");
}
}
}
/**
* overriden parse to count parsed files and count their statements
* @param [type] $file [description]
* @return [type] [description]
*/
public function parse($file)
{
$this->inc("parsed/files/all");
$ast=parent::parse($file);
if (isset($this->all_files[$file]))
{
$this->all_files[$file]++;
}
else
{
$this->inc("parsed/files/unique");
$this->all_files[$file]=1;
$bu=$this->current_file;
$this->current_file=$file;
$this->node_traverser($ast);
$this->current_file=$bu;
}
// $this->inc("statements/parsed/all",$this->count_statements($ast));
// $this->inc("statements/parsed/no-expressions",$this->count_statements($ast,true));
// $bu=$this->current_file;
// $this->current_file=$file;
// $this->node_traverser($ast);
// $this->current_file=$bu;
return $ast;
}
/**
* Returns a 32bit integer supposedly unique for each statement
* based on File, Line and statement type
* meaning that two similar statements on one line will have similar ids
* @param Node $node optional
* @return integer or null
*/
function statement_id($node=null)
{
if ($node===null)
$node=$this->current_node;
if (is_object($node) and method_exists($node, "getLine"))
//TODO:works for expressions too, make it statement only
{
$line=$node->getLine();
$file=$this->current_file;
$type=get_class($node);
return crc32("$file:$line:$type");
}
return 0;
}
/**
* Override for try/catch handling so it doesn't pop
* out of isolation
* @param [type] $e [description]
* @return [type] [description]
*/
public function throw_exception($e)
{
#TODO: make the isolation for try/catch in off_branches sound
//hacky workaround, exceptions will simply terminate the off-branch
if ($this->off_branch>0)
return $this->exception_handler($e);
parent::throw_exception($e);
}
/**
* Creates a snapshot of current emulator state
* @param boolean $swap whether to put the created snapshot as active
* @return either the copy or original state, based on swap
*/
public function snapshot($swap=true)
{
$items=array_keys($this->state);
$items[]='verbose_state';
$res=[];
foreach ($items as $item )
$res[$item]=&$this->{$item};
// echo "Statement ID: ",$this->statement_id(),PHP_EOL;
if (function_exists("deep_copy"))
$r=deep_copy($res);
else
{
require_once "deepcopy.php";
@$r=&deep_copy($res);
}
gc_collect_cycles();
if ($swap) //swap the snapshot with active state
{
foreach ($r as $key=>$value)
$this->{$key}=&$r[$key];//$value;
return $res;
}
else
return $r;
}
/**
* restore state from snapshot
* @param [type] $snapshot [description]
* @return [type] [description]
*/
public function restore_snapshot($snapshot)
{
foreach ($snapshot as $key=>$value)
$this->{$key}=&$snapshot[$key];//$value;
gc_collect_cycles();
}
// public function run_file($file)
// {
// $result = parent::run_file($file);
// while (sizeof($this->rerun_points) > 0 && end($this->rerun_points)->current_file === $file) {
// $this->verbose(strcolor(
// sprintf("Restoring concolic path %s [%s:%s] (depth=%d)...\n",$this->statement_id(),$this->current_file, $this->current_line, $this->off_branch)
// ,"light green"),0);
// $rerun_point = array_pop($this->rerun_points);
// $this->restore_snapshot($rerun_point->snapshot);
// $ast = $this->parse($file);
// $result = parent::run_code($ast, $this->current_node);
// }
// return $result;
// }
/**
* Starts an off-branch by taking a snapshot and applying it.
* @return [type] [description]
*/
function off_branch_start()
{
// if ($this->off_branch==0) //entering
// {
// $this->mock_functions['serialize']="serialize_mock2";
// $this->mock_functions['unserialize']="unserialize_mock2";
// }
$this->off_branch++;
$this->verbose(strcolor(
sprintf("Branching off at %s [%s:%s] (depth=%d)...\n",$this->statement_id(),$this->current_file, $this->current_line, $this->off_branch)
,"light green"),0);
if ($this->off_branch_recursive_isolation or $this->off_branch==1)
$this->snapshot_stack[]=$this->snapshot();
if ($this->off_branch>=$this->off_branch_depth_limit)
{
$this->verbose(strcolor("Off branches exhausted, ignoring this path...\n","red"),0);
$this->terminated=true;
}
}
/**
* Ends an off branch, restoring the parent branch
* @return [type] [description]
*/
function off_branch_end()
{
//NOTE: without this, some branches will run to the end of the program
//this causes any hiccup in a branch to result in dismissal of the entire branch
//from the main path. not very accurate, but yields acceptable results.
// if ($this->off_branch==1)
{
if ($this->terminated)
$this->terminated=false;
}
if ($this->off_branch_recursive_isolation or $this->off_branch==1)
$this->restore_snapshot(array_pop($this->snapshot_stack));
$this->off_branch--; //FIXME: move this to the bottom of this function, should return to main branch after restoring
$this->verbose(strcolor("Branch-off (depth=".($this->off_branch+1).") restored\n","light green"),0);
if ($this->off_branch==0)
{
$this->mock_functions['serialize']="serialize_mock";
$this->mock_functions['unserialize']="unserialize_mock";
$this->verbose(strcolor("Resuming main branch...\n","green"),0);
}
}
/**
* Run code isolated
* @param [type] $stmts [description]
* @param [type] $node [description]
* @param [type] $branch used to determine branches of one statement
* @return [type] [description]
*/
function run_off_branch_code($stmts,$node,$branch)
{
$statementid=$this->statement_id($node);
if (!isset($this->off_branch_execution[$statementid]))
$this->off_branch_execution[$statementid]=[];
if (!isset($this->off_branch_execution[$statementid][$branch]))
$this->off_branch_execution[$statementid][$branch]=0;
$this->inc("off-branch/all");
if (++$this->off_branch_execution[$statementid][$branch] > $this->off_branch_execution_limit)
{
$this->verbose(strcolor("This off-branch has already been executed, ignoring.\n","light green"),3);
return; //run everything twice at most
}
$this->inc("off-branch/executed");
$this->off_branch_start();
$this->run_code($stmts);
$this->off_branch_end();
}
function evaluate_expression($node, &$is_symbolic = false)
{
if ($node instanceof Node\Expr\Exit_ and $this->diehard)
{
$this->inc("exit/all");
if ($this->off_branch==0)
{
$this->verbose("Exit encountered in main branch, instead of terminating, I will resume as off-branch...\n",1);
$this->inc("exit/avoided");
$this->off_branch_start(); //no corresponding end, results in shutdown in off_branch mode
}
else
{
$this->verbose("Exit encountered in off branch, instead of terminating, I will resume the off-branch!\n",2);
$this->inc("exit/ignored");
}
return null;
}
if ($node instanceof Node\Expr\Include_)
$this->inc("statements/executed/include");
return parent::evaluate_expression($node, $is_symbolic);
}
function file_line($prepend="",$append="")
{
return "{$prepend}{$this->current_file}:{$this->current_line}{$append}";
}
function add_rerun_point(Node $current_condition) {
$this->rerun_points[] = new RerunPoint($this->snapshot(false), $this->statement_id($current_condition), $this->current_file);
}
public $if_nesting =0;
/**
* Overriden run_statement that counts and runs ifs concolicly
* @param [type] $node [description]
* @return [type] [description]
*/
function run_statement($node)
{
//crashes:
// if ($node instanceof Node\Stmt\Return_ and !$node->expr and $this->off_branch>0 and $this->diehard)
// {
// $this->verbose("Empty return encountered in off branch, instead of returning, I will resume the off-branch...\n",1);
// $this->return_value=null;
// $this->inc("return/avoided");
// return;
// }
$this->inc("statements/executed/sum");
$statementid=$this->statement_id($node);
if (!isset($this->statements[$statementid]))
{
$this->statements[$statementid]=1;
$this->inc("statements/executed/unique");
}
else
$this->statements[$statementid]++;
if ($node instanceof Node\Stmt\If_)
{
$this->inc("if/count");
$this->inc("if/branches");
if ($this->off_branch)
{
$this->inc("counterfactual/if/count");
$this->inc("counterfactual/if/branches");
}
if (is_array($node->elseifs))
foreach ($node->elseifs as $elseif)
{
if ($this->off_branch)
{
$this->inc("counterfactual/if/branches");
$this->inc("counterfactual/if/elseifs");
}
$this->inc("if/branches");
$this->inc("if/elseifs");
}
if (isset($node->else))
{
if ($this->off_branch)
{
$this->inc("counterfactual/if/branches");
$this->inc("counterfactual/if/elses");
}
$this->inc("if/branches");
$this->inc("if/elses");
}
if (!count($node->elseifs) and !isset($node->else))
{
if ($this->off_branch)
{
$this->inc("counterfactual/if/single");
}
$this->inc("if/single");
}
if ($this->concolic) //execute them all!
{
// TODO: For proper implementation here
// $branch_statements = null;
// $branch_execution_done = false;
// // Check if one of the conditions are factual and the condition is satisfied.
// $branch_evaled_conditions = [];
// $branch_evaled_conditions[$this->statement_id($node->cond)] = $this->evaluate_expression($node->cond);
// // If main branch is factual, only execute that one
// if ($branch_evaled_conditions[$this->statement_id($node->cond)]) {
// $branch_statements = $node->stmts;
// $branch_execution_done = true;
// $condition = $this->print_ast($node->cond);
// }
// else {
// // Check if any of the elseif and else branches are factual
// $else_statements = [];
// if (is_array($node->elseifs)) {
// $else_statements = $node->elseifs;
// }
// foreach ()
// }
// if ($this->evaluate_expression())
$selected_branch_statements = null;
$break = false;
// Check if any of the branches are concrete
$have_symbolic_conditions = false;
$is_symbolic = false;
$this->current_line = $node->getLine();
$this->lineLogger->logNodeCoverage($node->cond, $this->current_file);
$main_branch_condition = $this->evaluate_expression($node->cond, $is_symbolic);
// Function calls inside if may change current line, revert it to original value
$this->current_line = $node->getLine();
// $this->verbose('main branch condition: '.print_r($main_branch_condition, true).PHP_EOL);
if ($main_branch_condition && !$main_branch_condition instanceof SymbolicVariable) {
// Condition of this branch is concretely satisfied
// $this->verbose('Not forking'.PHP_EOL);
$break = true;
$selected_branch_statements = $node->stmts;
$condition = $this->print_ast($node->cond);
}
elseif ($main_branch_condition instanceof SymbolicVariable) {
// $this->verbose('should be forking'.PHP_EOL);
$forked_process_info = $this->fork_execution([$this->current_file, $this->current_line, true]);
if ($forked_process_info !== false) {
list($pid, $child_pid) = $forked_process_info;
if ($child_pid === 0) {
// $this->terminate_early = true;
// $this->verbose(strcolor(sprintf('%d will terminate early.'.PHP_EOL, getmypid()), 'green'));
$selected_branch_statements = $node->stmts;
$break = true;
}
} else {
// Terminated
return;
}
}
$branch_conditions = [];
if (!$break && is_array($node->elseifs) && sizeof($node->elseifs) > 0) {
// Main branch is not satisfied, now checking the elseif branches
foreach ($node->elseifs as $elseif) {
$this->current_line = $elseif->cond->getLine();
$this->lineLogger->logNodeCoverage($elseif->cond, $this->current_file);
$branch_condition = $this->evaluate_expression($elseif->cond);
$branch_conditions[$this->statement_id($elseif)] = $branch_condition;
if ($branch_condition && !$branch_condition instanceof SymbolicVariable) {
// Condition of this branch is concretely satisfied
$break=true;
$selected_branch_statements = $elseif->stmts;
$condition = $this->print_ast($elseif->cond);
break;
}
elseif ($branch_condition instanceof SymbolicVariable) {
// Elseif condition is symbolic
$forked_process_info = $this->fork_execution([$this->current_file, $this->current_line, true]);
if ($forked_process_info !== false) {
list($pid, $child_pid) = $forked_process_info;
if ($child_pid === 0) {
// $this->verbose(strcolor(sprintf('%d will terminate early.'.PHP_EOL, getmypid()), 'green'));
// $this->terminate_early = true;
if (isset($elseif->cond)) {
$condition = $this->print_ast($elseif->cond);
} else {
$condition = 'else';
}
$selected_branch_statements = $elseif->stmts;
$break = true;
break;
}
} else {
// Terminated
return;
}
}
}
}
if (!$break) {
// None of the If/Elseif conditions were satisfied
// Therefore we run Else
if (isset($node->else)) {
// run else
$break = true;
$selected_branch_statements = $node->else->stmts;
$condition="not ".$this->print_ast($node->cond);
}
else {
// Nothing to do
$break = true;
$condition = '';
}
}
if ($selected_branch_statements !==null)
{
if (!isset($condition)) {
$condition = 'not set';
}
array_push($this->active_conditions,$condition);
$this->if_nesting++;
// $this->verbose("Running the code inside if body ".$node->getStartLine().PHP_EOL);
$res = $this->run_code($selected_branch_statements);
$this->if_nesting--;
array_pop($this->active_conditions);
return $res;
}
// if ($this->terminate_early) {
// $this->shutdown();
// exit();
// }
return;
}
else //non-concolic
{
$condition=$this->print_ast($node->cond).$this->file_line(" (",")");
array_push($this->active_conditions,$condition);
$res = parent::run_statement($node);
array_pop($this->active_conditions);
return $res;
}
}
elseif ($node instanceof Node\Stmt\Switch_)
{
//its hard to determine which cases will be executed
//prior to doing it, because they break the execution themselves
//we need to find cases that are not executed and off_branch them
//but it might be impossible to do so prior to running the actual cases
//
$this->inc("switch/count");
$this->inc("switch/branches",count($node->cases));
if ($this->off_branch)
{
$this->inc("counterfactual/switch/count");
$this->inc("counterfactual/switch/branches", count($node->cases));
}
if ($this->concolic)
{
$break = false;
$master_condition = $this->evaluate_expression($node->cond);
$this->verbose("Concolic switch with ".count($node->cases)." cases found...\n",3);
$run_next_case = false;
// If the main condition is Symbolic then run everything
if ($master_condition instanceof SymbolicVariable) {
$this->verbose(strcolor("Switch condition relies on SymbolicVariable, running all branches\n", "light green"), 4);
foreach ($node->cases as $case) {
$this->current_line = $case->getStartLine();
if ($case->cond === null) { // If default branch, do not fork
$this->verbose(strcolor(
sprintf("Running default branch %s [%s:%s] ...\n", $this->statement_id(), $this->current_file, $this->current_line)