tools/testing/selftests/x86/fsgsbase_restore.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/x86/fsgsbase_restore.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/x86/fsgsbase_restore.c
Extension
.c
Size
6357 bytes
Lines
245
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 (ret != 0) {
			printf("[NOTE]\tcould not create a segment -- can't test anything\n");
			exit(0);
		}
		printf("\tusing GDT slot %d\n", desc.entry_number);

		unsigned short sel = (unsigned short)((desc.entry_number << 3) | 0x3);
		asm volatile ("mov %0, %" SEG :: "rm" (sel));
	}
}

static void tracee_zap_segment(void)
{
	/*
	 * The tracer will redirect execution here.  This is meant to
	 * work like gdb's 'p func()' feature.  The tricky bit is that
	 * we modify a segment register in order to make sure that ptrace
	 * can correctly restore segment registers.
	 */
	printf("\tTracee: in tracee_zap_segment()\n");

	/*
	 * Write a nonzero selector with base zero to the segment register.
	 * Using a null selector would defeat the test on AMD pre-Zen2
	 * CPUs, as such CPUs don't clear the base when loading a null
	 * selector.
	 */
	unsigned short sel;
	asm volatile ("mov %%ss, %0\n\t"
		      "mov %0, %" SEG
		      : "=rm" (sel));

	pid_t pid = getpid(), tid = syscall(SYS_gettid);

	printf("\tTracee is going back to sleep\n");
	syscall(SYS_tgkill, pid, tid, SIGSTOP);

	/* Should not get here. */
	while (true) {
		printf("[FAIL]\tTracee hit unreachable code\n");
		pause();
	}
}

int main()
{
	printf("\tSetting up a segment\n");
	init_seg();

	unsigned int val = dereference_seg_base();
	if (val != EXPECTED_VALUE) {
		printf("[FAIL]\tseg[0] == %x; should be %x\n", val, EXPECTED_VALUE);
		return 1;
	}
	printf("[OK]\tThe segment points to the right place.\n");

	pid_t chld = fork();
	if (chld < 0)
		err(1, "fork");

	if (chld == 0) {
		prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0, 0);

		if (ptrace(PTRACE_TRACEME, 0, 0, 0) != 0)
			err(1, "PTRACE_TRACEME");

		pid_t pid = getpid(), tid = syscall(SYS_gettid);

		printf("\tTracee will take a nap until signaled\n");
		syscall(SYS_tgkill, pid, tid, SIGSTOP);

		printf("\tTracee was resumed.  Will re-check segment.\n");

		val = dereference_seg_base();
		if (val != EXPECTED_VALUE) {
			printf("[FAIL]\tseg[0] == %x; should be %x\n", val, EXPECTED_VALUE);
			exit(1);
		}

		printf("[OK]\tThe segment points to the right place.\n");
		exit(0);
	}

	int status;

	/* Wait for SIGSTOP. */
	if (waitpid(chld, &status, 0) != chld || !WIFSTOPPED(status))
		err(1, "waitpid");

	struct user_regs_struct regs;

Annotation

Implementation Notes