Merge pull request #60 from d3zd3z/pr/py-header

Make header padding optional
diff --git a/doc/imgtool.md b/doc/imgtool.md
index f881d57..309364e 100644
--- a/doc/imgtool.md
+++ b/doc/imgtool.md
@@ -66,6 +66,7 @@
       --align ALIGN
       -v VERSION, --version VERSION
       -H HEADER_SIZE, --header-size HEADER_SIZE
+      --included-header     Image has gap for header
       --pad PAD             Pad image to this many bytes, adding trailer magic
       --rsa-pkcs1-15        Use old PKCS#1 v1.5 signature algorithm
 
@@ -75,8 +76,10 @@
 
 The header size depends on the operating system and the particular
 flash device.  For Zephyr, it will be configured as part of the build,
-and will be a small power of two.  The generated image should start
-with zero bytes of this length (and the script will check this).
+and will be a small power of two.  By default, the header will be
+prepended to the image.  If `--included-header` is given, the image
+must start with header-size bytes of zeros, and the header will be
+overwritten over these bytes.
 
 The optional --pad argument will place a trailer on the image that
 indicates that the image should be considered an upgrade.  Writing
diff --git a/scripts/imgtool.py b/scripts/imgtool.py
index e0a8106..6bc3cd0 100755
--- a/scripts/imgtool.py
+++ b/scripts/imgtool.py
@@ -34,6 +34,7 @@
         keys.sign_rsa_pss = False
     img = image.Image.load(args.infile, version=args.version,
             header_size=args.header_size,
+            included_header=args.included_header,
             pad=args.pad)
     key = keys.load(args.key) if args.key else None
     img.sign(key)
@@ -79,6 +80,8 @@
     sign.add_argument("--align", type=alignment_value, required=True)
     sign.add_argument("-v", "--version", type=version.decode_version, required=True)
     sign.add_argument("-H", "--header-size", type=intparse, required=True)
+    sign.add_argument("--included-header", default=False, action='store_true',
+            help='Image has gap for header')
     sign.add_argument("--pad", type=intparse,
             help='Pad image to this many bytes, adding trailer magic')
     sign.add_argument("--rsa-pkcs1-15", help='Use old PKCS#1 v1.5 signature algorithm',
diff --git a/scripts/imgtool/image.py b/scripts/imgtool/image.py
index f270268..49b8249 100644
--- a/scripts/imgtool/image.py
+++ b/scripts/imgtool/image.py
@@ -55,12 +55,17 @@
 
 class Image():
     @classmethod
-    def load(cls, path, **kwargs):
+    def load(cls, path, included_header=False, **kwargs):
         """Load an image from a given file"""
         with open(path, 'rb') as f:
             payload = f.read()
         obj = cls(**kwargs)
         obj.payload = payload
+
+        # Add the image header if needed.
+        if not included_header and obj.header_size > 0:
+            obj.payload = (b'\000' * obj.header_size) + obj.payload
+
         obj.check()
         return obj