summaryrefslogtreecommitdiffstats
path: root/resources/libreboot/install/depthcharge/cros-flash-replace
blob: 4ad3fabd10a2c3959a03b87aa8849a89cb122dab (plain)
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
#!/bin/bash

#  replace the requested parts in the flash image with separate parts images
#
#	Copyright (C) 2015 Paul Kocialkowski <contact@paulk.fr>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

[ "x${DEBUG+set}" = 'xset' ] && set -v

regex="\([0-9a-fA-F]*\):\([0-9a-fA-F]*\)[[:space:]]*\(.*\)"
block=256
layout="layout.txt"
flash=$1

shift 1

if [ ! -f "$flash" ]
then
	echo "Usage: $0 [flash image] [image] ..."
	exit 1
fi

if [ ! -f "$layout" ]
then
	echo "Missing layout file: $layout"
	exit 1
fi

flashsize=$( stat $flash -c "%s" )

for image in $@; do
	range=$( grep "$image" "$layout" )
	name=$( echo "$range" | sed "s/$regex/\3/g" )
	file="$name.img"

	if [ -z "$range" ] || [ ! -f "$file" ]
	then
		echo "Invalid image name: $name"
		continue
	fi

	start=$( echo "$range" | sed "s/$regex/\1/g" )
	start=$( printf "%d\n" "0x$start" )
	stop=$( echo "$range" | sed "s/$regex/\2/g" )
	stop=$( printf "%d\n" "0x$stop" )

	size=$(( $stop - $start + 1 ))
	filesize=$( stat $file -c "%s" )

	if [ $size -ne $filesize ]
	then
		echo "Invalid file size: expected $size, read $filesize"
		continue
	fi

	if [ $size -gt $flashsize ]
	then
		echo "Image size too big for flash"
		continue
	fi

	printf "Replacing $image in $flash\n\n"

	if [ $start -gt 0 ]
	then
		dd if=$flash of=before.img bs=$block count=$(( $start / $block ))
	else
		touch before.img
	fi

	if [ $(( $stop + 1 )) -lt $flashsize ]
	then
		dd if=$flash of=after.img skip=$(( ($stop + 1) / $block )) bs=$block count=$(( ($flashsize - $stop - 1) / $block ))
	else
		touch after.img
	fi

	cat before.img $file after.img > $flash

	rm before.img after.img

	printf "\n"
done