// autogenerated by syzkaller (http://github.com/google/syzkaller)

#ifndef __NR_mmap
#define __NR_mmap 9
#endif
#ifndef __NR_syz_open_dev
#define __NR_syz_open_dev 1000002
#endif
#ifndef __NR_madvise
#define __NR_madvise 28
#endif

#define _GNU_SOURCE 

#include <stdint.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>

static int flag_debug;

static void debug(const char* msg, ...)
{
	if (!flag_debug)
		return;
	va_list args;
	va_start(args, msg);
	vfprintf(stdout, msg, args);
	va_end(args);
	fflush(stdout);
}

static uintptr_t syz_open_dev(uintptr_t a0, uintptr_t a1, uintptr_t a2)
{
	if (a0 == 0xc || a0 == 0xb) {
		char buf[128];
		sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2);
		return open(buf, O_RDWR, 0);
	} else {
		char buf[1024];
		char* hash;
strncpy(buf, (char*)a0, sizeof(buf));
		buf[sizeof(buf) - 1] = 0;
		while ((hash = strchr(buf, '#'))) {
			*hash = '0' + (char)(a1 % 10);
			a1 /= 10;
		}
		return open(buf, a2, 0);
	}
}

static void test();

void loop()
{
	while (1) {
		test();
	}
}

long r[9];
void *thr(void *arg)
{
	switch ((long)arg) {
	case 5:
		r[7] = syscall(__NR_madvise, 0x20235000ul, 0x3000ul, 0x8ul);
		break;
	case 6:
		r[8] = syscall(__NR_madvise, 0x20086000ul, 0x800000ul, 0x4ul);
		break;
	}
	return 0;
}

void test()
{
	long i = 5;
	long j = 6;
	pthread_t th[14];

	debug("test\n");
	memset(r, -1, sizeof(r));
	srand(getpid());
	r[0] = syscall(__NR_mmap, 0x20000000ul, 0x6d2000ul, 0x3ul, 0x32ul, 0xfffffffffffffffful, 0x0ul);
	memcpy((void*)0x203c4fec, "\x2f\x64\x65\x76\x2f\x6d\x65\x6d", 8);
	r[2] = syz_open_dev(0x203c4fecul, 0x0ul, 0x0ul);
	printf("syz_open_dev = %ld\n", r[2]);
	memcpy((void*)0x2033c000, "\x2f\x64\x65\x76\x2f\x6d\x65\x6d", 8);
	r[5] = syz_open_dev(0x2033c000ul, 0x0ul, 0x0ul);
	printf("syz_open_dev = %ld\n", r[5]);
	pthread_create(&th[0], 0, thr, (void*)i);
	pthread_create(&th[1], 0, thr, (void*)j);
	usleep(100000);
}

int main()
{
	loop();
	return 0;
}
