void BytecodeGeneratorification::run()
{
    // We calculate the liveness at each merge point. This gives us the information which registers should be saved and resumed conservatively.

    {
        GeneratorLivenessAnalysis pass(*this);
        pass.run();
    }

    UnlinkedCodeBlock* codeBlock = m_graph.codeBlock();
    BytecodeRewriter rewriter(m_graph);

    // Setup the global switch for the generator.
    {
        unsigned nextToEnterPoint = enterPoint() + opcodeLength(op_enter);
        unsigned switchTableIndex = m_graph.codeBlock()->numberOfSwitchJumpTables();
        VirtualRegister state = virtualRegisterForArgument(static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State));
        auto& jumpTable = m_graph.codeBlock()->addSwitchJumpTable();
        jumpTable.min = 0;
        jumpTable.branchOffsets.resize(m_yields.size() + 1);
        jumpTable.branchOffsets.fill(0);
        jumpTable.add(0, nextToEnterPoint);
        for (unsigned i = 0; i < m_yields.size(); ++i)
            jumpTable.add(i + 1, m_yields[i].point);

        rewriter.insertFragmentBefore(nextToEnterPoint, [&](BytecodeRewriter::Fragment& fragment) {
            fragment.appendInstruction(op_switch_imm, switchTableIndex, nextToEnterPoint, state.offset());
        });
    }

    for (const YieldData& data : m_yields) {
        VirtualRegister scope = virtualRegisterForArgument(static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame));

        // Emit save sequence.
        rewriter.insertFragmentBefore(data.point, [&](BytecodeRewriter::Fragment& fragment) {
            data.liveness.forEachSetBit([&](size_t index) {
                VirtualRegister operand = virtualRegisterForLocal(index);
                Storage storage = storageForGeneratorLocal(index);

                fragment.appendInstruction(
                    op_put_to_scope,
                    scope.offset(), // scope
                    storage.identifierIndex, // identifier
                    operand.offset(), // value
                    GetPutInfo(DoNotThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand(), // info
                    m_generatorFrameSymbolTableIndex, // symbol table constant index
                    storage.scopeOffset.offset() // scope offset
                );
            });

            // Insert op_ret just after save sequence.
            fragment.appendInstruction(op_ret, data.argument);
        });

        // Emit resume sequence.
        rewriter.insertFragmentAfter(data.point, [&](BytecodeRewriter::Fragment& fragment) {
            data.liveness.forEachSetBit([&](size_t index) {
                VirtualRegister operand = virtualRegisterForLocal(index);
                Storage storage = storageForGeneratorLocal(index);

                UnlinkedValueProfile profile = codeBlock->addValueProfile();
                fragment.appendInstruction(
                    op_get_from_scope,
                    operand.offset(), // dst
                    scope.offset(), // scope
                    storage.identifierIndex, // identifier
                    GetPutInfo(DoNotThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand(), // info
                    0, // local scope depth
                    storage.scopeOffset.offset(), // scope offset
                    profile // profile
                );
            });
        });

        // Clip the unnecessary bytecodes.
        rewriter.removeBytecode(data.point);
    }

    rewriter.execute();
}
Example #2
0
int main(int argc, char **argv)
{
	int ret = -1, fd, status;
	char path[PATH_MAX];
	pid_t pid;

	if (!getenv("ZDTM_NEWNS")) {
		if (mount_and_add(cgname, "test") < 0)
			return -1;

		if (unshare(CLONE_NEWCGROUP) < 0) {
			pr_perror("unshare");
			goto out;
		}
	}

	test_init(argc, argv);

	test_daemon();
	test_waitsig();

	sprintf(path, "name=%s", cgname);

	/* first check that the task is in zdtmtst:/ */
	if (!pid_in_cgroup(getpid(), path, "/")) {
		fail("pid not in cgroup /");
		goto out;
	}

	/* now check that the task is in the right place in a ns by setnsing to
	 * someone else's ns and looking there.
	 */
	pid = fork();
	if (pid < 0) {
		pr_perror("fork");
		goto out;
	}

	if (pid == 0) {
		sprintf(path, "/proc/%d/ns/cgroup", 1);
		fd = open(path, O_RDONLY);
		if (fd < 0) {
			pr_perror("open");
			exit(1);
		}

		ret = setns(fd, CLONE_NEWCGROUP);
		close(fd);
		if (ret < 0) {
			pr_perror("setns");
			exit(1);
		}

		sprintf(path, "name=%s", cgname);
		if (!pid_in_cgroup(getppid(), path, "/test")) {
			fail("pid not in cgroup %s", path);
			exit(1);
		}

		exit(0);
	}

	if (pid != waitpid(pid, &status, 0)) {
		pr_err("wrong pid");
		goto out;
	}

	if (!WIFEXITED(status) || WEXITSTATUS(status)) {
		pr_err("got bad exit status %d\n", status);
		goto out;
	}

	ret = 0;
	pass();

out:
	sprintf(path, "%s/%s/test", dirname, cgname);
	rmdir(path);
	sprintf(path, "%s/%s", dirname, cgname);
	umount(path);
	rmdir(path);
	rmdir(dirname);
	return ret;
}
Example #3
0
File: 163.c Project: Ravenbrook/mps
int main(void) {
 run_test(test);
 pass();
 return 0;
}
int main(int argc, char**argv) {
  int err=0;
  err+=test_defaultmatrix("FuMa[f]" , 4, 4, AMBIX_MATRIX_FUMA    , 3, 1024, 6e-8);
  return pass();
}
Example #5
0
int main(int argc, char**argv) {
  check_create_extended("test2-pcm32.caf",  AMBIX_SAMPLEFORMAT_PCM32, 1024, 1e-5);

  pass();
  return 0;
}
Example #6
0
int main(int argc, char ** argv)
{
	int fd;
	size_t fsize=1000;
	mode_t mode;
	uid_t uid;
	gid_t gid;
	uint8_t buf[fsize];
	struct stat fst;
	uint32_t crc;
#ifdef UNLINK_FSTAT04
	char filename[PATH_MAX];
#endif

	test_init(argc, argv);

#ifdef UNLINK_FSTAT04
	snprintf(filename, sizeof(filename), "%s/test\\file'\n\"un%%linkfstat00", dirname);

	mkdir(dirname, 0700);
#endif
	fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0644);
	if (fd < 0) {
		pr_perror("can't open %s", filename);
		exit(1);
	}

#ifdef UNLINK_FSTAT04
	if (chmod(dirname, 0500)) {
		pr_perror("chmod");
		exit(1);
	}
#endif

	if (fstat(fd, &fst) < 0) {
		pr_perror("can't get file info %s before", filename);
		goto failed;
	}

	if (unlink(filename) < 0) {
		pr_perror("can't unlink %s", filename);
		goto failed;
	}
	/* Change file size */
	if (fst.st_size != 0) {
		pr_perror("%s file size eq %d", fst.st_size);
		goto failed;
	}

	crc = ~0;
	datagen(buf, sizeof(buf), &crc);
	if (write(fd, buf, sizeof(buf)) != sizeof(buf)) {
		pr_perror("can't write %s", filename);
		goto failed;
	}
	/* Change file mode */
	if ((fst.st_mode & S_IXOTH) == 0)
		mode = (fst.st_mode | S_IXOTH);
	else
		mode = (fst.st_mode ^ S_IXOTH);

	if (fchmod(fd, mode) < 0) {
		pr_perror("can't chmod %s", filename);
		goto failed;
	}

	if (getuid()) {
		uid = getuid();
		gid = getgid();
	} else {
		/* Change uid, gid */
		if (fchown(fd, (uid = fst.st_uid + 1), (gid = fst.st_gid + 1)) < 0) {
			pr_perror("can't chown %s", filename);
			goto failed;
		}
	}

	if (lseek(fd, 0, SEEK_SET) != 0) {
		pr_perror("can't reposition to 0");
		goto failed;
	}

	test_daemon();
	test_waitsig();

	if (fstat(fd, &fst) < 0) {
		pr_perror("can't get %s file info after", filename);
		goto failed;
	}

	/* Check file size */
	if (fst.st_size != fsize) {
		fail("(via fstat): file size changed to %d", fst.st_size);
		goto failed;
	}
	fst.st_size = lseek(fd, 0, SEEK_END);
	if (fst.st_size != fsize) {
		fail("(via lseek): file size changed to %d", fst.st_size);
		goto failed;
	}
	/* Check mode */
	if (fst.st_mode != mode) {
		fail("mode is changed to %o(%o)", fst.st_mode, mode);
		goto failed;
	}
	/* Check uid, gid */
	if (fst.st_uid != uid || fst.st_gid != gid) {
		fail("u(g)id changed: uid=%d(%d), gid=%d(%d)",
				fst.st_uid, uid, fst.st_gid, gid);
		goto failed;
	}

	if (lseek(fd, 0, SEEK_SET) != 0) {
		pr_perror("can't reposition to 0");
		goto failed;
	}
	if (read(fd, buf, sizeof(buf)) != sizeof(buf)) {
		fail("can't read %s: %m\n", filename);
		goto failed;
	}

	crc = ~0;
	if (datachk(buf, sizeof(buf), &crc)) {
		fail("CRC mismatch\n");
		goto failed;
	}

	close(fd);

	pass();
	return 0;
