- else
- pos = lseek(fd, 0L, SEEK_SET);
- }
- else
- {
- // size & pos not given, so assume offset of 0 and all of the binary
- size = lseek(fd, 0L, SEEK_END);
- pos = lseek(fd, 0L, SEEK_SET);
+
+ // Adjust size if the user didn't specify it via the parameter
+ if (requested_size == -1)
+ {
+ requested_size = size - pos;
+ }
+
+ // Are we going to read past the end of the file?
+ if (pos + requested_size > size)
+ {
+ close(fd);
+ return error("invalid combination of incbin position and size");
+ }
+ size = requested_size;
+
+ // All checks passed, let's seek to where the user requested, otherwise at file start
+ lseek(fd, pos, SEEK_SET);