+#define BITSTREAM_MAX_SIZE 262144 /* bitstream size limit for safety */
+#define BITSTREAM_HEADER_SIZE 4 /* transfer header size in bytes */
+
+/* Load a bitstream file into memory. Returns a newly allocated array
+ * consisting of a 32-bit length field followed by the bitstream data.
+ */
+static unsigned char *load_bitstream_file(const char *filename, int *length_p)
+{
+ GStatBuf statbuf;
+ FILE *file;
+ unsigned char *stream;
+ size_t length, count;
+
+ /* Retrieve and validate the file size. */
+ if (g_stat(filename, &statbuf) < 0) {
+ sr_err("Failed to access bitstream file: %s.",
+ g_strerror(errno));
+ return NULL;
+ }
+ if (!S_ISREG(statbuf.st_mode)) {
+ sr_err("Bitstream is not a regular file.");
+ return NULL;
+ }
+ if (statbuf.st_size <= 0 || statbuf.st_size > BITSTREAM_MAX_SIZE) {
+ sr_err("Refusing to load bitstream of unreasonable size "
+ "(%" PRIu64 " bytes).", (uint64_t)statbuf.st_size);
+ return NULL;
+ }
+
+ /* The message length includes the 4-byte header. */
+ length = BITSTREAM_HEADER_SIZE + statbuf.st_size;
+ stream = g_try_malloc(length);
+ if (!stream) {
+ sr_err("Failed to allocate bitstream buffer.");
+ return NULL;
+ }
+
+ file = g_fopen(filename, "rb");
+ if (!file) {
+ sr_err("Failed to open bitstream file: %s.", g_strerror(errno));
+ g_free(stream);
+ return NULL;
+ }
+
+ /* Write the message length header. */
+ *(uint32_t *)stream = GUINT32_TO_BE(length);
+
+ count = fread(stream + BITSTREAM_HEADER_SIZE,
+ length - BITSTREAM_HEADER_SIZE, 1, file);
+ if (count != 1) {
+ sr_err("Failed to read bitstream file: %s.", g_strerror(errno));
+ fclose(file);
+ g_free(stream);
+ return NULL;
+ }
+ fclose(file);
+
+ *length_p = length;
+ return stream;
+}
+
+/* Load a Raw Binary File (.rbf) from the firmware directory and transfer
+ * it to the device.
+ */