failed:
	unlink(filename);
	close(fd);
	return 1;
}
Example #7
0
int main(int argc, char **argv)
{
	int cgfd, l, ret = 1, i;
	char aux[1024], paux[1024];
	FILE *cgf;
	struct stat st;

	test_init(argc, argv);

	if (mkdir(dirname, 0700) < 0) {
		err("Can't make dir");
		goto out;
	}

	sprintf(aux, "none,name=%s", cgname);
	if (mount("none", dirname, "cgroup", 0, aux)) {
		err("Can't mount cgroups");
		goto out_rd;
	}

	sprintf(paux, "%s/%s", dirname, subname);
	mkdir(paux, 0600);

	l = sprintf(aux, "%d", getpid());
	sprintf(paux, "%s/%s/tasks", dirname, subname);

	cgfd = open(paux, O_WRONLY);
	if (cgfd < 0) {
		err("Can't open tasks");
		goto out_rs;
	}

	l = write(cgfd, aux, l);
	close(cgfd);

	if (l < 0) {
		err("Can't move self to subcg");
		goto out_rs;
	}

	for (i = 0; i < 2; i++) {
		sprintf(paux, "%s/%s/%s.%d", dirname, subname, empty, i);
		if (mkdir(paux, 0600)) {
			err("mkdir %s", paux);
			return 1;
		}
	}

	test_daemon();
	test_waitsig();

	cgf = fopen("/proc/self/mountinfo", "r");
	if (cgf == NULL) {
		fail("No mountinfo file");
		goto out_rs;
	}

	while (fgets(paux, sizeof(paux), cgf)) {
		char *s;

		s = strstr(paux, cgname);
		if (!s)
			continue;

		sscanf(paux, "%*d %*d %*d:%*d %*s %s", aux);
		test_msg("found cgroup at %s\n", aux);

		for (i = 0; i < 2; i++) {
			sprintf(paux, "%s/%s/%s.%d", aux, subname, empty, i);
			if (stat(paux, &st)) {
				fail("couldn't stat %s\n", paux);
				ret = -1;
				goto out_close;
			}

			if (!S_ISDIR(st.st_mode)) {
				fail("%s is not a directory\n", paux);
				ret = -1;
				goto out_close;
			}
		}

		pass();
		ret = 0;
		goto out_close;
	}

	fail("empty cgroup not found!\n");

out_close:
	fclose(cgf);
out_rs:
	umount(dirname);
out_rd:
	rmdir(dirname);
out:
	return ret;
}
Example #8
0
int main(int argc, char **argv)
{
	int ret = 0;
	int readfd, writefd;
	mode_t mode = S_IFIFO | 0600;
	char path[PROCS_DEF][BUF_SIZE];
	pid_t pid;
	int i;
	uint8_t buf[0x100000];
	int chret;
	char *file_path;

	test_init(argc, argv);

	for (i = 0; i < PROCS_DEF; i++) {
		file_path = path[i];
		if (snprintf(file_path, BUF_SIZE, "%s-%02d", filename, i) >= BUF_SIZE) {
			err("filename %s is too long\n", filename);
			exit(1);
		}
		if (mkfifo(file_path, mode)) {
			err("can't make fifo \"%s\": %m\n", file_path);
			exit(1);
		}
	}

	pid = test_fork();
	if (pid < 0) {
		err("Can't fork: %m\n");
		kill(0, SIGKILL);
		exit(1);
	}
	if (pid == 0) {
		file_path = path[0];
		readfd = open(file_path, O_RDONLY);
		if (readfd < 0) {
			err("open(%s, O_RDONLY) Failed: %m\n", file_path);
			ret = errno;
			return ret;
		}
		file_path = path[1];
		writefd = open(file_path, O_WRONLY);
		if (writefd < 0) {
			err("open(%s, O_WRONLY) Failed: %m\n", file_path);
			ret = errno;
			return ret;
		}

		if (pipe_in2out(readfd, writefd, buf, sizeof(buf)) < 0)
			/* pass errno as exit code to the parent */
			if (test_go() /* signal NOT delivered */ ||
					(errno != EINTR && errno != EPIPE))
				ret = errno;
		close(readfd);
		close(writefd);
		exit(ret);
	}
	file_path = path[0];
	writefd = open(file_path, O_WRONLY);
	if (writefd < 0) {
		err("open(%s, O_WRONLY) Failed: %m\n", file_path);
		kill(pid, SIGKILL);
		return 1;
	}

	file_path = path[1];
	readfd = open(file_path, O_RDONLY);
	if (readfd < 0) {
		err("open(%s, O_RDONLY) Failed: %m\n", file_path);
		kill(pid, SIGKILL);
		return 1;
	}
	test_daemon();

	while (test_go()) {
		int len, rlen = 0, wlen;
		uint8_t rbuf[sizeof(buf)], *p;

		datagen(buf, sizeof(buf), NULL);
		wlen = write(writefd, buf, sizeof(buf));
		if (wlen < 0) {
			if (errno == EINTR)
				continue;
			else {
				fail("write failed: %m\n");
				ret = 1;
				break;
			}
		}

		for (p = rbuf, len = wlen; len > 0; p += rlen, len -= rlen) {
			rlen = read(readfd, p, len);
			if (rlen <= 0)
				break;
		}

		if (rlen < 0 && errno == EINTR)
			continue;

		if (len > 0) {
			fail("read failed: %m\n");
			ret = 1;
			break;
		}

		if (memcmp(buf, rbuf, wlen)) {
			fail("data mismatch\n");
			ret = 1;
			break;
		}
	}

	close(writefd);
	test_waitsig();

	wait(&chret);
	chret = WEXITSTATUS(chret);
	if (chret) {
		fail("child exited with non-zero code %d (%s)\n",
			chret, strerror(chret));
		return 1;
	}
	if (!ret)
		pass();
	close(readfd);
	for (i = 0; i < PROCS_DEF; i++)
		unlink(path[i]);
	return 0;
}
Example #9
0
	glm::vec4 get( int i )
	{
		return pass(i) ? window[i] : glm::vec4(0,0,0,1);
	}
Example #10
0
            void run() {
//                log() << "******** NOT RUNNING TruncateCapped test yet ************" << endl;
                pass(0);
            }
Example #11
0
int main(int argc, char **argv)
{
	struct sockaddr_un addr;
	unsigned int addrlen;
	int srv, clnt = -1, ret, i;
	char buf[1024];
	struct iovec iov = {
			.iov_base = &buf,
			.iov_len = sizeof(buf),
		};
	struct msghdr hdr = {
			.msg_name = &addr,
			.msg_namelen = sizeof(addr),
			.msg_iov = &iov,
			.msg_iovlen = 1,
		};

	test_init(argc, argv);

	srv = socket(PF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);

	addr.sun_family = AF_UNIX;
	memcpy(addr.sun_path, SK_SRV, sizeof(SK_SRV));
	addrlen = sizeof(addr.sun_family) + sizeof(SK_SRV);

	if (bind(srv, &addr, addrlen)) {
		fail("bind\n");
		exit(1);
	}

	for (i = 0; i < 2; i++) {
		close(clnt);
		clnt = socket(PF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);

		sk_names[i][1] += i;
		addr.sun_family = AF_UNIX;
		memcpy(addr.sun_path, sk_names[i], sizeof(SK_NAME));
		addrlen = sizeof(addr.sun_family) + sizeof(SK_NAME);

		if (bind(clnt, &addr, addrlen)) {
			fail("bind\n");
			exit(1);
		}

		memcpy(addr.sun_path, SK_SRV, sizeof(SK_SRV));
		addrlen = sizeof(addr.sun_family) + sizeof(SK_SRV);
		if (connect(clnt, &addr, addrlen)) {
			fail("connect\n");
			exit(1);
		}

		if (send(clnt, MSG, sizeof(MSG), 0) != sizeof(MSG)) {
			pr_perror("write");
			return 1;
		}
	}

	test_daemon();
	test_waitsig();

	for (i = 0; i < 2; i++) {
		memset(addr.sun_path, 0, sizeof(addr.sun_path));
		ret = recvmsg(srv, &hdr, MSG_DONTWAIT);
		buf[ret > 0 ? ret : 0] = 0;
		if (ret != sizeof(MSG)) {
			fail("%d: %s", ret, buf);
			return 1;
		}
		if (hdr.msg_namelen > sizeof(addr.sun_family) + 1)
			pr_perror("%d, %s", hdr.msg_namelen, addr.sun_path + 1);
		if (memcmp(addr.sun_path, sk_names[i], sizeof(SK_NAME))) {
			fail("A sender address is mismatch");
			return 1;
		}
	}

	pass();
	return 0;
}
Example #12
0
int main(int argc, char ** argv)
{
	int pipe1[2];
	int pipe2[2];
	int ret;
	pid_t pid;
	char buf[sizeof(TEST_STRING)];

	test_init(argc, argv);

	ret = pipe(pipe1);
	if (ret)
		return 1;

	ret = pipe(pipe2);
	if (ret)
		return 1;

	pid = test_fork();
	if (pid < 0) {
		err("Can't fork");
		exit(1);
	} else if (pid == 0) {
		if (dup2(pipe1[1], 11) == -1 || dup2(pipe2[0], 12) == -1) {
			err("dup2 failed");
			return 1;
		}
	} else {
		if (dup2(pipe1[0], 12) == -1 ||	dup2(pipe2[1], 11) == -1) {
			err("dup2 failed");
			goto err;
		}
	}

	close(pipe2[0]);
	close(pipe2[1]);
	close(pipe1[0]);
	close(pipe1[1]);

	if (pid > 0) {
		int status;

		test_daemon();

		test_waitsig();

		ret = read(12, buf, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("read failed: %d", ret);
			goto err;
		}
		ret = write(11, TEST_STRING, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("write failed: %d", ret);
			goto err;
		}
		close(11);
		ret = read(12, buf, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("read failed: %d", ret);
			goto err;
		}
		if (strcmp(TEST_STRING, buf)) {
			err("data curruption");
			goto err;
		}

		ret = wait(&status);
		if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
			kill(pid, SIGKILL);
			goto err;
		}

		pass();
	} else {
		ret = write(11, TEST_STRING, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("write failed: %d", ret);
			return 1;
		}
		ret = read(12, buf, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("read failed: %d", ret);
			return 1;
		}
		ret = write(11, TEST_STRING, sizeof(TEST_STRING));
		if (ret != sizeof(TEST_STRING)) {
			err("write failed: %d", ret);
			return 1;
		}
		close(11);
		if (strcmp(TEST_STRING, buf)) {
			err("data curruption");
			return 1;
		}
	}

	return 0;
