Skip to content

Instantly share code, notes, and snippets.

@kostikbel
Created September 17, 2017 21:09
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/6353128c10c8344ea4292bd44716b3b7 to your computer and use it in GitHub Desktop.
Save kostikbel/6353128c10c8344ea4292bd44716b3b7 to your computer and use it in GitHub Desktop.
/* $Id: mvillard_nest.c,v 1.2 2017/09/15 14:33:30 kostik Exp kostik $ */
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/ucontext.h>
#include <machine/atomic.h>
#include <machine/segments.h>
#include <machine/sysarch.h>
#include <err.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
static volatile u_int b, s;
static void *
dealloc_ldt(void *arg __unused)
{
u_int sl;
for (;;) {
while (atomic_load_acq_int(&b) == 0)
;
sl = s;
s = 0;
if (sl != 0)
i386_set_ldt(sl, NULL, 1);
atomic_store_rel_int(&b, 0);
}
return (NULL);
}
static void
func(void)
{
union descriptor desc;
u_int sel, sl;
bzero(&desc, sizeof(desc));
desc.sd.sd_type = SDT_MEMRWA;
desc.sd.sd_dpl = SEL_UPL;
desc.sd.sd_p = 1;
desc.sd.sd_def32 = 1;
desc.sd.sd_gran = 1;
desc.sd.sd_lolimit = 0xffff;
desc.sd.sd_hilimit = 0xf;
sl = i386_set_ldt(LDT_AUTO_ALLOC, &desc, 1);
if ((int)sl == -1)
err(1, "i386_set_ldt");
sel = LSEL(sl, SEL_UPL);
s = sl;
__asm volatile("movw\t%w0,%%es" : : "r" (sel));
atomic_store_rel_int(&b, 1);
while (atomic_load_acq_int(&b) != 0)
;
getpid();
}
static void
sigsegv_handler(int signo __unused, siginfo_t *si __unused, void *rctx)
{
ucontext_t *uc;
uc = rctx;
uc->uc_mcontext.mc_es = uc->uc_mcontext.mc_ds;
}
int
main(void)
{
pthread_t thr;
struct sigaction sa;
int error;
bzero(&sa, sizeof(sa));
sa.sa_sigaction = sigsegv_handler;
sa.sa_flags = SA_SIGINFO;
error = sigaction(SIGSEGV, &sa, NULL);
if (error != 0)
err(1, "sigaction SIGSEGV");
error = sigaction(SIGBUS, &sa, NULL);
if (error != 0)
err(1, "sigaction SIGBUS");
error = pthread_create(&thr, NULL, dealloc_ldt, NULL);
if (error != 0)
errc(1, error, "pthread_create");
for (;;)
func();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment