forked from dacp/firmware-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplaceDataInFirmware.php
executable file
·66 lines (60 loc) · 2.63 KB
/
replaceDataInFirmware.php
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
<?php
function BinaryRepresentation(string $char):string
//returns the binary representation of a one byte string
{
$binary = decbin(ord($char)); //convert byte to int and get binary representation
$binary = str_pad($binary, 8, 0, STR_PAD_LEFT); //pad with 0s up to 8 digits
return $binary;
}
function ReverseBits(string $byte):string
//gets a one byte string and returns a one byte string with the bits reversed
{
$binary = BinaryRepresentation($byte); //get a string with the bits
$binary = strrev($binary); //reverse the string
$reversednumber = bindec($binary); //assemble the bits back into a number
$reversed = pack("C",$reversednumber); //convert the number to a one byte string
return $reversed;
}
function ServeContent(string $filename, string $content):void
{
header('Content-Type: application/octet-stream');
header('Content-Length: ' . strlen($content));
header("Content-Disposition: attachment; filename=\"$filename\"");
echo $content;
}
function ServeModifiedFirmware(string $firmwarePath, string $wavetablePath, string $hexAddress):void
{
//load the firmware into memory as a string
$firmwarefhandler = fopen($firmwarePath, "rb");
$firmwareSize = filesize($firmwarePath);
$firmwareContents = fread($firmwarefhandler,$firmwareSize);
//same for replacement
$wavetablefhandler = fopen($wavetablePath, "rb");
$wavetableSize = filesize($wavetablePath);
$wavetableContents = fread($wavetablefhandler,$wavetableSize);
$wavetableLength = strlen($wavetableContents);
//loop through all the bytes in the firmware and replace the wavetable portion
$replaceStart = hexdec($hexAddress);
$replaceEnd = $replaceStart + $wavetableLength;
$outputFirmware = "";
for ($i = 0; $i < strlen($firmwareContents); $i++) {
$char = $firmwareContents[$i];
if($i < $replaceStart || $i > $replaceEnd)
//we're copying a byte outside the replacment boundaries
{
$outputFirmware .= $char;
}
else
{
//at the correct point, inject the wavetable while inverting the bits
$wavetableCharPos = $i-$replaceStart;
$outputFirmware .= ReverseBits($wavetableContents[$wavetableCharPos]);
}
}
ServeContent("custom_firmware.jic",$outputFirmware);
}
//$uploadsDir = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir() . DIRECTORY_SEPARATOR;
$wavetable = $_FILES["rawAudio"]["tmp_name"];
$firmware = $_FILES["firmwareFile"]["tmp_name"];
ServeModifiedFirmware($firmware, $wavetable, $_POST["offset"]);
?>