err:
	err("FAIL");
	return 1;
}
int main(void)
{
	int trial;
	
	plan_tests(TRIAL_COUNT);
	
	for (trial = 1; trial <= TRIAL_COUNT; trial++) {
		int i, count;
		uchar_t codepoints[MAX_CHARS_PER_TRIAL];
		uchar_t c;
		bool c_valid;
		
		char write_buffer[MAX_CHARS_PER_TRIAL * 4];
		char *o = write_buffer;
		char *oe = write_buffer + sizeof(write_buffer);
		
		char *string;
		const char *s;
		const char *e;
		
		int len;
		
		count = rand32() % MAX_CHARS_PER_TRIAL + 1;
		
		for (i = 0; i < count; i++) {
			if (o >= oe) {
				fail("utf8_write_char: Buffer overflow (1)");
				goto next_trial;
			}
			
			switch (rand32() % 7) {
				case 0:
					c = range(rand32(), 0x0, 0x7F);
					c_valid = true;
					break;
				case 1:
					c = range(rand32(), 0x80, 0x7FF);
					c_valid = true;
					break;
				case 2:
					c = range(rand32(), 0x800, 0xD7FF);
					c_valid = true;
					break;
				case 3:
					c = range(rand32(), 0xD800, 0xDFFF);
					c_valid = false;
					break;
				case 4:
					c = range(rand32(), 0xE000, 0xFFFF);
					c_valid = true;
					break;
				case 5:
					c = range(rand32(), 0x10000, 0x10FFFF);
					c_valid = true;
					break;
				default:
					do {
						c = rand32();
					} while (c < 0x110000);
					c_valid = false;
					break;
			}
			
			codepoints[i] = c_valid ? c : REPLACEMENT_CHARACTER;
			
			len = utf8_write_char(c, o);
			if (len < 1 || len > 4) {
				fail("utf8_write_char: Return value is not 1 thru 4.");
				goto next_trial;
			}
			o += len;
		}
		if (o > oe) {
			fail("utf8_write_char: Buffer overflow (2)");
			goto next_trial;
		}
		
		string = malloc(o - write_buffer);
		memcpy(string, write_buffer, o - write_buffer);
		s = string;
		e = string + (o - write_buffer);
		
		if (!utf8_validate(s, e - s)) {
			fail("Invalid string produced by utf8_write_char.");
			goto next_trial_free_string;
		}
		
		for (i = 0; i < count; i++) {
			if (s >= e) {
				fail("utf8_read_char: Buffer overflow (1)");
				goto next_trial_free_string;
			}
			
			len = utf8_read_char(s, &c);
			if (len < 1 || len > 4) {
				fail("utf8_read_char: Return value is not 1 thru 4.");
				goto next_trial_free_string;
			}
			if (c != codepoints[i]) {
				fail("utf8_read_char: Character read differs from that written.");
				goto next_trial_free_string;
			}
			s += len;
		}
		if (s > e) {
			fail("utf8_read_char: Buffer overflow (2)");
			goto next_trial_free_string;
		}
		if (s < e) {
			fail("utf8_read_char: Did not reach end of string.");
			goto next_trial_free_string;
		}
		
		pass("Trial %d: %d characters", trial, count);
		
	next_trial_free_string:
		free(string);
	next_trial:;
	}
	
	return exit_status();
}
void performGeneratorification(UnlinkedCodeBlock* codeBlock, UnlinkedCodeBlock::UnpackedInstructions& instructions, SymbolTable* generatorFrameSymbolTable, int generatorFrameSymbolTableIndex)
{
    BytecodeGeneratorification pass(codeBlock, instructions, generatorFrameSymbolTable, generatorFrameSymbolTableIndex);
    pass.run();
}
Example #15
0
int main(int argc, char **argv)
{
	char path[PATH_MAX], bpath[PATH_MAX], spath[PATH_MAX], bspath[PATH_MAX];
	pid_t pid;
	int status;
	task_waiter_t t;

	test_init(argc, argv);

	task_waiter_init(&t);

	mount(NULL, "/", NULL, MS_SHARED, NULL);

	snprintf(path, sizeof(path), "%s/test", dirname);
	snprintf(bpath, sizeof(bpath), "%s/test.bind", dirname);
	snprintf(spath, sizeof(spath), "%s/test/sub", dirname);
	snprintf(bspath, sizeof(bspath), "%s/test.bind/sub", dirname);

	if (mkdir(dirname, 0700) ||
	    mkdir(path, 0700) ||
	    mkdir(spath, 0700) ||
	    mkdir(bpath, 0700)) {
		err("mkdir");
		return 1;
	}

	pid = fork();
	if (pid < 0) {
		err("fork");
		return 1;
	}
	if (pid == 0) {
		unshare(CLONE_NEWNS);
		if (mount(path, bpath, NULL, MS_BIND, NULL)) {
			err("mount");
			return 1;
		}

		task_waiter_complete(&t, 1);
		task_waiter_wait4(&t, 2);

		if (access(bspath, F_OK)) {
			fail("%s isn't accessiable", bspath);
			return 1;
		}


		if (umount2(bpath, MNT_DETACH)) {
			fail("umount");
			return 1;
		}

		return 0;
	}

	task_waiter_wait4(&t, 1);

	if (mount("test", spath, "tmpfs", 0, NULL)) {
		err("mount");
		return 1;
	}

	test_daemon();
	test_waitsig();

	task_waiter_complete(&t, 2);

	if (waitpid(pid, &status, 0) != pid) {
		err("waitpid %d", pid);
		return 1;
	}

	if (status) {
		err("%d/%d/%d/%d", WIFEXITED(status), WEXITSTATUS(status), WIFSIGNALED(status), WTERMSIG(status));
		return 1;
	}

	pass();

	return 0;
}
Example #16
0
 bool pass()
 {
    return pass( 0 );
 }
Example #17
0
int main(int argc, char *argv[])
{
    int        p[2];
    int        stdoutfd;
        struct obj exp;

        (void)argc;
        (void)argv;

    printf("1..1\n");
    fflush(stdout);
    stderrfd = dup(STDERR_FILENO);

    if (stderrfd < 0)
        err(1, "dup of stderr failed");

    stdoutfd = dup(STDOUT_FILENO);

    if (stdoutfd < 0)
        err(1, "dup of stdout failed");

    if (pipe(p) != 0)
        failmsg("pipe failed");

    if (dup2(p[1], STDERR_FILENO) < 0 || dup2(p[1], STDOUT_FILENO) < 0)
        failmsg("Duplicating file descriptor");

    plan_tests(10);
    expect(p[0], "1..10\n");

    ok(1, "msg1");
    expect(p[0], "ok 1 - msg1\n");

    ok(0, "msg2");
    expect(p[0], "not ok 2 - msg2\n"
           "#     Failed test (*tap/test/run.c:main() at line 199)\n");

    ok1(true);
    expect(p[0], "ok 3 - true\n");

    ok1(false);
    expect(p[0], "not ok 4 - false\n"
           "#     Failed test (*tap/test/run.c:main() at line 206)\n");

    pass("passed");
    expect(p[0], "ok 5 - passed\n");

    fail("failed");
    expect(p[0], "not ok 6 - failed\n"
           "#     Failed test (*tap/test/run.c:main() at line 213)\n");

    skip(2, "skipping %s", "test");
    expect(p[0], "ok 7 # skip skipping test\n"
           "ok 8 # skip skipping test\n");

    todo_start("todo");
    ok1(false);
    expect(p[0], "not ok 9 - false # TODO todo\n"
                 "#     Failed (TODO) test (*tap/test/run.c:main() at line 222)\n");
    ok1(true);
    expect(p[0], "ok 10 - true # TODO todo\n");
    todo_end();

    if (exit_status() != 3)
        failmsg("Expected exit status 3, not %i", exit_status());

        is(one_int(), 1, "one_int() returns 1");
        expect(p[0], "ok 11 - one_int() returns 1\n");
        is(one_int(), 2, "one_int() returns 2");
        expect(p[0], "not ok 12 - one_int() returns 2\n"
               "#     Failed test (*tap/test/run.c:main() at line 234)\n"
               "#          got: 1\n"
               "#     expected: 2\n");

        is_eq(one_str(), "one", "one_str() returns 'one'");
        expect(p[0], "ok 13 - one_str() returns 'one'\n");
        is_eq(one_str(), "two", "one_str() returns 'two'");
        expect(p[0], "not ok 14 - one_str() returns 'two'\n"
               "#     Failed test (*tap/test/run.c:main() at line 242)\n"
               "#          got: \"one\"\n"
               "#     expected: \"two\"\n");

        exp.id = 1;
        is_cmp(one_obj(), &exp, obj_cmp, obj_to_str, "one_obj() has id 1");
        expect(p[0], "ok 15 - one_obj() has id 1\n");
        exp.id = 2;
        is_cmp(one_obj(), &exp, obj_cmp, obj_to_str, "one_obj() has id 2");
        expect(p[0], "not ok 16 - one_obj() has id 2\n"
               "#     Failed test (*tap/test/run.c:main() at line 252)\n"
               "#          got: {id=1}\n"
               "#     expected: {id=2}\n");

        is_strstr(one_str(), "n", "one_str() contains 'n'");
        expect(p[0], "ok 17 - one_str() contains 'n'\n");
        is_strstr(one_str(), "w", "one_str() contains 'w'");
        expect(p[0], "not ok 18 - one_str() contains 'w'\n"
               "#     Failed test (*tap/test/run.c:main() at line 260)\n"
               "#                     got: \"one\"\n"
               "#     expected to contain: \"w\"\n");
#if 0
    /* Manually run the atexit command. */
    _cleanup();
    expect(p[0], "# Looks like you failed 2 tests of 9.\n");
#endif

    write_all(stdoutfd, "ok 1 - All passed\n",
          strlen("ok 1 - All passed\n"));
    _exit(0);
}
Example #18
0
int main(int argc, char ** argv)
{
    int sock, acc_sock, ret;
    pid_t pid;
    uint32_t crc;
    uint8_t buf[1000];

    test_init(argc, argv);

    sock = setup_srv_sock();
    if (sock < 0)
        exit(1);

    pid = test_fork();
    if (pid < 0) {
        pr_perror("can't fork");
        exit(1);
    }

    if (pid == 0) {	/* child writes to the unlinked socket and returns */
        close(sock);

        sock = setup_clnt_sock();
        if (sock < 0)
            _exit(1);

        test_waitsig();

        crc = ~0;
        datagen(buf, sizeof(buf), &crc);
        if (write(sock, buf, sizeof(buf)) != sizeof(buf)) {
            pr_perror("can't write to socket");
            exit(errno);
        }

        close(sock);
        exit(0);
    }

    acc_sock = accept(sock, NULL, NULL);
    if (acc_sock < 0) {
        pr_perror("can't accept() the connection on \"%s\"", filename);
        goto out_kill;
    }

    close(sock);
    sock = acc_sock;

    if (unlink(filename)) {
        pr_perror("can't unlink %s", filename);
        goto out_kill;
    }

    test_daemon();
    test_waitsig();

    if (kill(pid, SIGTERM)) {
        fail("terminating the child failed: %m\n");
        goto out;
    }

    if (wait(&ret) != pid) {
        fail("wait() returned wrong pid %d: %m\n", pid);
        goto out;
    }

    if (WIFEXITED(ret)) {
        ret = WEXITSTATUS(ret);
        if (ret) {
            fail("child exited with nonzero code %d (%s)\n", ret, strerror(ret));
            goto out;
        }
    }
    if (WIFSIGNALED(ret)) {
        fail("child exited on unexpected signal %d\n", WTERMSIG(ret));
        goto out;
    }

    if (read(sock, buf, sizeof(buf)) != sizeof(buf)) {
        fail("can't read %s: %m\n", filename);
        goto out;
    }

    crc = ~0;
    if (datachk(buf, sizeof(buf), &crc)) {
        fail("CRC mismatch\n");
        goto out;
    }


    if (close(sock)) {
        fail("close failed: %m\n");
        goto out;
    }

    if (unlink(filename) != -1 || errno != ENOENT) {
        fail("file %s should have been deleted before migration: unlink: %m\n", filename);
        goto out;
    }

    pass();

out_kill:
    kill(pid, SIGTERM);
out:
    close(sock);
    return 0;
}
Example #19
0
int main(int argc, char **argv)
{
	int fd, fd_s, clt;
	char cmd[4096], buf[10];

	test_init(argc, argv);
	signal(SIGPIPE, SIG_IGN);

	if ((fd_s = tcp_init_server(ZDTM_SRV_FAMILY, &port)) < 0) {
		pr_err("initializing server failed\n");
		return 1;
	}


	clt = tcp_init_client(ZDTM_FAMILY, "localhost", port);
	if (clt < 0) {
		pr_perror("Unable to create a client socket");
	        return 1;
	}

	/*
	* parent is server of TCP connection
	*/
	fd = tcp_accept_server(fd_s);
	if (fd < 0) {
		pr_err("can't accept client connection\n");
		return 1;
	}
	if (write(clt, "asd", 3) != 3) {
		pr_perror("Unable to write into a socket");
		return 1;
	}
	snprintf(cmd, sizeof(cmd), "iptables -w -t filter --protocol tcp -A INPUT --dport %d -j REJECT --reject-with tcp-reset", port);
	if (system(cmd))
		return 1;

	if (write(fd, "asdas", 5) == -1) {
		pr_perror("Unable to write into a socket");
		return 1;
	}

	snprintf(cmd, sizeof(cmd), "iptables -w -t filter --protocol tcp -D INPUT --dport %d -j REJECT --reject-with tcp-reset", port);
	if (system(cmd))
		return 1;

	test_daemon();
	test_waitsig();

	if (read(fd, buf, sizeof(buf)) != 3) {
		fail("Unable to read data from a socket");
		return 1;
	}

	if (write(fd, buf, 3) != -1) {
		fail("Can write into a closed socket");
		return 1;
	}

	pass();
	return 0;
}
Example #20
0
static int test_fn(int argc, char **argv)
{
	FILE *f;
	int fd, tmpfs_fd;
	unsigned fs_cnt, fs_cnt_last = 0;

again:
	fs_cnt = 0;
	f = fopen("/proc/self/mountinfo", "r");
	if (!f) {
		fail("Can't open mountinfo");
		return -1;
	}

	while (fgets(buf, sizeof(buf), f) != NULL) {
		char *mp = buf, *end;

		mp = strchr(mp, ' ') + 1;
		mp = strchr(mp, ' ') + 1;
		mp = strchr(mp, ' ') + 1;
		mp = strchr(mp, ' ') + 1;
		end = strchr(mp, ' ');
		*end = '\0';

		if (!strcmp(mp, "/"))
			continue;
		if (!strcmp(mp, "/proc"))
			continue;

		umount(mp);
		fs_cnt++;
	}

	fclose(f);

	if (fs_cnt == 0)
		goto done;

	if (fs_cnt != fs_cnt_last) {
		fs_cnt_last = fs_cnt;
		goto again;
	}

	fail("Can't umount all the filesystems");
	return -1;

done:
	rmdir(MPTS_ROOT);
	if (mkdir(MPTS_ROOT, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}

	if (mount("none", MPTS_ROOT, "sysfs", 0, "") < 0) {
		fail("Can't mount sysfs");
		return 1;
	}

	if (mount("none", MPTS_ROOT"/dev", "tmpfs", 0, "") < 0) {
		fail("Can't mount tmpfs");
		return 1;
	}
	tmpfs_fd = open(MPTS_ROOT"/dev/test", O_WRONLY | O_CREAT);
	if (write(tmpfs_fd, "hello", 5) <= 0) {
		err("write() failed");
		return 1;
	}

	if (mount("none", MPTS_ROOT"/kernel", "proc", 0, "") < 0) {
		fail("Can't mount proc");
		return 1;
	}
	if (mount("none", MPTS_ROOT"/kernel/sys/fs/binfmt_misc",
					"binfmt_misc", 0, "") < 0) {
		fail("Can't mount proc");
		return 1;
	}

	mknod("/dev/null", 0777 | S_IFCHR, makedev(1, 3));

	setup_outfile();

	fd = open(MPTS_ROOT"/kernel/meminfo", O_RDONLY);
	if (fd == -1)
		return 1;

	test_daemon();
	test_waitsig();

	/* this checks both -- sys and proc presence */
	if (access(MPTS_ROOT"/kernel/meminfo", F_OK)) {
		fail("No proc after restore");
		return 1;
	}

	pass();
	return 0;
}
Example #21
0
void TestPreferences::testPreferences()
{
	auto pref = SettingsObjectWrapper::instance();
	pref->load();

	auto cloud = pref->cloud_storage;
	cloud->setBackgroundSync(true);
	TEST(cloud->backgroundSync(), true);
	cloud->setBackgroundSync(false);
	TEST(cloud->backgroundSync(), false);

	cloud->setBaseUrl("test_one");
	TEST(cloud->baseUrl(), QStringLiteral("test_one"));
	cloud->setBaseUrl("test_two");
	TEST(cloud->baseUrl(), QStringLiteral("test_two"));

	cloud->setEmail("*****@*****.**");
	TEST(cloud->email(), QStringLiteral("*****@*****.**"));
	cloud->setEmail("*****@*****.**");
	TEST(cloud->email(), QStringLiteral("*****@*****.**"));

	cloud->setGitLocalOnly(true);
	TEST(cloud->gitLocalOnly(), true);
	cloud->setGitLocalOnly(false);
	TEST(cloud->gitLocalOnly(), false);

	// Why there's new password and password on the prefs?
	cloud->setNewPassword("ABCD");
	TEST(cloud->newPassword(), QStringLiteral("ABCD"));
	cloud->setNewPassword("ABCDE");
	TEST(cloud->newPassword(), QStringLiteral("ABCDE"));

	cloud->setPassword("ABCDE");
	TEST(cloud->password(), QStringLiteral("ABCDE"));
	cloud->setPassword("ABCABC");
	TEST(cloud->password(), QStringLiteral("ABCABC"));

	cloud->setSavePasswordLocal(true);
	TEST(cloud->savePasswordLocal(), true);
	cloud->setSavePasswordLocal(false);
	TEST(cloud->savePasswordLocal(), false);

	// Why this is short and not bool?
	cloud->setSaveUserIdLocal(1);
	TEST(cloud->saveUserIdLocal(), (short)1);
	cloud->setSaveUserIdLocal(0);
	TEST(cloud->saveUserIdLocal(), (short)0);

	cloud->setUserId("Tomaz");
	TEST(cloud->userId(), QStringLiteral("Tomaz"));
	cloud->setUserId("Zamot");
	TEST(cloud->userId(), QStringLiteral("Zamot"));

	cloud->setVerificationStatus(0);
	TEST(cloud->verificationStatus(), (short)0);
	cloud->setVerificationStatus(1);
	TEST(cloud->verificationStatus(), (short)1);

	auto tecDetails = pref->techDetails;
	tecDetails->setModp02(0.2);
	TEST(tecDetails->modp02(), 0.2);
	tecDetails->setModp02(1.0);
	TEST(tecDetails->modp02(), 1.0);

	tecDetails->setGflow(2);
	TEST(tecDetails->gflow(), 2);
	tecDetails->setGflow(3);
	TEST(tecDetails->gflow(), 3);

	tecDetails->setGfhigh(4);
	TEST(tecDetails->gfhigh(), 4);
	tecDetails->setGfhigh(5);
	TEST(tecDetails->gfhigh(), 5);

	tecDetails->setVpmbConservatism(5);
	TEST(tecDetails->vpmbConservatism(), (short)5);
	tecDetails->setVpmbConservatism(6);
	TEST(tecDetails->vpmbConservatism(), (short)6);

	tecDetails->setEad(true);
	TEST(tecDetails->ead(), true);
	tecDetails->setMod(true);
	TEST(tecDetails->mod(), true);
	tecDetails->setDCceiling(true);
	TEST(tecDetails->dcceiling(), true);
	tecDetails->setRedceiling(true);
	TEST(tecDetails->redceiling(), true);
	tecDetails->setCalcceiling(true);
	TEST(tecDetails->calcceiling(), true);
	tecDetails->setCalcceiling3m(true);
	TEST(tecDetails->calcceiling3m(), true);
	tecDetails->setCalcalltissues(true);
	TEST(tecDetails->calcalltissues(), true);
	tecDetails->setCalcndltts(true);
	TEST(tecDetails->calcndltts(), true);
	tecDetails->setBuehlmann(true);
	TEST(tecDetails->buehlmann(), true);
	tecDetails->setHRgraph(true);
	TEST(tecDetails->hrgraph(), true);
	tecDetails->setTankBar(true);
	TEST(tecDetails->tankBar(), true);
	tecDetails->setPercentageGraph(true);
	TEST(tecDetails->percentageGraph(), true);
	tecDetails->setRulerGraph(true);
	TEST(tecDetails->rulerGraph(), true);
	tecDetails->setShowCCRSetpoint(true);
	TEST(tecDetails->showCCRSetpoint(), true);
	tecDetails->setShowCCRSensors(true);
	TEST(tecDetails->showCCRSensors(), true);
	tecDetails->setZoomedPlot(true);
	TEST(tecDetails->zoomedPlot(), true);
	tecDetails->setShowSac(true);
	TEST(tecDetails->showSac(), true);
	tecDetails->setGfLowAtMaxDepth(true);
	TEST(tecDetails->gfLowAtMaxDepth(), true);
	tecDetails->setDisplayUnusedTanks(true);
	TEST(tecDetails->displayUnusedTanks(), true);
	tecDetails->setShowAverageDepth(true);
	TEST(tecDetails->showAverageDepth(), true);
	tecDetails->setShowPicturesInProfile(true);
	TEST(tecDetails->showPicturesInProfile(), true);

	tecDetails->setEad(false);
	TEST(tecDetails->ead(), false);
	tecDetails->setMod(false);
	TEST(tecDetails->mod(), false);
	tecDetails->setDCceiling(false);
	TEST(tecDetails->dcceiling(), false);
	tecDetails->setRedceiling(false);
	TEST(tecDetails->redceiling(), false);
	tecDetails->setCalcceiling(false);
	TEST(tecDetails->calcceiling(), false);
	tecDetails->setCalcceiling3m(false);
	TEST(tecDetails->calcceiling3m(), false);
	tecDetails->setCalcalltissues(false);
	TEST(tecDetails->calcalltissues(), false);
	tecDetails->setCalcndltts(false);
	TEST(tecDetails->calcndltts(), false);
	tecDetails->setBuehlmann(false);
	TEST(tecDetails->buehlmann(), false);
	tecDetails->setHRgraph(false);
	TEST(tecDetails->hrgraph(), false);
	tecDetails->setTankBar(false);
	TEST(tecDetails->tankBar(), false);
	tecDetails->setPercentageGraph(false);
	TEST(tecDetails->percentageGraph(), false);
	tecDetails->setRulerGraph(false);
	TEST(tecDetails->rulerGraph(), false);
	tecDetails->setShowCCRSetpoint(false);
	TEST(tecDetails->showCCRSetpoint(), false);
	tecDetails->setShowCCRSensors(false);
	TEST(tecDetails->showCCRSensors(), false);
	tecDetails->setZoomedPlot(false);
	TEST(tecDetails->zoomedPlot(), false);
	tecDetails->setShowSac(false);
	TEST(tecDetails->showSac(), false);
	tecDetails->setGfLowAtMaxDepth(false);
	TEST(tecDetails->gfLowAtMaxDepth(), false);
	tecDetails->setDisplayUnusedTanks(false);
	TEST(tecDetails->displayUnusedTanks(), false);
	tecDetails->setShowAverageDepth(false);
	TEST(tecDetails->showAverageDepth(), false);
	tecDetails->setShowPicturesInProfile(false);
	TEST(tecDetails->showPicturesInProfile(), false);

	auto pp = pref->pp_gas;
	pp->setShowPn2(false);
	pp->setShowPhe(false);
	pp->setShowPo2(false);
	pp->setPo2Threshold(1.0);
	pp->setPn2Threshold(2.0);
	pp->setPheThreshold(3.0);

	TEST(pp->showPn2(), (short) false);
	TEST(pp->showPhe(), (short) false);
	TEST(pp->showPo2(), (short) false);
	TEST(pp->pn2Threshold(), 2.0);
	TEST(pp->pheThreshold(), 3.0);
	TEST(pp->po2Threshold(), 1.0);

	pp->setShowPn2(true);
	pp->setShowPhe(true);
	pp->setShowPo2(true);
	pp->setPo2Threshold(4.0);
	pp->setPn2Threshold(5.0);
	pp->setPheThreshold(6.0);

	TEST(pp->showPn2(), (short) true);
	TEST(pp->showPhe(), (short) true);
	TEST(pp->showPo2(), (short) true);
	TEST(pp->pn2Threshold(), 5.0);
	TEST(pp->pheThreshold(), 6.0);
	TEST(pp->po2Threshold(), 4.0);

	auto fb = pref->facebook;
	fb->setAccessToken("rand-access-token");
	fb->setUserId("tomaz-user-id");
	fb->setAlbumId("album-id");

	TEST(fb->accessToken(),QStringLiteral("rand-access-token"));
	TEST(fb->userId(),     QStringLiteral("tomaz-user-id"));
	TEST(fb->albumId(),    QStringLiteral("album-id"));

	fb->setAccessToken("rand-access-token-2");
	fb->setUserId("tomaz-user-id-2");
	fb->setAlbumId("album-id-2");

	TEST(fb->accessToken(),QStringLiteral("rand-access-token-2"));
	TEST(fb->userId(),     QStringLiteral("tomaz-user-id-2"));
	TEST(fb->albumId(),    QStringLiteral("album-id-2"));

	auto geo = pref->geocoding;
	geo->setEnableGeocoding(true);
	geo->setParseDiveWithoutGps(true);
	geo->setTagExistingDives(true);

	TEST(geo->enableGeocoding(),true);
	TEST(geo->parseDiveWithoutGps(),true);
	TEST(geo->tagExistingDives(),true);

	geo->setFirstTaxonomyCategory(TC_NONE);
	geo->setSecondTaxonomyCategory(TC_OCEAN);
	geo->setThirdTaxonomyCategory(TC_COUNTRY);

	TEST(geo->firstTaxonomyCategory(), TC_NONE);
	TEST(geo->secondTaxonomyCategory(), TC_OCEAN);
	TEST(geo->thirdTaxonomyCategory(), TC_COUNTRY);

	geo->setEnableGeocoding(false);
	geo->setParseDiveWithoutGps(false);
	geo->setTagExistingDives(false);

	TEST(geo->enableGeocoding(),false);
	TEST(geo->parseDiveWithoutGps(),false);
	TEST(geo->tagExistingDives(),false);

	geo->setFirstTaxonomyCategory(TC_OCEAN);
	geo->setSecondTaxonomyCategory(TC_COUNTRY);
	geo->setThirdTaxonomyCategory(TC_NONE);

	TEST(geo->firstTaxonomyCategory(), TC_OCEAN);
	TEST(geo->secondTaxonomyCategory(), TC_COUNTRY);
	TEST(geo->thirdTaxonomyCategory(), TC_NONE);

	auto proxy = pref->proxy;
	proxy->setType(2);
	proxy->setPort(80);
	proxy->setAuth(true);
	proxy->setHost("localhost");
	proxy->setUser("unknown");
	proxy->setPass("secret");

	TEST(proxy->type(),2);
	TEST(proxy->port(),80);
	TEST(proxy->auth(),true);
	TEST(proxy->host(),QStringLiteral("localhost"));
	TEST(proxy->user(),QStringLiteral("unknown"));
	TEST(proxy->pass(),QStringLiteral("secret"));

	proxy->setType(3);
	proxy->setPort(8080);
	proxy->setAuth(false);
	proxy->setHost("127.0.0.1");
	proxy->setUser("unknown_1");
	proxy->setPass("secret_1");

	TEST(proxy->type(),3);
	TEST(proxy->port(),8080);
	TEST(proxy->auth(),false);
	TEST(proxy->host(),QStringLiteral("127.0.0.1"));
	TEST(proxy->user(),QStringLiteral("unknown_1"));
	TEST(proxy->pass(),QStringLiteral("secret_1"));

	auto planner = pref->planner_settings;
	planner->setLastStop(true);
	planner->setVerbatimPlan(true);
	planner->setDisplayRuntime(true);
	planner->setDisplayDuration(true);
	planner->setDisplayTransitions(true);
	planner->setDoo2breaks(true);
	planner->setDropStoneMode(true);
	planner->setSafetyStop(true);
	planner->setSwitchAtRequiredStop(true);

	planner->setAscrate75(1);
	planner->setAscrate50(2);
	planner->setAscratestops(3);
	planner->setAscratelast6m(4);
	planner->setDescrate(5);
	planner->setBottompo2(6);
	planner->setDecopo2(7);
	planner->setBestmixend(8);
	planner->setReserveGas(9);
	planner->setMinSwitchDuration(10);
	planner->setBottomSac(11);
	planner->setDecoSac(12);

	planner->setDecoMode(BUEHLMANN);

	TEST(planner->lastStop(),true);
	TEST(planner->verbatimPlan(),true);
	TEST(planner->displayRuntime(),true);
	TEST(planner->displayDuration(),true);
	TEST(planner->displayTransitions(),true);
	TEST(planner->doo2breaks(),true);
	TEST(planner->dropStoneMode(),true);
	TEST(planner->safetyStop(),true);
	TEST(planner->switchAtRequiredStop(),true);

	TEST(planner->ascrate75(),1);
	TEST(planner->ascrate50(),2);
	TEST(planner->ascratestops(),3);
	TEST(planner->ascratelast6m(),4);
	TEST(planner->descrate(),5);
	TEST(planner->bottompo2(),6);
	TEST(planner->decopo2(),7);
	TEST(planner->bestmixend(),8);
	TEST(planner->reserveGas(),9);
	TEST(planner->minSwitchDuration(),10);
	TEST(planner->bottomSac(),11);
	TEST(planner->decoSac(),12);

	TEST(planner->decoMode(),BUEHLMANN);

	planner->setLastStop(false);
	planner->setVerbatimPlan(false);
	planner->setDisplayRuntime(false);
	planner->setDisplayDuration(false);
	planner->setDisplayTransitions(false);
	planner->setDoo2breaks(false);
	planner->setDropStoneMode(false);
	planner->setSafetyStop(false);
	planner->setSwitchAtRequiredStop(false);

	planner->setAscrate75(11);
	planner->setAscrate50(12);
	planner->setAscratestops(13);
	planner->setAscratelast6m(14);
	planner->setDescrate(15);
	planner->setBottompo2(16);
	planner->setDecopo2(17);
	planner->setBestmixend(18);
	planner->setReserveGas(19);
	planner->setMinSwitchDuration(110);
	planner->setBottomSac(111);
	planner->setDecoSac(112);

	planner->setDecoMode(RECREATIONAL);

	TEST(planner->lastStop(),false);
	TEST(planner->verbatimPlan(),false);
	TEST(planner->displayRuntime(),false);
	TEST(planner->displayDuration(),false);
	TEST(planner->displayTransitions(),false);
	TEST(planner->doo2breaks(),false);
	TEST(planner->dropStoneMode(),false);
	TEST(planner->safetyStop(),false);
	TEST(planner->switchAtRequiredStop(),false);

	TEST(planner->ascrate75(),11);
	TEST(planner->ascrate50(),12);
	TEST(planner->ascratestops(),13);
	TEST(planner->ascratelast6m(),14);
	TEST(planner->descrate(),15);
	TEST(planner->bottompo2(),16);
	TEST(planner->decopo2(),17);
	TEST(planner->bestmixend(),18);
	TEST(planner->reserveGas(),19);
	TEST(planner->minSwitchDuration(),110);
	TEST(planner->bottomSac(),111);
	TEST(planner->decoSac(),112);

	TEST(planner->decoMode(),RECREATIONAL);

	auto units = pref->unit_settings;
	units->setLength(0);
	units->setPressure(0);
	units->setVolume(0);
	units->setTemperature(0);
	units->setWeight(0);
	units->setVerticalSpeedTime(0);
	units->setUnitSystem(QStringLiteral("metric"));
	units->setCoordinatesTraditional(false);

	TEST(units->length(),0);
	TEST(units->pressure(),0);
	TEST(units->volume(),0);
	TEST(units->temperature(),0);
	TEST(units->weight(),0);
	TEST(units->verticalSpeedTime(),0);
	TEST(units->unitSystem(),QStringLiteral("metric"));
	TEST(units->coordinatesTraditional(),false);

	units->setLength(1);
	units->setPressure(1);
	units->setVolume(1);
	units->setTemperature(1);
	units->setWeight(1);
	units->setVerticalSpeedTime(1);
	units->setUnitSystem(QStringLiteral("fake-metric-system"));
	units->setCoordinatesTraditional(true);

	TEST(units->length(),1);
	TEST(units->pressure(),1);
	TEST(units->volume(),1);
	TEST(units->temperature(),1);
	TEST(units->weight(),1);
	TEST(units->verticalSpeedTime(),1);
	TEST(units->unitSystem(),QStringLiteral("personalized"));
	TEST(units->coordinatesTraditional(),true);

	auto general = pref->general_settings;
	general->setDefaultFilename       ("filename");
	general->setDefaultCylinder       ("cylinder_2");
	//TODOl: Change this to a enum. 	// This is 'undefined', it will need to figure out later between no_file or use_deault file.
	general->setDefaultFileBehavior   (0);
	general->setDefaultSetPoint       (0);
	general->setO2Consumption         (0);
	general->setPscrRatio             (0);
	general->setUseDefaultFile        (true);

	TEST(general->defaultFilename(), QStringLiteral("filename"));
	TEST(general->defaultCylinder(), QStringLiteral("cylinder_2"));
	TEST(general->defaultFileBehavior(), (short) LOCAL_DEFAULT_FILE); // since we have a default file, here it returns
	TEST(general->defaultSetPoint(), 0);
	TEST(general->o2Consumption(), 0);
	TEST(general->pscrRatio(), 0);
	TEST(general->useDefaultFile(), true);

	general->setDefaultFilename       ("no_file_name");
	general->setDefaultCylinder       ("cylinder_1");
	//TODOl: Change this to a enum.
	general->setDefaultFileBehavior   (CLOUD_DEFAULT_FILE);

	general->setDefaultSetPoint       (1);
	general->setO2Consumption         (1);
	general->setPscrRatio             (1);
	general->setUseDefaultFile        (false);

	TEST(general->defaultFilename(), QStringLiteral("no_file_name"));
	TEST(general->defaultCylinder(), QStringLiteral("cylinder_1"));
	TEST(general->defaultFileBehavior(), (short) CLOUD_DEFAULT_FILE);
	TEST(general->defaultSetPoint(), 1);
	TEST(general->o2Consumption(), 1);
	TEST(general->pscrRatio(), 1);
	TEST(general->useDefaultFile(), false);

	auto display = pref->display_settings;
	display->setDivelistFont("comic");
	display->setFontSize(10.0);
	display->setDisplayInvalidDives(true);

	TEST(display->divelistFont(),QStringLiteral("comic"));
	TEST(display->fontSize(), 10.0);
	TEST(display->displayInvalidDives(),(short) true); //TODO: this is true / false.

	display->setDivelistFont("helvetica");
	display->setFontSize(14.0);
	display->setDisplayInvalidDives(false);

	TEST(display->divelistFont(),QStringLiteral("helvetica"));
	TEST(display->fontSize(), 14.0);
	TEST(display->displayInvalidDives(),(short) false);

	auto language = pref->language_settings;
	language->setLangLocale         ("en_US");
	language->setLanguage           ("en");
	language->setTimeFormat         ("hh:mm");
	language->setDateFormat         ("dd/mm/yy");
	language->setDateFormatShort    ("dd/mm");
	language->setTimeFormatOverride (false);
	language->setDateFormatOverride (false);
	language->setUseSystemLanguage  (false);

	TEST(language->langLocale(), QStringLiteral("en_US"));
	TEST(language->language(), QStringLiteral("en"));
	TEST(language->timeFormat(), QStringLiteral("hh:mm"));
	TEST(language->dateFormat(), QStringLiteral("dd/mm/yy"));
	TEST(language->dateFormatShort(), QStringLiteral("dd/mm"));
	TEST(language->timeFormatOverride(), false);
	TEST(language->dateFormatOverride(), false);
	TEST(language->useSystemLanguage(), false);

	language->setLangLocale         ("en_EN");
	language->setLanguage           ("br");
	language->setTimeFormat         ("mm:hh");
	language->setDateFormat         ("yy/mm/dd");
	language->setDateFormatShort    ("dd/yy");
	language->setTimeFormatOverride (true);
	language->setDateFormatOverride (true);
	language->setUseSystemLanguage  (true);

	TEST(language->langLocale(), QStringLiteral("en_EN"));
	TEST(language->language(), QStringLiteral("br"));
	TEST(language->timeFormat(), QStringLiteral("mm:hh"));
	TEST(language->dateFormat(), QStringLiteral("yy/mm/dd"));
	TEST(language->dateFormatShort(), QStringLiteral("dd/yy"));
	TEST(language->timeFormatOverride(),true);
	TEST(language->dateFormatOverride(),true);
	TEST(language->useSystemLanguage(), true);

	pref->animation_settings->setAnimationSpeed(20);
	TEST(pref->animation_settings->animationSpeed(), 20);
	pref->animation_settings->setAnimationSpeed(30);
	TEST(pref->animation_settings->animationSpeed(), 30);

	auto location = pref->location_settings;
	location->setTimeThreshold(10);
	location->setDistanceThreshold(20);

	TEST(location->timeThreshold(), 10);
	TEST(location->distanceThreshold(), 20);

	location->setTimeThreshold(30);
	location->setDistanceThreshold(40);

	TEST(location->timeThreshold(), 30);
	TEST(location->distanceThreshold(), 40);

	auto update = pref->update_manager_settings;
	QDate date = QDate::currentDate();

	update->setDontCheckForUpdates(true);
	update->setLastVersionUsed("tomaz-1");
	update->setNextCheck(date);

	TEST(update->dontCheckForUpdates(), true);
	TEST(update->lastVersionUsed(), QStringLiteral("tomaz-1"));
	TEST(update->nextCheck(), date);

	date.addDays(3);
	update->setDontCheckForUpdates(false);
	update->setLastVersionUsed("tomaz-2");
	update->setNextCheck(date);

	TEST(update->dontCheckForUpdates(), false);
	TEST(update->lastVersionUsed(), QStringLiteral("tomaz-2"));
	TEST(update->nextCheck(), date);

	auto dc = pref->dive_computer_settings;
	dc->setDevice("TomazComputer");
	TEST(dc->dc_device(), QStringLiteral("TomazComputer"));
	dc->setDevice("Deepwater");
	TEST(dc->dc_device(), QStringLiteral("Deepwater"));

	dc->setDownloadMode(0);
	TEST(dc->downloadMode(), 0);
	dc->setDownloadMode(1);
	TEST(dc->downloadMode(), 1);

	dc->setProduct("Thingy1");
	TEST(dc->dc_product(), QStringLiteral("Thingy1"));
	dc->setProduct("Thingy2");
	TEST(dc->dc_product(), QStringLiteral("Thingy2"));

	dc->setVendor("Sharewater");
	TEST(dc->dc_vendor(), QStringLiteral("Sharewater"));
	dc->setVendor("OSTS");
	TEST(dc->dc_vendor(), QStringLiteral("OSTS"));
}
Example #22
0
int main(int argc, char **argv)
{
	int ret, sk1, sk2;
	socklen_t len = sizeof(struct sockaddr_in);
	struct sockaddr_in addr1, addr2, addr;

	test_init(argc, argv);

	sk1 = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDPLITE);
	if (sk1 < 0) {
		err("Can't create socket");
		return 1;
	}

	memset(&addr1, 0, sizeof(addr1));
	addr1.sin_family = AF_INET;
	addr1.sin_addr.s_addr = inet_addr("127.0.0.1");
	addr1.sin_port = htons(port);

	ret = bind(sk1, (struct sockaddr *)&addr1, len);
	if (ret < 0) {
		err("Can't bind socket");
		return 1;
	}

	sk2 = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDPLITE);
	if (sk2 < 0) {
		err("Can't create socket");
		return 1;
	}

	memset(&addr2, 0, sizeof(addr1));
	addr2.sin_family = AF_INET;
	addr2.sin_addr.s_addr = inet_addr("127.0.0.1");
	addr2.sin_port = htons(port + 1);

	ret = bind(sk2, (struct sockaddr *)&addr2, len);
	if (ret < 0) {
		err("Can't bind socket");
		return 1;
	}

	ret = connect(sk2, (struct sockaddr *)&addr1, len);
	if (ret < 0) {
		err("Can't connect");
		return 1;
	}

	test_daemon();
	test_waitsig();

	ret = sendto(sk1, MSG1, sizeof(MSG1), 0,
			(struct sockaddr *)&addr2, len);
	if (ret < 0) {
		fail("Can't send");
		return 1;
	}

	ret = send(sk2, MSG2, sizeof(MSG2), 0);
	if (ret < 0) {
		fail("Can't send C");
		return 1;
	}

	ret = recvfrom(sk1, buf, sizeof(buf), MSG_DONTWAIT,
			(struct sockaddr *)&addr, &len);
	if (ret <= 0) {
		fail("Can't recv C");
		return 1;
	}

	if (len != sizeof(struct sockaddr_in) || memcmp(&addr2, &addr, len)) {
		fail("Wrong peer C");
		return 1;
	}

	if (ret != sizeof(MSG2) || memcmp(buf, MSG2, ret)) {
		fail("Wrong message C");
		return 1;
	}

	ret = recvfrom(sk2, buf, sizeof(buf), MSG_DONTWAIT,
			(struct sockaddr *)&addr, &len);
	if (ret <= 0) {
		fail("Can't recv");
		return 1;
	}

	if (len != sizeof(struct sockaddr_in) || memcmp(&addr1, &addr, len)) {
		fail("Wrong peer");
		return 1;
	}

	if (ret != sizeof(MSG1) || memcmp(buf, MSG1, ret)) {
		fail("Wrong message");
		return 1;
	}

	pass();
	return 0;
}
Example #23
0
message *
message_register::duplicate() {
    return new message_register(id(), user(), pass(), mail());
}
Example #24
0
/*
 * Handles commands received from the slave process. It will not return
 * except in one situation: After successful authentication it will
 * return as the user-privileged slave process.
 */
