Computer

color-valgrind with PHP

This VERY SIMPLE script has the intention to get the output from Valgrind with color using PHP.

Usualy I put this script on /usr/bin named as color-valgrind with access level 755.
#!/usr/bin/php
<?php
// v.1   - 2022-05-10
// v.1.1 - 2022-05-11
function escape($str)
{
	if(strpos($str, ' ' ) !== false
	|| strpos($str, '"' ) !== false
	|| strpos($str, "'" ) !== false
	|| strpos($str, '\t') !== false
	|| strpos($str, '\n') !== false
	|| strpos($str, '\r') !== false
	) {
		$str = '"'.addslashes($str).'"';
	}

	return $str;
}

$argv[0] = 'valgrind';

$cmd = implode(' ', array_map('escape', $argv)).' 2>&1';

$descripts = array(
	1 => array("pipe", "w")
);

$p = proc_open($cmd, $descripts, $pipes);

if(!is_resource($p)) {
	echo "Fail!\n";
	exit(1);
}

$count = 0;
$data  = '';
while($count < 1000) {
	$read   = array($pipes[1]);
	$write  = null;
	$except = null;
	if(($n = stream_select($read, $write, $except, 0, 1000)) !== false && $n > 0) {
		foreach($read as $pipe) {
			if(!feof($pipe) && $block = fread($pipe, 128)) {
				$count = 0;
				$data .= $block;
				if(strpos($data, "\n") !== false) {
					$lines = explode("\n", $data);
					$data  = array_pop($lines);
					foreach($lines as $line) {
						if(preg_match('/^(==[0-9]+==)(.+)?$/', $line, $matches)) {
							echo chr(27).'[0;104m'.$matches[1].chr(27).'[0m';
							echo chr(27)."[1;34m" .$matches[2].chr(27)."[0m\n";
						} else {
							echo $line."\n";
						}
					}
				}
			}
		}
		if(feof($pipes[1])) {
			$count++;
		}
	}
}
fclose($pipes[1]);
proc_close($p);
P.S.: On your program, flush your stdout on every output to pipe receive the data.

USE IT AT YOUR OWN RISK!
Kudos: 0 [Give a kudo]

12r6j5xasef5Z6Sm4A6oBpMLn2ESPPX6ym
Ads: