scripts/bin_to_c.py: add support for text files

bin_to_c.py may be useful to generate a C file from a text file, not
only from a binary file. This patch adds the --text argument for that
purpose. With --text, the script will:
 - define a "const char []" variable,
 - error out if a null byte is encountered,
 - terminate the input string with a null byte.

Signed-off-by: Jerome Forissier <jerome@forissier.org>
Reviewed-by: Joakim Bech <joakim.bech@linaro.org>
Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org>
diff --git a/scripts/bin_to_c.py b/scripts/bin_to_c.py
index c9d2f01..d35cc68 100755
--- a/scripts/bin_to_c.py
+++ b/scripts/bin_to_c.py
@@ -8,6 +8,7 @@
 import array
 import os
 import re
+import sys
 
 
 def get_args():
@@ -26,6 +27,9 @@
     parser.add_argument('--out', required=True,
                         help='Path for the generated C file')
 
+    parser.add_argument('--text', required=False, action='store_true',
+                        help='Treat input as a text file')
+
     return parser.parse_args()
 
 
@@ -35,6 +39,8 @@
 
     with open(args.bin, 'rb') as indata:
         bytes = indata.read()
+        if args.text:
+            bytes += b'\0'
         size = len(bytes)
 
     f = open(args.out, 'w')
@@ -42,12 +48,18 @@
             os.path.basename(__file__) + ' */\n\n')
     f.write('#include <compiler.h>\n')
     f.write('#include <stdint.h>\n')
-    f.write('__extension__ const uint8_t ' + args.vname + '[] ' +
-            ' __aligned(__alignof__(uint64_t)) = {\n')
+    if args.text:
+        f.write('__extension__ const char ' + args.vname + '[] = {\n')
+    else:
+        f.write('__extension__ const uint8_t ' + args.vname + '[] ' +
+                ' __aligned(__alignof__(uint64_t)) = {\n')
     i = 0
     while i < size:
         if i % 8 == 0:
             f.write('\t\t')
+        if args.text and i != size - 1 and bytes[i] == b'\0':
+            print('Error: null byte encountered in text file')
+            sys.exit(1)
         f.write('0x' + '{:02x}'.format(bytes[i]) + ',')
         i = i + 1
         if i % 8 == 0 or i == size: