tools/testing/selftests/sgx/load.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/sgx/load.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/sgx/load.c
Extension
.c
Size
7897 bytes
Lines
371
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

if (sections[i].sh_type == SHT_SYMTAB) {
			symtab = (Elf64_Sym *)((char *)encl->bin + sections[i].sh_offset);
			num_sym = sections[i].sh_size / sections[i].sh_entsize;
			break;
		}
	}

	for (i = 0; i < ehdr->e_shnum; i++) {
		if (sections[i].sh_type == SHT_STRTAB) {
			sym_names = (char *)encl->bin + sections[i].sh_offset;
			break;
		}
	}

	if (!symtab || !sym_names)
		return 0;

	for (i = 0; i < num_sym; i++) {
		Elf64_Sym *sym = &symtab[i];

		if (!strcmp(symbol, sym_names + sym->st_name))
			return (uint64_t)sym->st_value;
	}

	return 0;
}

bool encl_load(const char *path, struct encl *encl, unsigned long heap_size)
{
	const char device_path[] = "/dev/sgx_enclave";
	struct encl_segment *seg;
	Elf64_Phdr *phdr_tbl;
	off_t src_offset;
	Elf64_Ehdr *ehdr;
	struct stat sb;
	void *ptr;
	int i, j;
	int ret;
	int fd = -1;

	memset(encl, 0, sizeof(*encl));

	fd = open(device_path, O_RDWR);
	if (fd < 0) {
		perror("Unable to open /dev/sgx_enclave");
		goto err;
	}

	ret = stat(device_path, &sb);
	if (ret) {
		perror("device file stat()");
		goto err;
	}

	ptr = mmap(NULL, PAGE_SIZE, PROT_READ, MAP_SHARED, fd, 0);
	if (ptr == (void *)-1) {
		perror("mmap for read");
		goto err;
	}
	munmap(ptr, PAGE_SIZE);

#define ERR_MSG \
"mmap() succeeded for PROT_READ, but failed for PROT_EXEC.\n" \
" Check that /dev does not have noexec set:\n" \
" \tmount | grep \"/dev .*noexec\"\n" \
" If so, remount it executable: mount -o remount,exec /dev\n\n"

	ptr = mmap(NULL, PAGE_SIZE, PROT_EXEC, MAP_SHARED, fd, 0);
	if (ptr == (void *)-1) {
		fprintf(stderr, ERR_MSG);
		goto err;
	}
	munmap(ptr, PAGE_SIZE);

	encl->fd = fd;

	if (!encl_map_bin(path, encl))
		goto err;

	ehdr = encl->bin;
	phdr_tbl = encl->bin + ehdr->e_phoff;

	encl->nr_segments = 1; /* one for the heap */

	for (i = 0; i < ehdr->e_phnum; i++) {
		Elf64_Phdr *phdr = &phdr_tbl[i];

		if (phdr->p_type == PT_LOAD)
			encl->nr_segments++;
	}

Annotation

Implementation Notes