flash_image_builder.sh 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env bash
  2. #
  3. # Copyright (c) 2020 Project CHIP Authors
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. #
  18. # Description:
  19. # This script can be used to build an image file containing multiple
  20. # source binaries at specific offset in the image
  21. #
  22. set -e
  23. usage() {
  24. exitcode=0
  25. if [[ -n "$1" ]]; then
  26. exitcode=1
  27. echo "Error: $*"
  28. fi
  29. echo "Usage: $0 <image-size> <output-file> <offset1=input-file1> [<offset2=input-file2> ..]"
  30. exit "$exitcode"
  31. }
  32. [[ $# -ge 3 ]] || usage "Incorrect number of arguments"
  33. image_size="$1"
  34. image_size=$((image_size))
  35. [[ $? -eq 0 ]] || usage "Image size ($1) must be a number"
  36. [[ $image_size -gt 0 ]] || usage "Image size ($1) must be a valid number and greater than 0"
  37. # Create an empty <image_size> file containing all 0xff
  38. dd if=/dev/zero bs="$image_size" count=1 | tr '\000' '\377' >"$2"
  39. written=0
  40. # Argument 3 onwards have input files and corresponding offsets
  41. for item in "${@:3}"; do
  42. IFS='=' read -r start file <<<"$item"
  43. offset=$((start))
  44. [[ $? -eq 0 ]] || usage "Offset ($start) must be a number"
  45. [[ -r $file ]] || usage "Cannot read file $file"
  46. [[ $written -le $offset ]] || usage "Writing $file at $offset will overwrite previous segment"
  47. read -r _perms _ _user _group filesize _rest < <(ls -l "$file")
  48. ((written += filesize))
  49. [[ $written -lt $image_size ]] || usage "Writing $file at $offset will overflow image"
  50. dd if="$file" of="$2" conv=notrunc bs="$offset" seek=1
  51. done