', $diff);
    junit_mark_test_as($restype, $shortname, $tested, null, $info, $diff);
    return $restype[0] . 'ED';
}
function comp_line($l1, $l2, $is_reg)
{
    if ($is_reg) {
        return preg_match('/^' . $l1 . '$/s', $l2);
    } else {
        return !strcmp($l1, $l2);
    }
}
function count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $idx2, $cnt1, $cnt2, $steps)
{
    $equal = 0;
    while ($idx1 < $cnt1 && $idx2 < $cnt2 && comp_line($ar1[$idx1], $ar2[$idx2], $is_reg)) {
        $idx1++;
        $idx2++;
        $equal++;
        $steps--;
    }
    if (--$steps > 0) {
        $eq1 = 0;
        $st = $steps / 2;
        for ($ofs1 = $idx1 + 1; $ofs1 < $cnt1 && $st-- > 0; $ofs1++) {
            $eq = @count_array_diff($ar1, $ar2, $is_reg, $w, $ofs1, $idx2, $cnt1, $cnt2, $st);
            if ($eq > $eq1) {
                $eq1 = $eq;
            }
        }
        $eq2 = 0;
        $st = $steps;
        for ($ofs2 = $idx2 + 1; $ofs2 < $cnt2 && $st-- > 0; $ofs2++) {
            $eq = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $ofs2, $cnt1, $cnt2, $st);
            if ($eq > $eq2) {
                $eq2 = $eq;
            }
        }
        if ($eq1 > $eq2) {
            $equal += $eq1;
        } else if ($eq2 > 0) {
            $equal += $eq2;
        }
    }
    return $equal;
}
function generate_array_diff($ar1, $ar2, $is_reg, $w)
{
    $idx1 = 0;
    $cnt1 = @count($ar1);
    $idx2 = 0;
    $cnt2 = @count($ar2);
    $diff = array();
    $old1 = array();
    $old2 = array();
    while ($idx1 < $cnt1 && $idx2 < $cnt2) {
        if (comp_line($ar1[$idx1], $ar2[$idx2], $is_reg)) {
            $idx1++;
            $idx2++;
            continue;
        } else {
            $c1 = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1 + 1, $idx2, $cnt1, $cnt2, 10);
            $c2 = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $idx2 + 1, $cnt1, $cnt2, 10);
            if ($c1 > $c2) {
                $old1[$idx1] = sprintf("%03d- ", $idx1 + 1) . $w[$idx1++];
            } else if ($c2 > 0) {
                $old2[$idx2] = sprintf("%03d+ ", $idx2 + 1) . $ar2[$idx2++];
            } else {
                $old1[$idx1] = sprintf("%03d- ", $idx1 + 1) . $w[$idx1++];
                $old2[$idx2] = sprintf("%03d+ ", $idx2 + 1) . $ar2[$idx2++];
            }
        }
    }
    reset($old1);
    $k1 = key($old1);
    $l1 = -2;
    reset($old2);
    $k2 = key($old2);
    $l2 = -2;
    while ($k1 !== null || $k2 !== null) {
        if ($k1 == $l1 + 1 || $k2 === null) {
            $l1 = $k1;
            $diff[] = current($old1);
            $k1 = next($old1) ? key($old1) : null;
        } else if ($k2 == $l2 + 1 || $k1 === null) {
            $l2 = $k2;
            $diff[] = current($old2);
            $k2 = next($old2) ? key($old2) : null;
        } else if ($k1 < $k2) {
            $l1 = $k1;
            $diff[] = current($old1);
            $k1 = next($old1) ? key($old1) : null;
        } else {
            $l2 = $k2;
            $diff[] = current($old2);
            $k2 = next($old2) ? key($old2) : null;
        }
    }
    while ($idx1 < $cnt1) {
        $diff[] = sprintf("%03d- ", $idx1 + 1) . $w[$idx1++];
    }
    while ($idx2 < $cnt2) {
        $diff[] = sprintf("%03d+ ", $idx2 + 1) . $ar2[$idx2++];
    }
    return $diff;
}
function generate_diff($wanted, $wanted_re, $output)
{
    $w = explode("\n", $wanted);
    $o = explode("\n", $output);
    $r = is_null($wanted_re) ? $w : explode("\n", $wanted_re);
    $diff = generate_array_diff($r, $o, !is_null($wanted_re), $w);
    return implode(PHP_EOL, $diff);
}
function error($message)
{
    echo "ERROR: {$message}\n";
    exit(1);
}
function settings2array($settings, &$ini_settings)
{
    foreach ($settings as $setting) {
        if (strpos($setting, '=') !== false) {
            $setting = explode("=", $setting, 2);
            $name = trim($setting[0]);
            $value = trim($setting[1]);
            if ($name == 'extension' || $name == 'zend_extension') {
                if (!isset($ini_settings[$name])) {
                    $ini_settings[$name] = array();
                }
                $ini_settings[$name][] = $value;
            } else {
                $ini_settings[$name] = $value;
            }
        }
    }
}
function settings2params($ini_settings)
{
    $settings = '';
    foreach($ini_settings as $name => $value) {
        if (is_array($value)) {
            foreach($value as $val) {
                $val = addslashes($val);
                $settings .= " -d \"$name=$val\"";
            }
        } else {
            if (substr(PHP_OS, 0, 3) == "WIN" && !empty($value) && $value[0] == '"') {
                $len = strlen($value);
                if ($value[$len - 1] == '"') {
                    $value[0] = "'";
                    $value[$len - 1] = "'";
                }
            } else {
                $value = addslashes($value);
            }
            $settings .= " -d \"$name=$value\"";
        }
    }
    return $settings;
}
function compute_summary()
{
    global $n_total, $test_results, $ignored_by_ext, $sum_results, $percent_results;
    $n_total = count($test_results);
    $n_total += $ignored_by_ext;
    $sum_results = array(
        'PASSED' => 0,
        'WARNED' => 0,
        'SKIPPED' => 0,
        'FAILED' => 0,
        'BORKED' => 0,
        'LEAKED' => 0,
        'XFAILED' => 0,
        'XLEAKED' => 0
    );
    foreach ($test_results as $v) {
        $sum_results[$v]++;
    }
    $sum_results['SKIPPED'] += $ignored_by_ext;
    $percent_results = array();
    foreach ($sum_results as $v => $n) {
        $percent_results[$v] = (100.0 * $n) / $n_total;
    }
}
function get_summary($show_ext_summary, $show_html)
{
    global $exts_skipped, $exts_tested, $n_total, $sum_results, $percent_results, $end_time, $start_time, $failed_test_summary, $PHP_FAILED_TESTS, $valgrind;
    $x_total = $n_total - $sum_results['SKIPPED'] - $sum_results['BORKED'];
    if ($x_total) {
        $x_warned = (100.0 * $sum_results['WARNED']) / $x_total;
        $x_failed = (100.0 * $sum_results['FAILED']) / $x_total;
        $x_xfailed = (100.0 * $sum_results['XFAILED']) / $x_total;
        $x_xleaked = (100.0 * $sum_results['XLEAKED']) / $x_total;
        $x_leaked = (100.0 * $sum_results['LEAKED']) / $x_total;
        $x_passed = (100.0 * $sum_results['PASSED']) / $x_total;
    } else {
        $x_warned = $x_failed = $x_passed = $x_leaked = $x_xfailed = $x_xleaked = 0;
    }
    $summary = '';
    if ($show_html) {
        $summary .= "\n";
    }
    if ($show_ext_summary) {
        $summary .= '
=====================================================================
TEST RESULT SUMMARY
---------------------------------------------------------------------
Exts skipped    : ' . sprintf('%4d', $exts_skipped) . '
Exts tested     : ' . sprintf('%4d', $exts_tested) . '
---------------------------------------------------------------------
';
    }
    $summary .= '
Number of tests : ' . sprintf('%4d', $n_total) . '          ' . sprintf('%8d', $x_total);
    if ($sum_results['BORKED']) {
        $summary .= '
Tests borked    : ' . sprintf('%4d (%5.1f%%)', $sum_results['BORKED'], $percent_results['BORKED']) . ' --------';
    }
    $summary .= '
Tests skipped   : ' . sprintf('%4d (%5.1f%%)', $sum_results['SKIPPED'], $percent_results['SKIPPED']) . ' --------
Tests warned    : ' . sprintf('%4d (%5.1f%%)', $sum_results['WARNED'], $percent_results['WARNED']) . ' ' . sprintf('(%5.1f%%)', $x_warned) . '
Tests failed    : ' . sprintf('%4d (%5.1f%%)', $sum_results['FAILED'], $percent_results['FAILED']) . ' ' . sprintf('(%5.1f%%)', $x_failed);
    if ($sum_results['XFAILED']) {
        $summary .= '
Expected fail   : ' . sprintf('%4d (%5.1f%%)', $sum_results['XFAILED'], $percent_results['XFAILED']) . ' ' . sprintf('(%5.1f%%)', $x_xfailed);
    }
    if ($valgrind) {
        $summary .= '
Tests leaked    : ' . sprintf('%4d (%5.1f%%)', $sum_results['LEAKED'], $percent_results['LEAKED']) . ' ' . sprintf('(%5.1f%%)', $x_leaked);
        if ($sum_results['XLEAKED']) {
            $summary .= '
Expected leak   : ' . sprintf('%4d (%5.1f%%)', $sum_results['XLEAKED'], $percent_results['XLEAKED']) . ' ' . sprintf('(%5.1f%%)', $x_xleaked);
        }
    }
    $summary .= '
Tests passed    : ' . sprintf('%4d (%5.1f%%)', $sum_results['PASSED'], $percent_results['PASSED']) . ' ' . sprintf('(%5.1f%%)', $x_passed) . '
---------------------------------------------------------------------
Time taken      : ' . sprintf('%4d seconds', $end_time - $start_time) . '
=====================================================================
';
    $failed_test_summary = '';
    if (count($PHP_FAILED_TESTS['SLOW'])) {
        usort($PHP_FAILED_TESTS['SLOW'], function ($a, $b) {
            return $a['info'] < $b['info'] ? 1 : -1;
        });
        $failed_test_summary .= '
=====================================================================
SLOW TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['SLOW'] as $failed_test_data) {
            $failed_test_summary .= sprintf('(%.3f s) ', $failed_test_data['info']) . $failed_test_data['test_name'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['XFAILED'])) {
        $failed_test_summary .= '
=====================================================================
EXPECTED FAILED TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['XFAILED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['BORKED'])) {
        $failed_test_summary .= '
=====================================================================
BORKED TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['BORKED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['FAILED'])) {
        $failed_test_summary .= '
=====================================================================
FAILED TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['FAILED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['WARNED'])) {
        $failed_test_summary .= '
=====================================================================
WARNED TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['WARNED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['LEAKED'])) {
        $failed_test_summary .= '
=====================================================================
LEAKED TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['LEAKED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if (count($PHP_FAILED_TESTS['XLEAKED'])) {
        $failed_test_summary .= '
=====================================================================
EXPECTED LEAK TEST SUMMARY
---------------------------------------------------------------------
';
        foreach ($PHP_FAILED_TESTS['XLEAKED'] as $failed_test_data) {
            $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
        }
        $failed_test_summary .= "=====================================================================\n";
    }
    if ($failed_test_summary && !getenv('NO_PHPTEST_SUMMARY')) {
        $summary .= $failed_test_summary;
    }
    if ($show_html) {
        $summary .= "";
    }
    return $summary;
}
function show_start($start_time)
{
    global $html_output, $html_file;
    if ($html_output) {
        fwrite($html_file, "Time Start: " . date('Y-m-d H:i:s', $start_time) . "
\n");
        fwrite($html_file, "\n");
    }
    echo "TIME START " . date('Y-m-d H:i:s', $start_time) . "\n=====================================================================\n";
}
function show_end($end_time)
{
    global $html_output, $html_file;
    if ($html_output) {
        fwrite($html_file, "
\n");
        fwrite($html_file, "Time End: " . date('Y-m-d H:i:s', $end_time) . "
\n");
    }
    echo "=====================================================================\nTIME END " . date('Y-m-d H:i:s', $end_time) . "\n";
}
function show_summary()
{
    global $html_output, $html_file;
    if ($html_output) {
        fwrite($html_file, "
\n" . get_summary(true, true));
    }
    echo get_summary(true, false);
}
function show_redirect_start($tests, $tested, $tested_file)
{
    global $html_output, $html_file, $line_length, $SHOW_ONLY_GROUPS;
    if ($html_output) {
        fwrite($html_file, "| ---> $tests ($tested [$tested_file]) begin | 
\n");
    }
    if (!$SHOW_ONLY_GROUPS || in_array('REDIRECT', $SHOW_ONLY_GROUPS)) {
        echo "REDIRECT $tests ($tested [$tested_file]) begin\n";
    } else {
        clear_show_test();
    }
}
function show_redirect_ends($tests, $tested, $tested_file)
{
    global $html_output, $html_file, $line_length, $SHOW_ONLY_GROUPS;
    if ($html_output) {
        fwrite($html_file, "| ---> $tests ($tested [$tested_file]) done | 
\n");
    }
    if (!$SHOW_ONLY_GROUPS || in_array('REDIRECT', $SHOW_ONLY_GROUPS)) {
        echo "REDIRECT $tests ($tested [$tested_file]) done\n";
    } else {
        clear_show_test();
    }
}
function show_test($test_idx, $shortname)
{
    global $test_cnt;
    global $line_length;
    $str = "TEST $test_idx/$test_cnt [$shortname]\r";
    $line_length = strlen($str);
    echo $str;
    flush();
}
function clear_show_test() {
    global $line_length;
    // Parallel testing
    global $workerID;
    if (!$workerID) {
        // Write over the last line to avoid random trailing chars on next echo
        echo str_repeat(" ", $line_length), "\r";
    }
}
function parse_conflicts(string $text) : array {
    // Strip comments
    $text = preg_replace('/#.*/', '', $text);
    return array_map('trim', explode("\n", trim($text)));
}
function show_result($result, $tested, $tested_file, $extra = '', $temp_filenames = null)
{
    global $html_output, $html_file, $temp_target, $temp_urlbase, $line_length, $SHOW_ONLY_GROUPS;
    if (!$SHOW_ONLY_GROUPS || in_array($result, $SHOW_ONLY_GROUPS)) {
        echo "$result $tested [$tested_file] $extra\n";
    } else if (!$SHOW_ONLY_GROUPS) {
        clear_show_test();
    }
    if ($html_output) {
        if (isset($temp_filenames['file']) && file_exists($temp_filenames['file'])) {
            $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['file']);
            $tested = "$tested";
        }
        if (isset($temp_filenames['skip']) && file_exists($temp_filenames['skip'])) {
            if (empty($extra)) {
                $extra = "skipif";
            }
            $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['skip']);
            $extra = "$extra";
        } else if (empty($extra)) {
            $extra = " ";
        }
        if (isset($temp_filenames['diff']) && file_exists($temp_filenames['diff'])) {
            $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['diff']);
            $diff = "diff";
        } else {
            $diff = " ";
        }
        if (isset($temp_filenames['mem']) && file_exists($temp_filenames['mem'])) {
            $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['mem']);
            $mem = "leaks";
        } else {
            $mem = " ";
        }
        fwrite(
            $html_file,
            "" .
                "| $result | " .
                "$tested | " .
                "$extra | " .
                "$diff | " .
                "$mem | " .
                "
\n"
        );
    }
}
function junit_init()
{
    // Check whether a junit log is wanted.
    global $workerID;
    $JUNIT = getenv('TEST_PHP_JUNIT');
    if (empty($JUNIT)) {
        $GLOBALS['JUNIT'] = false;
        return;
    }
    if ($workerID) {
        $fp = null;
    } else if (!$fp = fopen($JUNIT, 'w')) {
        error("Failed to open $JUNIT for writing.");
    }
    $GLOBALS['JUNIT'] = array(
        'fp' => $fp,
        'name' => 'PHP',
        'test_total' => 0,
        'test_pass' => 0,
        'test_fail' => 0,
        'test_error' => 0,
        'test_skip' => 0,
        'test_warn' => 0,
        'execution_time' => 0,
        'suites' => array(),
        'files' => array()
    );
}
function junit_save_xml()
{
    global $JUNIT;
    if (!junit_enabled()) return;
    $xml = '<' . '?' . 'xml version="1.0" encoding="UTF-8"' . '?' . '>' . PHP_EOL;
    $xml .= sprintf(
        '' . PHP_EOL,
        $JUNIT['name'],
        $JUNIT['test_total'],
        $JUNIT['test_fail'],
        $JUNIT['test_error'],
        $JUNIT['test_skip'],
        $JUNIT['execution_time']
    );
    $xml .= junit_get_suite_xml();
    $xml .= '';
    fwrite($JUNIT['fp'], $xml);
}
function junit_get_suite_xml($suite_name = '')
{
    global $JUNIT;
    $result = "";
    foreach ($JUNIT['suites'] as $suite_name => $suite) {
        $result .= sprintf(
            '' . PHP_EOL,
            $suite['name'],
            $suite['test_total'],
            $suite['test_fail'],
            $suite['test_error'],
            $suite['test_skip'],
            $suite['execution_time']
        );
        if (!empty($suite_name)) {
            foreach ($suite['files'] as $file) {
                $result .= $JUNIT['files'][$file]['xml'];
            }
        }
        $result .= '' . PHP_EOL;
    }
    return $result;
}
function junit_enabled()
{
    global $JUNIT;
    return !empty($JUNIT);
}
/**
 * @param array|string $type
 * @param string $file_name
 * @param string $test_name
 * @param int|string $time
 * @param string $message
 * @param string $details
 * @return void
 */
function junit_mark_test_as($type, $file_name, $test_name, $time = null, $message = '', $details = '')
{
    global $JUNIT;
    if (!junit_enabled()) return;
    $suite = junit_get_suitename_for($file_name);
    junit_suite_record($suite, 'test_total');
    $time = $time ?? junit_get_timer($file_name);
    junit_suite_record($suite, 'execution_time', $time);
    $escaped_details = htmlspecialchars($details, ENT_QUOTES, 'UTF-8');
    $escaped_details = preg_replace_callback('/[\0-\x08\x0B\x0C\x0E-\x1F]/', function ($c) {
        return sprintf('[[0x%02x]]', ord($c[0]));
    }, $escaped_details);
    $escaped_message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
    $escaped_test_name = htmlspecialchars($file_name . ' (' . $test_name . ')', ENT_QUOTES);
    $JUNIT['files'][$file_name]['xml'] = "\n";
    if (is_array($type)) {
        $output_type = $type[0] . 'ED';
        $temp = array_intersect(array('XFAIL', 'XLEAK', 'FAIL', 'WARN'), $type);
        $type = reset($temp);
    } else {
        $output_type = $type . 'ED';
    }
    if ('PASS' == $type || 'XFAIL' == $type || 'XLEAK' == $type) {
        junit_suite_record($suite, 'test_pass');
    } elseif ('BORK' == $type) {
        junit_suite_record($suite, 'test_error');
        $JUNIT['files'][$file_name]['xml'] .= "\n";
    } elseif ('SKIP' == $type) {
        junit_suite_record($suite, 'test_skip');
        $JUNIT['files'][$file_name]['xml'] .= "$escaped_message\n";
    } elseif ('WARN' == $type) {
        junit_suite_record($suite, 'test_warn');
        $JUNIT['files'][$file_name]['xml'] .= "$escaped_message\n";
    } elseif ('FAIL' == $type) {
        junit_suite_record($suite, 'test_fail');
        $JUNIT['files'][$file_name]['xml'] .= "$escaped_details\n";
    } else {
        junit_suite_record($suite, 'test_error');
        $JUNIT['files'][$file_name]['xml'] .= "$escaped_details\n";
    }
    $JUNIT['files'][$file_name]['xml'] .= "\n";
}
function junit_suite_record($suite, $param, $value = 1)
{
    global $JUNIT;
    $JUNIT[$param] += $value;
    $JUNIT['suites'][$suite][$param] += $value;
}
function junit_get_timer($file_name)
{
    global $JUNIT;
    if (!junit_enabled()) return 0;
    if (isset($JUNIT['files'][$file_name]['total'])) {
        return number_format($JUNIT['files'][$file_name]['total'], 4);
    }
    return 0;
}
function junit_start_timer($file_name)
{
    global $JUNIT;
    if (!junit_enabled()) return;
    if (!isset($JUNIT['files'][$file_name]['start'])) {
        $JUNIT['files'][$file_name]['start'] = microtime(true);
        $suite = junit_get_suitename_for($file_name);
        junit_init_suite($suite);
        $JUNIT['suites'][$suite]['files'][$file_name] = $file_name;
    }
}
function junit_get_suitename_for($file_name)
{
    return junit_path_to_classname(dirname($file_name));
}
function junit_path_to_classname($file_name)
{
    global $JUNIT;
    if (!junit_enabled()) return '';
    $ret = $JUNIT['name'];
    $_tmp = array();
    // lookup whether we're in the PHP source checkout
    $max = 5;
    if (is_file($file_name)) {
        $dir = dirname(realpath($file_name));
    } else {
        $dir = realpath($file_name);
    }
    do {
        array_unshift($_tmp, basename($dir));
        $chk = $dir . DIRECTORY_SEPARATOR . "main" . DIRECTORY_SEPARATOR . "php_version.h";
        $dir = dirname($dir);
    } while (!file_exists($chk) && --$max > 0);
    if (file_exists($chk)) {
        if ($max) {
            array_shift($_tmp);
        }
        foreach ($_tmp as $p) {
            $ret .= "." . preg_replace(",[^a-z0-9]+,i", ".", $p);
        }
        return $ret;
    }
    return $JUNIT['name'] . '.' . str_replace(array(DIRECTORY_SEPARATOR, '-'), '.', $file_name);
}
function junit_init_suite($suite_name)
{
    global $JUNIT;
    if (!junit_enabled()) return;
    if (!empty($JUNIT['suites'][$suite_name])) {
        return;
    }
    $JUNIT['suites'][$suite_name] = array(
        'name' => $suite_name,
        'test_total' => 0,
        'test_pass' => 0,
        'test_fail' => 0,
        'test_error' => 0,
        'test_skip' => 0,
        'test_warn' => 0,
        'files' => array(),
        'execution_time' => 0,
    );
}
function junit_finish_timer($file_name)
{
    global $JUNIT;
    if (!junit_enabled()) return;
    if (!isset($JUNIT['files'][$file_name]['start'])) {
        error("Timer for $file_name was not started!");
    }
    if (!isset($JUNIT['files'][$file_name]['total'])) {
        $JUNIT['files'][$file_name]['total'] = 0;
    }
    $start = $JUNIT['files'][$file_name]['start'];
    $JUNIT['files'][$file_name]['total'] += microtime(true) - $start;
    unset($JUNIT['files'][$file_name]['start']);
}
function junit_merge_results($junit)
{
    global $JUNIT;
    $JUNIT['test_total'] += $junit['test_total'];
    $JUNIT['test_pass']  += $junit['test_pass'];
    $JUNIT['test_fail']  += $junit['test_fail'];
    $JUNIT['test_error'] += $junit['test_error'];
    $JUNIT['test_skip']  += $junit['test_skip'];
    $JUNIT['test_warn']  += $junit['test_warn'];
    $JUNIT['execution_time'] += $junit['execution_time'];
    $JUNIT['files'] += $junit['files'];
    foreach ($junit['suites'] as $name => $suite) {
        if (!isset($JUNIT['suites'][$name])) {
            $JUNIT['suites'][$name] = $suite;
            continue;
        }
        $SUITE =& $JUNIT['suites'][$name];
        $SUITE['test_total'] += $suite['test_total'];
        $SUITE['test_pass']  += $suite['test_pass'];
        $SUITE['test_fail']  += $suite['test_fail'];
        $SUITE['test_error'] += $suite['test_error'];
        $SUITE['test_skip']  += $suite['test_skip'];
        $SUITE['test_warn']  += $suite['test_warn'];
        $SUITE['execution_time'] += $suite['execution_time'];
        $SUITE['files'] += $suite['files'];
    }
}
class RuntestsValgrind
{
    protected $version = '';
    protected $header = '';
    protected $version_3_3_0 = false;
    protected $version_3_8_0 = false;
    protected $tool = null;
    public function getVersion()
    {
        return $this->version;
    }
    public function getHeader()
    {
        return $this->header;
    }
    public function __construct(array $environment, string $tool = 'memcheck')
    {
        $this->tool = $tool;
        $header = system_with_timeout("valgrind --tool={$this->tool} --version", $environment);
        if (!$header) {
            error("Valgrind returned no version info for {$this->tool}, cannot proceed.\n".
                  "Please check if Valgrind is installed and the tool is named correctly.");
        }
        $count = 0;
        $version = preg_replace("/valgrind-(\d+)\.(\d+)\.(\d+)([.\w_-]+)?(\s+)/", '$1.$2.$3', $header, 1, $count);
        if ($count != 1) {
            error("Valgrind returned invalid version info (\"{$header}\") for {$this->tool}, cannot proceed.");
        }
        $this->version = $version;
        $this->header = sprintf(
            "%s (%s)", trim($header), $this->tool);
        $this->version_3_3_0 = version_compare($version, '3.3.0', '>=');
        $this->version_3_8_0 = version_compare($version, '3.8.0', '>=');
    }
    public function wrapCommand($cmd, $memcheck_filename, $check_all)
    {
        $vcmd = "valgrind -q --tool={$this->tool} --trace-children=yes";
        if ($check_all) {
            $vcmd .= ' --smc-check=all';
        }
        /* --vex-iropt-register-updates=allregs-at-mem-access is necessary for phpdbg watchpoint tests */
        if ($this->version_3_8_0) {
            /* valgrind 3.3.0+ doesn't have --log-file-exactly option */
            return "$vcmd --vex-iropt-register-updates=allregs-at-mem-access --log-file=$memcheck_filename $cmd";
        } elseif ($this->version_3_3_0) {
            return "$vcmd --vex-iropt-precise-memory-exns=yes --log-file=$memcheck_filename $cmd";
        } else {
            return "$vcmd --vex-iropt-precise-memory-exns=yes --log-file-exactly=$memcheck_filename $cmd";
        }
    }
}
main();