void
handle_cmds(void)
{
	enum monitor_command cmd;
	enum auth_ret auth;
	int err, s, slavequit, serrno, domain;
	pid_t preauth_slave_pid;
	size_t len;
	union sockunion sa;
	socklen_t salen;
	char *name, *pw;

	for (;;) {
		recv_data(fd_slave, &cmd, sizeof(cmd));

		switch (cmd) {
		case CMD_USER:
			debugmsg("CMD_USER received");

			recv_data(fd_slave, &len, sizeof(len));
			if (len == SIZE_T_MAX)
				fatalx("monitor received invalid user length");
			if ((name = malloc(len + 1)) == NULL)
				fatalx("malloc: %m");
			if (len > 0)
				recv_data(fd_slave, name, len);
			name[len] = '\0';

			user(name);
			free(name);
			break;
		case CMD_PASS:
			debugmsg("CMD_PASS received");

			recv_data(fd_slave, &len, sizeof(len));
			if (len == SIZE_T_MAX)
				fatalx("monitor received invalid pass length");
			if ((pw = malloc(len + 1)) == NULL)
				fatalx("malloc: %m");
			if (len > 0)
				recv_data(fd_slave, pw, len);
			pw[len] = '\0';

			preauth_slave_pid = slave_pid;

			auth = pass(pw);
			bzero(pw, len);
			free(pw);

			switch (auth) {
			case AUTH_FAILED:
				/* Authentication failure */
				debugmsg("authentication failed");
				slavequit = 0;
				send_data(fd_slave, &slavequit,
				    sizeof(slavequit));
				break;
			case AUTH_SLAVE:
				/* User-privileged slave */
				debugmsg("user-privileged slave started");
				return;
				/* NOTREACHED */
			case AUTH_MONITOR:
				/* Post-auth monitor */
				debugmsg("monitor went into post-auth phase");
				state = POSTAUTH;
#ifdef HASSETPROCTITLE
				setproctitle("%s: [priv post-auth]",
				    remotehost);
#endif
				slavequit = 1;

				send_data(fd_slave, &slavequit,
				    sizeof(slavequit));

				while (waitpid(preauth_slave_pid, NULL, 0) < 0 &&
				    errno == EINTR)
					;
				break;
			default:
				fatalx("bad return value from pass()");
				/* NOTREACHED */
			}
			break;
		case CMD_SOCKET:
			debugmsg("CMD_SOCKET received");

			if (state != POSTAUTH)
				fatalx("CMD_SOCKET received in invalid state");

			recv_data(fd_slave, &domain, sizeof(domain));
			if (domain != AF_INET && domain != AF_INET6)
				fatalx("monitor received invalid addr family");

			s = socket(domain, SOCK_STREAM, 0);
			serrno = errno;

			send_fd(fd_slave, s);
			if (s == -1)
				send_data(fd_slave, &serrno, sizeof(serrno));
			else
				close(s);
			break;
		case CMD_BIND:
			debugmsg("CMD_BIND received");

			if (state != POSTAUTH)
				fatalx("CMD_BIND received in invalid state");

			s = recv_fd(fd_slave);

			recv_data(fd_slave, &salen, sizeof(salen));
			if (salen == 0 || salen > sizeof(sa))
				fatalx("monitor received invalid sockaddr len");

			bzero(&sa, sizeof(sa));
			recv_data(fd_slave, &sa, salen);

			if (sa.su_si.si_len != salen)
				fatalx("monitor received invalid sockaddr len");

			if (sa.su_si.si_family != AF_INET &&
			    sa.su_si.si_family != AF_INET6)
				fatalx("monitor received invalid addr family");

			err = bind(s, (struct sockaddr *)&sa, salen);
			serrno = errno;

			if (s >= 0)
				close(s);

			send_data(fd_slave, &err, sizeof(err));
			if (err == -1)
				send_data(fd_slave, &serrno, sizeof(serrno));
			break;
		default:
			fatalx("monitor received unknown command %d", cmd);
			/* NOTREACHED */
		}
	}
}
int main(void) {
 easy_tramp(test);
 pass();
 return 0;
}
Example #26
0
File: lpsend.c Project: npe9/harvey
void
main(int argc, char *argv[])
{
    int i, rv, netfd, bsize, datafd;
#ifndef plan9
    void (*oldhandler)();
#endif

    /* make connection */
    if (argc != 2) {
        fprint(stderr, "usage: %s network!destination!service\n",
               argv[0]);
        exits("usage");
    }

    /* read options line from stdin into lnbuf */
    i = readline(0);

    /* read stdin into tempfile to get size */
    datafd = tempfile();
    bsize = prereadfile(datafd);

    /* network connection is opened after data is in to avoid timeout */
    if ((netfd = dial(argv[1], 0, 0, 0)) < 0) {
        fprint(stderr, "dialing ");
        perror(argv[1]);
        exits("can't dial");
    }

    /* write out the options we read above */
    if (write(netfd, lnbuf, i) != i) {
        error(0, "write error while sending options\n");
        exits("write error sending options");
    }

    /* send the size of the file to be sent */
    sprint(lnbuf, "%d\n", bsize);
    i = strlen(lnbuf);
    if ((rv=write(netfd, lnbuf, i)) != i) {
        perror("write error while sending size");
        error(0, "write returned %d\n", rv);
        exits("write error sending size");
    }

    if (seek(datafd, 0L, 0) < 0) {
        error(0, "error seeking temp file\n");
        exits("seek error");
    }
    /* mirror performance in readfile() in lpdaemon */

#ifdef plan9
    atnotify(alarmhandler, 1);
#else
    oldhandler = signal(SIGALRM, alarmhandler);
#endif

    dbgstate = 1;
    if(!recvACK(netfd)) {
        error(0, "failed to receive ACK before sending data\n");
        exits("recv ack1 failed");
    }
    dbgstate = 2;
    if ((i=pass(datafd, netfd, bsize)) != 0) {
        NAK(netfd);
        error(0, "failed to send %d bytes\n", i);
        exits("send data failed");
    }
    ACK(netfd);
    dbgstate = 3;
    if(!recvACK(netfd)) {
        error(0, "failed to receive ACK after sending data\n");
        exits("recv ack2 failed");
    }

    /* get response, as from lp -q */
    dbgstate = 4;
    while((rv=read(netfd, jobbuf, RDSIZE)) > 0) {
        if((write(1, jobbuf, rv)) != rv) {
            error(0, "write error while sending to stdout\n");
            exits("write error while sending to stdout");
        }
    }
    dbgstate = 5;

#ifdef plan9
    atnotify(alarmhandler, 0);
    /* close down network connections and go away */
    exits("");
#else
    signal(SIGALRM, oldhandler);
    exit(0);
#endif
}
Example #27
0
int main(int argc, char **argv)
{
	int ret = 0;
	pid_t pid;
	int i;
	uint8_t buf[0x100000];
	int pipes[PROCS_MAX * 2];
	int in, out;

	test_init(argc, argv);

	if (num_procs > PROCS_MAX) {
		pr_err("%d processes is too many: max = %d\n", num_procs, PROCS_MAX);
		exit(1);
	}

	for (i = 0; i < num_procs; i++)
		if (pipe(pipes + i * 2)) {
			pr_perror("Can't create pipes");
			exit(1);
		}

	if (signal(SIGCHLD, inc_num_exited) == SIG_ERR) {
		pr_perror("can't set SIGCHLD handler");
		exit(1);
	}

	for (i = 1; i < num_procs; i++) {	/* i = 0 - parent */
		pid = test_fork();
		if (pid < 0) {
			pr_perror("Can't fork");
			kill(0, SIGKILL);
			exit(1);
		}

		if (pid == 0) {
			int j;
			in = i * 2;
			out = in - 1;
			for (j = 0; j < num_procs * 2; j++)
				if (j != in && j != out)
					close(pipes[j]);

			signal(SIGPIPE, SIG_IGN);
			if (pipe_in2out(pipes[in], pipes[out], buf, sizeof(buf)) < 0)
				/* pass errno as exit code to the parent */
				if (test_go() /* signal NOT delivered */ ||
						(errno != EINTR && errno != EPIPE))
					ret = errno;

			test_waitsig();	/* even if failed, wait for migration to complete */

			close(pipes[in]);
			close(pipes[out]);
			exit(ret);
		}
	}

	for (i = 1; i < num_procs * 2 - 1; i++)
		close(pipes[i]);
	in = pipes[0];
	out = pipes[num_procs * 2 - 1];

	/* don't block on writing, _do_ block on reading */
	if (set_nonblock(out,1) < 0) {
		pr_perror("setting O_NONBLOCK failed");
		exit(1);
	}

	if (num_exited) {
		pr_err("Some children died unexpectedly\n");
		kill(0, SIGKILL);
		exit(1);
	}

	test_daemon();

	while (test_go()) {
		int len, rlen = 0, wlen;
		uint8_t rbuf[sizeof(buf)], *p;

		datagen(buf, sizeof(buf), NULL);
		wlen = write(out, buf, sizeof(buf));
		if (wlen < 0) {
			if (errno == EINTR)
				continue;
			else {
				fail("write failed: %m\n", i);
				ret = 1;
				break;
			}
		}

		for (p = rbuf, len = wlen; len > 0; p += rlen, len -= rlen) {
			rlen = read(in, p, len);
			if (rlen <= 0)
				break;
		}

		if (rlen < 0 && errno == EINTR)
			continue;

		if (len > 0) {
			fail("read failed: %m\n");
			ret = 1;
			break;
		}

		if (memcmp(buf, rbuf, wlen)) {
			fail("data mismatch\n");
			ret = 1;
			break;
		}
	}

	close(out);

	test_waitsig();	/* even if failed, wait for migration to complete */

	if (kill(0, SIGTERM)) {
		fail("failed to send SIGTERM to my process group: %m\n");
		goto out;	/* shouldn't wait() in this case */
	}

	for (i = 1; i < num_procs; i++) {	/* i = 0 - parent */
		int chret;
		if (wait(&chret) < 0) {
			fail("can't wait for a child: %m\n");
			ret = 1;
			continue;
		}

		chret = WEXITSTATUS(chret);
		if (chret) {
			fail("child %d exited with non-zero code %d (%s)\n",
			     i, chret, strerror(chret));
			ret = 1;
			continue;
		}
	}

	if (!ret)
		pass();

out:
	close(in);
	return 0;
}
int main(int argc, char**argv) {
  int err=0;
  err+=test_datamatrix   ("'rand'[4x9]", 4, 9, data_4_9          , 0, 1024, 9e-5);
  return pass();
}
Example #29
0
void admin(){
	struct data{
	char id[10];	
	char pass[16];
	};

	struct data c;
	char m[10] ,n[10],x,ch,pa[10];
	int d=0;	

	FILE *fp,*fm;
	fp=fopen("admin.txt","rb+");
	printf("/**************ADMIN ID=12345   PASS= 00 ******************/\n");
	printf("ENTER ID \n");
	scanf("%s", m);
	printf("ENTER PASS\n");
	pass(n);
	rewind(fp);
	fread(&c,sizeof(struct data), 1, fp);
	while((d==0)){
		
		if((strcmp(c.id,m)==0) && (strcmp(c.pass,n)==0)){
			printf("SUCCESFULLY MATCH\n");
			d=1;
		}
		else {
			printf("1.RE ENTER\n ");
			printf("2.MAINMENU\n");
			scanf(" %c",&x);		
			system("clear");
			switch(x){
				case '1':
					printf("ENTER THE ID \n");
					scanf("%s", m);
					printf("ENTER  PASS\n");
					pass(n);
					break;
				case '2':
					mainmenu();
				}
		}
	}
	if(d){	
		printf("\n");
		printf("	--------1.SHOW BOOK RECORD------	\n");
		printf("	--------2.ADD BOOKS-------------	\n");
		printf("	--------3.CHANGE PASSWAORD------	\n");
		printf("	-------	4.REMOVE BOOKS----------	\n");
		printf("	-------	5.RETURN BOOK-----------	\n");
		printf("	-------	6.STUDENT INFORMATION---	\n");
		printf("	-------	7.ISSUE BOOK RECORD-----	\n");
		printf("	-------	8.MAINMENU--------------	\n");
		scanf(" %c",&ch);
	}
	switch(ch){
		case '1':
			showrcrd();
			break;
		case '2':
			addbooks();
			break;
		case '3':
			achangepass();
			break;
		case '4':
			rmbook();
			break;
		case '5':
			retur();
			break;
		case '6':
			sti();
			break;
		case '7':
			just1();
			break;
		case '8':
			mainmenu();
			break;
		default :
			printf("---------INVALID INPUT----------\n");
			admi();
			break;

		}
	fclose(fp);
}
Example #30
0
int ns_child(void *_arg)
{
	struct ns_exec_args *args = _arg;
	int fd2;
	int id1, id2;
	struct stat st1, st2;
	char lpath[PATH_MAX], fpath[PATH_MAX];

	snprintf(fpath, sizeof(fpath), "%s/1", dirname);
	if (umount(fpath)) {
		pr_perror("umount");
		return 1;
	}

	snprintf(lpath, sizeof(lpath), "%s/0/2", dirname);
	snprintf(fpath, sizeof(fpath), "%s/2", dirname);

	if (mkdir(fpath, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}

	if (mount(lpath, fpath, NULL, MS_BIND, NULL)) {
		pr_perror("mount");
		return 1;
	}

	snprintf(fpath, sizeof(fpath), "%s/0", dirname);
	if (umount(fpath)) {
		pr_perror("umount");
		return 1;
	}

	snprintf(fpath, sizeof(fpath), "%s/2/%s", dirname, MPTS_FILE);
	fd2 = open(fpath, O_RDWR);
	if (fd2 < 0) {
		pr_perror("open");
		return -1;
	}
	close(args->sync);
	test_waitsig();

	id1 = get_mntid(args->fd);
	id2 = get_mntid(fd2);
	if (id1 <0 || id2 < 0)
		exit(1);

	if (fstat(args->fd, &st1) || fstat(fd2, &st2)) {
		pr_perror("stat");
		exit(1);
	}

	test_msg("%d %d", id1, id2);

#ifdef ZDTM_LINK_REMAP
	if (st1.st_nlink != 1) {
#else
	if (st1.st_nlink != 0) {
#endif
		pr_perror("Wrong number of links: %d", st1.st_nlink);
		exit(1);
	}

	if (id1 > 0 && id1 != id2 && st1.st_ino == st2.st_ino)
		exit(AWK_OK);
	else
		exit(AWK_FAIL);
}

int main(int argc, char **argv)
{
	struct ns_exec_args args;
	pid_t pid = -1;
	char lpath[PATH_MAX], fpath[PATH_MAX];
	char buf[256];
	int p[2];

	test_init(argc, argv);

	if (mkdir(dirname, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}

	if (mount("test", dirname, "tmpfs", 0, NULL)) {
		pr_perror("mount");
		return 1;
	}

	snprintf(fpath, sizeof(fpath), "%s/0", dirname);
	if (mkdir(fpath, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}
	if (mount("test", fpath, "tmpfs", 0, NULL)) {
		pr_perror("mount");
		return 1;
	}

	snprintf(lpath, sizeof(lpath), "%s/0/1", dirname);
	if (mkdir(lpath, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}
	snprintf(fpath, sizeof(fpath), "%s/1", dirname);
	if (mkdir(fpath, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}
	if (mount(lpath, fpath, NULL, MS_BIND, NULL)) {
		pr_perror("mount");
		return 1;
	}
	snprintf(lpath, sizeof(lpath), "%s/0/2", dirname);
	if (mkdir(lpath, 0600) < 0) {
		fail("Can't make zdtm_sys");
		return 1;
	}

	if (pipe(p) == -1) {
		pr_perror("pipe");
		return 1;
	}

	if (getenv("ZDTM_NOSUBNS") == NULL) {
		snprintf(fpath, sizeof(fpath), "%s/1/%s", dirname, MPTS_FILE);

		args.fd = open(fpath, O_CREAT | O_RDWR, 0600);
		if (args.fd < 0) {
			fail("Can't open file");
			return 1;
		}
		snprintf(fpath, sizeof(fpath), "%s/0/1/%s", dirname, MPTS_FILE);
		snprintf(lpath, sizeof(fpath), "%s/0/2/%s", dirname, MPTS_FILE);
		if (link(fpath, lpath) == -1) {
			pr_perror("link");
			return -1;
		}
#ifdef ZDTM_LINK_REMAP
		snprintf(lpath, sizeof(fpath), "%s/0/%s", dirname, MPTS_FILE);
		if (link(fpath, lpath) == -1) {
			pr_perror("link");
			return -1;
		}
#endif
		args.sync = p[1];

		pid = clone(ns_child, args.stack_ptr, CLONE_NEWNS | SIGCHLD, &args);
		if (pid < 0) {
			pr_perror("Unable to fork child");
			return 1;
		}

		close(args.fd);
	}

	close(p[1]);
	read(p[0], buf, sizeof(buf));

	snprintf(fpath, sizeof(fpath), "%s/0/1/%s", dirname, MPTS_FILE);
	if (unlink(fpath))
		return 1;
	snprintf(fpath, sizeof(fpath), "%s/0/2/%s", dirname, MPTS_FILE);
	if (unlink(fpath))
		return 1;

	test_daemon();
	test_waitsig();


	if (pid > 0) {
		kill(pid, SIGTERM);
		int status = 1;
		wait(&status);
		if (WIFEXITED(status)) {
			if (WEXITSTATUS(status) == AWK_OK)
				pass();
			else if (WEXITSTATUS(status) == AWK_FAIL)
				fail("Mount ID not restored");
			else
				fail("Failed to check mount IDs (%d)", WEXITSTATUS(status));
		} else
			fail("Test died");
	}

	umount2(dirname, MNT_DETACH);
	rmdir(dirname);
	return 0;
}