+/* Check if the build_id for the current runtime is present in a
+ * buffer. */
+int
+check_runtime_build_id(void *buf, size_t size)
+{
+ size_t idlen;
+ char *pos;
+
+ idlen = strlen(build_id) - 1;
+ while ((pos = memchr(buf, build_id[0], size)) != NULL) {
+ size -= (pos + 1) - (char *)buf;
+ buf = (pos + 1);
+ if (idlen <= size && memcmp(buf, build_id + 1, idlen) == 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Slurp the executable portion of the runtime into a malloced buffer
+ * and return it. Places the size in bytes of the runtime into
+ * 'size_out'. Returns NULL if the runtime cannot be loaded from
+ * 'runtime_path'. */
+void *
+load_runtime(char *runtime_path, size_t *size_out)
+{
+ void *buf = NULL;
+ FILE *input = NULL;
+ size_t size, count;
+ os_vm_offset_t core_offset;
+
+ core_offset = search_for_embedded_core (runtime_path);
+ if ((input = fopen(runtime_path, "rb")) == NULL) {
+ fprintf(stderr, "Unable to open runtime: %s\n", runtime_path);
+ goto lose;
+ }
+
+ fseek(input, 0, SEEK_END);
+ size = (size_t) ftell(input);
+ fseek(input, 0, SEEK_SET);
+
+ if (core_offset != -1 && size > core_offset)
+ size = core_offset;
+
+ buf = successful_malloc(size);
+ if ((count = fread(buf, 1, size, input)) != size) {
+ fprintf(stderr, "Premature EOF while reading runtime.\n");
+ goto lose;
+ }
+
+ if (!check_runtime_build_id(buf, size)) {
+ fprintf(stderr, "Failed to locate current build_id in runtime: %s\n",
+ runtime_path);
+ goto lose;
+ }
+
+ fclose(input);
+ *size_out = size;
+ return buf;
+
+lose:
+ if (input != NULL)
+ fclose(input);
+ if (buf != NULL)
+ free(buf);
+ return NULL;
+}
+