Skip to content

Instantly share code, notes, and snippets.

@kostikbel
Created April 25, 2018 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostikbel/d13176d29d7ccf6972d18e7a2659a78e to your computer and use it in GitHub Desktop.
Save kostikbel/d13176d29d7ccf6972d18e7a2659a78e to your computer and use it in GitHub Desktop.
/* $Id: segnonp.c,v 1.4 2014/12/16 18:22:19 kostik Exp kostik $ */
#include <sys/param.h>
#include <sys/types.h>
#include <machine/segments.h>
#include <machine/sysarch.h>
#include <err.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>
static int
s2ds(int sel)
{
return (LSEL(sel, SEL_UPL));
}
static int
alloc_sel(char *base, size_t len, int type, int p)
{
int sel;
union descriptor descs[1], descsk[1];
uintptr_t pb;
memset(descs, 0, sizeof(descs));
if (len > PAGE_SIZE) {
len = roundup(len, PAGE_SIZE);
len /= PAGE_SIZE;
descs[0].sd.sd_lolimit = len & 0xffff;
descs[0].sd.sd_hilimit = (len >> 16) & 0xf;
descs[0].sd.sd_gran = 1;
} else {
descs[0].sd.sd_lolimit = len;
descs[0].sd.sd_hilimit = 0;
descs[0].sd.sd_gran = 0;
}
pb = (uintptr_t)base;
descs[0].sd.sd_lobase = pb & 0xffffff;
descs[0].sd.sd_hibase = (pb >> 24) & 0xff;
descs[0].sd.sd_type = type;
descs[0].sd.sd_dpl = SEL_UPL;
descs[0].sd.sd_p = p;
descs[0].sd.sd_def32 = 1;
if ((sel = i386_set_ldt(LDT_AUTO_ALLOC, descs, 1)) == -1)
fprintf(stderr, "i386_set_ldt: %s\n", strerror(errno));
else if (i386_get_ldt(sel, descsk, 1) == -1) {
fprintf(stderr, "i386_get_ldt: %s\n", strerror(errno));
sel = -1;
} else if (memcmp(descs, descsk, sizeof(descs)) != 0) {
fprintf(stderr, "descs != descsk\n");
sel = -1;
} else
fprintf(stderr, "selector %d\n", sel);
return (sel);
}
static int sel;
static void
sighandler(int signo __unused, siginfo_t *si __unused, void *u)
{
ucontext_t *up;
up = u;
up->uc_mcontext.mc_ss = s2ds(sel);
}
static void load_gs(int seg) __used;
static void
load_gs(int seg)
{
__asm __volatile("movw\t%0,%%gs"
: : "r" ((short)s2ds(seg)) : "memory");
}
int
main(void)
{
struct sigaction sa;
int error;
sel = alloc_sel(0, 0xffffffff, SDT_MEMERA, 0);
if (sel == -1)
exit(1);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = sighandler;
sa.sa_flags = SA_SIGINFO;
error = sigaction(SIGUSR1, &sa, NULL);
if (error != 0)
err(1, "sigaction");
#if 0
load_gs(sel);
#else
raise(SIGUSR1);
#endif
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment