예제 #1
0
static void
print_mul_op(uint64_t inst)
{
        uint32_t op_add = QPU_GET_FIELD(inst, QPU_OP_ADD);
        uint32_t op_mul = QPU_GET_FIELD(inst, QPU_OP_MUL);
        uint32_t cond = QPU_GET_FIELD(inst, QPU_COND_MUL);
        bool is_mov = (op_mul == QPU_M_V8MIN &&
                       QPU_GET_FIELD(inst, QPU_MUL_A) ==
                       QPU_GET_FIELD(inst, QPU_MUL_B));

        if (is_mov)
                fprintf(stderr, "mov");
        else
                fprintf(stderr, "%s", DESC(qpu_mul_opcodes, op_mul));

        if ((inst & QPU_SF) && op_add == QPU_A_NOP)
                fprintf(stderr, ".sf");

        if (op_mul != QPU_M_NOP)
                vc4_qpu_disasm_cond(stderr, cond);

        fprintf(stderr, " ");
        print_alu_dst(inst, true);
        fprintf(stderr, ", ");

        print_alu_src(inst, QPU_GET_FIELD(inst, QPU_MUL_A), true);

        if (!is_mov) {
                fprintf(stderr, ", ");
                print_alu_src(inst, QPU_GET_FIELD(inst, QPU_MUL_B), true);
        }
}
예제 #2
0
static void
print_add_op(uint64_t inst)
{
        uint32_t op_add = QPU_GET_FIELD(inst, QPU_OP_ADD);
        uint32_t cond = QPU_GET_FIELD(inst, QPU_COND_ADD);
        bool is_mov = (op_add == QPU_A_OR &&
                       QPU_GET_FIELD(inst, QPU_ADD_A) ==
                       QPU_GET_FIELD(inst, QPU_ADD_B));

        if (is_mov)
                fprintf(stderr, "mov");
        else
                fprintf(stderr, "%s", DESC(qpu_add_opcodes, op_add));

        if ((inst & QPU_SF) && op_add != QPU_A_NOP)
                fprintf(stderr, ".sf");

        if (op_add != QPU_A_NOP)
                vc4_qpu_disasm_cond(stderr, cond);

        fprintf(stderr, " ");
        print_alu_dst(inst, false);
        fprintf(stderr, ", ");

        print_alu_src(inst, QPU_GET_FIELD(inst, QPU_ADD_A), false);

        if (!is_mov) {
                fprintf(stderr, ", ");

                print_alu_src(inst, QPU_GET_FIELD(inst, QPU_ADD_B), false);
        }
}
예제 #3
0
void
vc4_qpu_disasm(const uint64_t *instructions, int num_instructions)
{
        for (int i = 0; i < num_instructions; i++) {
                uint64_t inst = instructions[i];
                uint32_t sig = QPU_GET_FIELD(inst, QPU_SIG);

                switch (sig) {
                case QPU_SIG_BRANCH:
                        fprintf(stderr, "branch");
                        break;
                case QPU_SIG_LOAD_IMM:
                        print_load_imm(inst);
                        break;
                default:
                        if (sig != QPU_SIG_NONE)
                                fprintf(stderr, "%s ", DESC(qpu_sig, sig));
                        print_add_op(inst);
                        fprintf(stderr, " ; ");
                        print_mul_op(inst);
                        break;
                }

                if (num_instructions != 1)
                        fprintf(stderr, "\n");
        }
}
예제 #4
0
static void
print_load_imm(uint64_t inst)
{
        uint32_t imm = inst;
        uint32_t waddr_add = QPU_GET_FIELD(inst, QPU_WADDR_ADD);
        uint32_t waddr_mul = QPU_GET_FIELD(inst, QPU_WADDR_MUL);
        uint32_t cond_add = QPU_GET_FIELD(inst, QPU_COND_ADD);
        uint32_t cond_mul = QPU_GET_FIELD(inst, QPU_COND_MUL);

        fprintf(stderr, "load_imm ");
        print_alu_dst(inst, false);
        fprintf(stderr, "%s, ", (waddr_add != QPU_W_NOP ?
                                 DESC(qpu_condflags, cond_add) : ""));
        print_alu_dst(inst, true);
        fprintf(stderr, "%s, ", (waddr_mul != QPU_W_NOP ?
                                 DESC(qpu_condflags, cond_mul) : ""));
        fprintf(stderr, "0x%08x (%f)", imm, uif(imm));
}
예제 #5
0
static void
print_alu_src(uint64_t inst, uint32_t mux, bool is_mul)
{
        bool is_a = mux != QPU_MUX_B;
        const char *file = is_a ? "a" : "b";
        uint32_t raddr = (is_a ?
                          QPU_GET_FIELD(inst, QPU_RADDR_A) :
                          QPU_GET_FIELD(inst, QPU_RADDR_B));
        uint32_t unpack = QPU_GET_FIELD(inst, QPU_UNPACK);
        bool has_si = QPU_GET_FIELD(inst, QPU_SIG) == QPU_SIG_SMALL_IMM;
        uint32_t si = QPU_GET_FIELD(inst, QPU_SMALL_IMM);

        if (mux <= QPU_MUX_R5) {
                fprintf(stderr, "r%d", mux);
                if (has_si && is_mul && si >= QPU_SMALL_IMM_MUL_ROT + 1)
                        fprintf(stderr, "+%d", si - QPU_SMALL_IMM_MUL_ROT);
        } else if (!is_a && has_si) {
                if (si <= 15)
                        fprintf(stderr, "%d", si);
                else if (si <= 31)
                        fprintf(stderr, "%d", -16 + (si - 16));
                else if (si <= 39)
                        fprintf(stderr, "%.1f", (float)(1 << (si - 32)));
                else if (si <= 47)
                        fprintf(stderr, "%f", 1.0f / (1 << (48 - si)));
                else
                        fprintf(stderr, "<bad imm %d>", si);
        } else if (raddr <= 31)
                fprintf(stderr, "r%s%d", file, raddr);
        else {
                if (is_a)
                        fprintf(stderr, "%s", DESC(special_read_a, raddr - 32));
                else
                        fprintf(stderr, "%s", DESC(special_read_b, raddr - 32));
        }

        if (((mux == QPU_MUX_A && !(inst & QPU_PM)) ||
             (mux == QPU_MUX_R4 && (inst & QPU_PM)))) {
                vc4_qpu_disasm_unpack(stderr, unpack);
        }
}
static void
print_alu_src(uint64_t inst, uint32_t mux)
{
        bool is_a = mux != QPU_MUX_B;
        const char *file = is_a ? "a" : "b";
        uint32_t raddr = (is_a ?
                          QPU_GET_FIELD(inst, QPU_RADDR_A) :
                          QPU_GET_FIELD(inst, QPU_RADDR_B));
        uint32_t unpack = QPU_GET_FIELD(inst, QPU_UNPACK);

        if (mux <= QPU_MUX_R5)
                fprintf(stderr, "r%d", mux);
        else if (!is_a &&
                 QPU_GET_FIELD(inst, QPU_SIG) == QPU_SIG_SMALL_IMM) {
                uint32_t si = QPU_GET_FIELD(inst, QPU_SMALL_IMM);
                if (si <= 15)
                        fprintf(stderr, "%d", si);
                else if (si <= 31)
                        fprintf(stderr, "%d", -16 + (si - 16));
                else if (si <= 39)
                        fprintf(stderr, "%.1f", (float)(1 << (si - 32)));
                else if (si <= 47)
                        fprintf(stderr, "%f", 1.0f / (256 / (si - 39)));
                else
                        fprintf(stderr, "???");
        } else if (raddr <= 31)
                fprintf(stderr, "r%s%d", file, raddr);
        else {
                if (is_a)
                        fprintf(stderr, "%s", DESC(special_read_a, raddr - 32));
                else
                        fprintf(stderr, "%s", DESC(special_read_b, raddr - 32));
        }

        if (unpack != QPU_UNPACK_NOP &&
            ((mux == QPU_MUX_A && !(inst & QPU_PM)) ||
             (mux == QPU_MUX_R4 && (inst & QPU_PM)))) {
                fprintf(stderr, ".%s", DESC(qpu_unpack, unpack));
        }
}
static void
print_alu_dst(uint64_t inst, bool is_mul)
{
        bool is_a = is_mul == ((inst & QPU_WS) != 0);
        uint32_t waddr = (is_mul ?
                          QPU_GET_FIELD(inst, QPU_WADDR_MUL) :
                          QPU_GET_FIELD(inst, QPU_WADDR_ADD));
        const char *file = is_a ? "a" : "b";
        uint32_t pack = QPU_GET_FIELD(inst, QPU_PACK);

        if (waddr <= 31)
                fprintf(stderr, "r%s%d", file, waddr);
        else if (get_special_write_desc(waddr, is_a))
                fprintf(stderr, "%s", get_special_write_desc(waddr, is_a));
        else
                fprintf(stderr, "%s%d?", file, waddr);

        if (is_mul && (inst & QPU_PM)) {
                fprintf(stderr, ".%s", DESC(qpu_pack_mul, pack));
        } else if (is_a && !(inst & QPU_PM)) {
                fprintf(stderr, "%s", DESC(qpu_pack_a, pack));
        }
}
예제 #8
0
파일: ntpdc.c 프로젝트: pexip/os-ntp
/*
 * main - parse arguments and handle options
 */
int
ntpdcmain(
	int argc,
	char *argv[]
	)
{
	extern int ntp_optind;

	delay_time.l_ui = 0;
	delay_time.l_uf = DEFDELAY;

#ifdef SYS_VXWORKS
	clear_globals();
	taskPrioritySet(taskIdSelf(), 100 );
#endif

	init_lib();	/* sets up ipv4_works, ipv6_works */
	ssl_applink();

	/* Check to see if we have IPv6. Otherwise default to IPv4 */
	if (!ipv6_works)
		ai_fam_default = AF_INET;

	progname = argv[0];

	{
		int optct = ntpOptionProcess(&ntpdcOptions, argc, argv);
		argc -= optct;
		argv += optct;
	}

	if (HAVE_OPT(IPV4))
		ai_fam_templ = AF_INET;
	else if (HAVE_OPT(IPV6))
		ai_fam_templ = AF_INET6;
	else
		ai_fam_templ = ai_fam_default;

	if (HAVE_OPT(COMMAND)) {
		int		cmdct = STACKCT_OPT( COMMAND );
		const char**	cmds  = STACKLST_OPT( COMMAND );

		while (cmdct-- > 0) {
			ADDCMD(*cmds++);
		}
	}

	debug = DESC(DEBUG_LEVEL).optOccCt;

	if (HAVE_OPT(INTERACTIVE)) {
		interactive = 1;
	}

	if (HAVE_OPT(NUMERIC)) {
		showhostnames = 0;
	}

	if (HAVE_OPT(LISTPEERS)) {
		ADDCMD("listpeers");
	}

	if (HAVE_OPT(PEERS)) {
		ADDCMD("peers");
	}

	if (HAVE_OPT(SHOWPEERS)) {
		ADDCMD("dmpeers");
	}

	if (ntp_optind == argc) {
		ADDHOST(DEFHOST);
	} else {
		for (; ntp_optind < argc; ntp_optind++)
		    ADDHOST(argv[ntp_optind]);
	}

	if (numcmds == 0 && interactive == 0
	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
		interactive = 1;
	}

#if 0
	ai_fam_templ = ai_fam_default;
	while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF)
	    switch (c) {
		case '4':
		    ai_fam_templ = AF_INET;
		    break;
		case '6':
		    ai_fam_templ = AF_INET6;
		    break;
		case 'c':
		    ADDCMD(ntp_optarg);
		    break;
		case 'd':
		    ++debug;
		    break;
		case 'i':
		    interactive = 1;
		    break;
		case 'l':
		    ADDCMD("listpeers");
		    break;
		case 'n':
		    showhostnames = 0;
		    break;
		case 'p':
		    ADDCMD("peers");
		    break;
		case 's':
		    ADDCMD("dmpeers");
		    break;
		default:
		    errflg++;
		    break;
	    }

	if (errflg) {
		(void) fprintf(stderr,
			       "usage: %s [-46dilnps] [-c cmd] host ...\n",
			       progname);
		exit(2);
	}

	if (ntp_optind == argc) {
		ADDHOST(DEFHOST);
	} else {
		for (; ntp_optind < argc; ntp_optind++)
		    ADDHOST(argv[ntp_optind]);
	}

	if (numcmds == 0 && interactive == 0
	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
		interactive = 1;
	}
#endif

#ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
	if (interactive)
	    (void) signal_no_reset(SIGINT, abortcmd);
#endif /* SYS_WINNT */

	/*
	 * Initialize the packet data buffer
	 */
	pktdatasize = INITDATASIZE;
	pktdata = emalloc(INITDATASIZE);

	if (numcmds == 0) {
		(void) openhost(chosts[0]);
		getcmds();
	} else {
		int ihost;
		int icmd;

		for (ihost = 0; ihost < numhosts; ihost++) {
			if (openhost(chosts[ihost]))
			    for (icmd = 0; icmd < numcmds; icmd++) {
				    if (numhosts > 1) 
					printf ("--- %s ---\n",chosts[ihost]);
				    docmd(ccmds[icmd]);
			    }
		}
	}
#ifdef SYS_WINNT
	WSACleanup();
#endif
	return(0);
} /* main end */
예제 #9
0
void
vc4_qpu_disasm_cond_branch(FILE *out, uint32_t cond)
{
        fprintf(out, "%s", DESC(qpu_cond_branch, cond));
}
예제 #10
0
void
vc4_qpu_disasm_unpack(FILE *out, uint32_t unpack)
{
        if (unpack != QPU_UNPACK_NOP)
                fprintf(out, ".%s", DESC(qpu_unpack, unpack));
}
예제 #11
0
void
vc4_qpu_disasm_pack_a(FILE *out, uint32_t pack)
{
        fprintf(out, "%s", DESC(qpu_pack_a, pack));
}
예제 #12
0
/*
 * Main program.  Initialize us, disconnect us from the tty if necessary,
 * and loop waiting for I/O and/or timer expiries.
 */
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp now;
	struct recvbuf *rbuf;
#ifdef _AIX			/* HMS: ifdef SIGDANGER? */
	struct sigaction sa;
#endif

	progname = argv[0];
	initializing = 1;		/* mark that we are initializing */
	process_commandline_opts(&argc, &argv);
	init_logging(progname, 1);	/* Open the log file */

	char *error = NULL;
	if (sandbox_init("ntpd", SANDBOX_NAMED, &error) == -1) {
		msyslog(LOG_ERR, "sandbox_init(ntpd, SANDBOX_NAMED) failed: %s", error);
		sandbox_free_error(error);
	}
#ifdef HAVE_UMASK
	{
		mode_t uv;

		uv = umask(0);
		if(uv)
			(void) umask(uv);
		else
			(void) umask(022);
	}
#endif

#if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	{
		uid_t uid;

		uid = getuid();
		if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
			msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid);
			printf("must be run as root, not uid %ld\n", (long)uid);
			exit(1);
		}
	}
#endif

	/* getstartup(argc, argv); / * startup configuration, may set debug */

#ifdef DEBUG
	debug = DESC(DEBUG_LEVEL).optOccCt;
	DPRINTF(1, ("%s\n", Version));
#endif

	/* honor -l/--logfile option to log to a file */
	setup_logfile();

/*
 * Enable the Multi-Media Timer for Windows?
 */
#ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
#endif

	if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT )
#ifdef DEBUG
	    || debug
#endif
	    || HAVE_OPT( SAVECONFIGQUIT ))
		nofork = 1;

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int	ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		isc_netaddr_t	netaddr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, &netaddr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

#if defined(HAVE_SCHED_SETSCHEDULER)
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
#endif

#ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
#endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

#if !defined(VMS)
# ifndef NODETACH
	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

		/*
		 * Install trap handlers to log errors and assertion
		 * failures.  Default handlers print to stderr which 
		 * doesn't work if detached.
		 */
		isc_assertion_setcallback(assertion_failed);
		isc_error_setfatal(library_fatal_error);
		isc_error_setunexpected(library_unexpected_error);

#  ifndef SYS_WINNT
#   ifdef HAVE_DAEMON
		daemon(0, 0);
#   else /* not HAVE_DAEMON */
		if (fork())	/* HMS: What about a -1? */
			exit(0);

		{
#if !defined(F_CLOSEM)
			u_long s;
			int max_fd;
#endif /* !FCLOSEM */
			if (syslog_file != NULL) {
				fclose(syslog_file);
				syslog_file = NULL;
			}
#if defined(F_CLOSEM)
			/*
			 * From 'Writing Reliable AIX Daemons,' SG24-4946-00,
			 * by Eric Agar (saves us from doing 32767 system
			 * calls)
			 */
			if (fcntl(0, F_CLOSEM, 0) == -1)
			    msyslog(LOG_ERR, "ntpd: failed to close open files(): %m");
#else  /* not F_CLOSEM */

# if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
			max_fd = sysconf(_SC_OPEN_MAX);
# else /* HAVE_SYSCONF && _SC_OPEN_MAX */
			max_fd = getdtablesize();
# endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
			for (s = 0; s < max_fd; s++)
				(void) close((int)s);
#endif /* not F_CLOSEM */
			(void) open("/", 0);
			(void) dup2(0, 1);
			(void) dup2(0, 2);

			init_logging(progname, 0);
			/* we lost our logfile (if any) daemonizing */
			setup_logfile();

#ifdef SYS_DOMAINOS
			{
				uid_$t puid;
				status_$t st;

				proc2_$who_am_i(&puid);
				proc2_$make_server(&puid, &st);
			}
#endif /* SYS_DOMAINOS */
#if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
# ifdef HAVE_SETSID
			if (setsid() == (pid_t)-1)
				msyslog(LOG_ERR, "ntpd: setsid(): %m");
# else
			if (setpgid(0, 0) == -1)
				msyslog(LOG_ERR, "ntpd: setpgid(): %m");
# endif
#else /* HAVE_SETPGID || HAVE_SETSID */
			{
# if defined(TIOCNOTTY)
				int fid;

				fid = open("/dev/tty", 2);
				if (fid >= 0)
				{
					(void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
					(void) close(fid);
				}
# endif /* defined(TIOCNOTTY) */
# ifdef HAVE_SETPGRP_0
				(void) setpgrp();
# else /* HAVE_SETPGRP_0 */
				(void) setpgrp(0, getpid());
# endif /* HAVE_SETPGRP_0 */
			}
#endif /* HAVE_SETPGID || HAVE_SETSID */
#ifdef _AIX
			/* Don't get killed by low-on-memory signal. */
			sa.sa_handler = catch_danger;
			sigemptyset(&sa.sa_mask);
			sa.sa_flags = SA_RESTART;

			(void) sigaction(SIGDANGER, &sa, NULL);
#endif /* _AIX */
		}
#   endif /* not HAVE_DAEMON */
#  endif /* SYS_WINNT */
	}
# endif /* NODETACH */
#endif /* VMS */

#ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	{
	    int fd = open("/dev/at1", O_RDONLY);
	    if (fd >= 0) {
		int zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
		    msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close( fd );
	    } /* else ...
	       *   If we can't open the device, this probably just isn't
	       *   a multiprocessor system, so we're A-OK.
	       */
	}
#endif

#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE)
# ifdef HAVE_SETRLIMIT
	/*
	 * Set the stack limit to something smaller, so that we don't lock a lot
	 * of unused stack memory.
	 */
	{
	    struct rlimit rl;

	    /* HMS: must make the rlim_cur amount configurable */
	    if (getrlimit(RLIMIT_STACK, &rl) != -1
		&& (rl.rlim_cur = 50 * 4096) < rl.rlim_max)
	    {
		    if (setrlimit(RLIMIT_STACK, &rl) == -1)
		    {
			    msyslog(LOG_ERR,
				"Cannot adjust stack limit for mlockall: %m");
		    }
	    }
#  ifdef RLIMIT_MEMLOCK
	    /*
	     * The default RLIMIT_MEMLOCK is very low on Linux systems.
	     * Unless we increase this limit malloc calls are likely to
	     * fail if we drop root privlege.  To be useful the value
	     * has to be larger than the largest ntpd resident set size.
	     */
	    rl.rlim_cur = rl.rlim_max = 32*1024*1024;
	    if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) {
		msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m");
	    }
#  endif /* RLIMIT_MEMLOCK */
	}
# endif /* HAVE_SETRLIMIT */
	/*
	 * lock the process into memory
	 */
	if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0)
		msyslog(LOG_ERR, "mlockall(): %m");
#else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */
# ifdef HAVE_PLOCK
#  ifdef PROCLOCK
#   ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8*4096)) < 0)
	{
		msyslog(LOG_ERR,"Cannot adjust stack limit for plock on AIX: %m");
	}
#   endif /* _AIX */
	/*
	 * lock the process into memory
	 */
	if (plock(PROCLOCK) < 0)
		msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#  else /* not PROCLOCK */
#   ifdef TXTLOCK
	/*
	 * Lock text into ram
	 */
	if (plock(TXTLOCK) < 0)
		msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#   else /* not TXTLOCK */
	msyslog(LOG_ERR, "plock() - don't know what to lock!");
#   endif /* not TXTLOCK */
#  endif /* not PROCLOCK */
# endif /* HAVE_PLOCK */
#endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */

	/*
	 * Set up signals we pay attention to locally.
	 */
#ifdef SIGDIE1
	(void) signal_no_reset(SIGDIE1, finish);
#endif	/* SIGDIE1 */
#ifdef SIGDIE2
	(void) signal_no_reset(SIGDIE2, finish);
#endif	/* SIGDIE2 */
#ifdef SIGDIE3
	(void) signal_no_reset(SIGDIE3, finish);
#endif	/* SIGDIE3 */
#ifdef SIGDIE4
	(void) signal_no_reset(SIGDIE4, finish);
#endif	/* SIGDIE4 */

#ifdef SIGBUS
	(void) signal_no_reset(SIGBUS, finish);
#endif /* SIGBUS */

#if !defined(SYS_WINNT) && !defined(VMS)
# ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
# else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
# endif /* DEBUG */
#endif /* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
#if defined SIGPIPE
	(void) signal_no_reset(SIGPIPE, SIG_IGN);
#endif	/* SIGPIPE */

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_lib();
	init_request();
	init_control();
	init_peer();
#ifdef REFCLOCK
	init_refclock();
#endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);
	NLOG(NLOG_SYSINFO) /* 'if' clause for syslog */
	msyslog(LOG_NOTICE, "%s", Version);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	loop_config(LOOP_DRIFTCOMP, old_drift);
	initializing = 0;

#ifdef HAVE_DROPROOT
	if( droproot ) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#endif /* HAVE_LINUX_CAPABILITIES */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					user = strdup(pw->pw_name);
					if (NULL == user) {
						msyslog(LOG_ERR, "strdup() failed: %m");
						exit (-1);
					}
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
					    msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
					    msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#ifndef HAVE_LINUX_CAPABILITIES
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#endif

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking");
		}

#ifdef HAVE_LINUX_CAPABILITIES
		do {
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext = (interface_interval)
				? "cap_sys_time,cap_net_bind_service=ipe"
				: "cap_sys_time=ipe";
			if( ! ( caps = cap_from_text( captext ) ) ) {
				msyslog( LOG_ERR, "cap_from_text() failed: %m" );
				exit(-1);
			}
			if( cap_set_proc( caps ) == -1 ) {
				msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" );
				exit(-1);
			}
			cap_free( caps );
		} while(0);
#endif /* HAVE_LINUX_CAPABILITIES */

	}    /* if( droproot ) */
#endif /* HAVE_DROPROOT */

	/*
	 * Use select() on all on all input fd's for unlimited
	 * time.  select() will terminate on SIGALARM or on the
	 * reception of input.	Using select() means we can't do
	 * robust signal handling and we get a potential race
	 * between checking for alarms and doing the select().
	 * Mostly harmless, I think.
	 */
	/* On VMS, I suspect that select() can't be interrupted
	 * by a "signal" either, so I take the easy way out and
	 * have select() time out after one second.
	 * System clock updates really aren't time-critical,
	 * and - lacking a hardware reference clock - I have
	 * yet to learn about anything else that is.
	 */
#if defined(HAVE_IO_COMPLETION_PORT)

	for (;;) {
		GetReceivedBuffers();
#else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = 0;
	for (;;)
	{
# if !defined(HAVE_SIGNALED_IO)
		extern fd_set activefds;
		extern int maxactivefd;

		fd_set rdfdes;
		int nfound;
# endif

		if (alarm_flag)		/* alarmed? */
		{
			was_alarmed = 1;
			alarm_flag = 0;
		}

		if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE)
		{
			/*
			 * Nothing to do.  Wait for something.
			 */
# ifndef HAVE_SIGNALED_IO
			rdfdes = activefds;
#  if defined(VMS) || defined(SYS_VXWORKS)
			/* make select() wake up after one second */
			{
				struct timeval t1;

				t1.tv_sec = 1; t1.tv_usec = 0;
				nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
						(fd_set *)0, &t1);
			}
#  else
			nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
					(fd_set *)0, (struct timeval *)0);
#  endif /* VMS */
			if (nfound > 0)
			{
				l_fp ts;

				get_systime(&ts);

				(void)input_handler(&ts);
			}
			else if (nfound == -1 && errno != EINTR)
				msyslog(LOG_ERR, "select() error: %m");
#  ifdef DEBUG
			else if (debug > 5)
				msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
#  endif /* DEBUG */
# else /* HAVE_SIGNALED_IO */

			wait_for_signal();
# endif /* HAVE_SIGNALED_IO */
			if (alarm_flag)		/* alarmed? */
			{
				was_alarmed = 1;
				alarm_flag = 0;
			}
		}

		if (was_alarmed)
		{
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = 0;
			BLOCK_IO_AND_ALARM();
		}

#endif /* ! HAVE_IO_COMPLETION_PORT */

#ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
#endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL)
			{
				if (alarm_flag)
				{
					was_alarmed = 1;
					alarm_flag = 0;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed)
				{	/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = 0;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL)	/* This should always be true */
				{
#ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
#endif
					(rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "receive buffer corruption - receiver found to be NULL - ABORTING");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
#ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
#endif

		/*
		 * Go around again
		 */

#ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attemping to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = 0;
			}
		}
#endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}


#ifdef SIGDIE2
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig);
#ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
#endif
	switch (sig) {
# ifdef SIGBUS
	case SIGBUS:
		printf("\nfinish(SIGBUS)\n");
		exit(0);
# endif
	case 0:			/* Should never happen... */
		return;

	default:
		exit(0);
	}
}
예제 #13
0
파일: herr.c 프로젝트: tws67/bayonne-cygwin
RETCODE SQL_API
SQLGetDiagField_Internal (
  SQLSMALLINT		  nHandleType,
  SQLHANDLE		  Handle,
  SQLSMALLINT		  nRecNumber,
  SQLSMALLINT		  nDiagIdentifier,
  SQLPOINTER		  pDiagInfoPtr,
  SQLSMALLINT		  nBufferLength,
  SQLSMALLINT		* pnStringLengthPtr,
  SQLCHAR		  waMode)
{
  GENV (genv, Handle);
  CONN (con, Handle);
  STMT (stmt, Handle);
  DESC (desc, Handle);
  HERR err;
  HPROC hproc = SQL_NULL_HPROC;
  RETCODE retcode = SQL_SUCCESS;
  SQLHANDLE dhandle = SQL_NULL_HANDLE;
  SWORD unicode_driver = 0;
  void *_DiagInfoPtr = NULL;
  void *diagInfoPtr = pDiagInfoPtr;


  switch (nHandleType)
    {
    case SQL_HANDLE_ENV:
      if (!IS_VALID_HENV (Handle))
	{
	  return SQL_INVALID_HANDLE;
	}
      err = genv->herr;
      con = NULL;
      stmt = NULL;
      desc = NULL;
      break;

    case SQL_HANDLE_DBC:
      if (!IS_VALID_HDBC (Handle))
	{
	  return SQL_INVALID_HANDLE;
	}
      err = con->herr;
      genv = (GENV_t *) con->genv;
      stmt = NULL;
      desc = NULL;
      dhandle = con->dhdbc;
      break;

    case SQL_HANDLE_STMT:
      if (!IS_VALID_HSTMT (Handle))
	{
	  return SQL_INVALID_HANDLE;
	}
      err = stmt->herr;
      con = (DBC_t *) stmt->hdbc;
      genv = (GENV_t *) con->genv;
      desc = NULL;
      dhandle = stmt->dhstmt;
      break;

    case SQL_HANDLE_DESC:
      if (!IS_VALID_HDESC (Handle))
	{
	  return SQL_INVALID_HANDLE;
	}
      err = desc->herr;
      stmt = (STMT_t *) desc->hstmt;
      con = (DBC_t *) desc->hdbc;
      genv = (GENV_t *) con->genv;
      dhandle = desc->dhdesc;
      break;

    default:
      return SQL_INVALID_HANDLE;
    }

  if (con != NULL && con->henv != SQL_NULL_HENV)
    unicode_driver = ((ENV_t *) con->henv)->unicode_driver;

  switch (nRecNumber)
    {

    case 0:			/* Header record */
      switch (nDiagIdentifier)
	{
	case SQL_DIAG_ROW_COUNT:
	  {
	    if (nHandleType != SQL_HANDLE_STMT || !stmt)
	      {
		return SQL_ERROR;
	      }

	    if (stmt->state != en_stmt_executed_with_info &&
	    	stmt->state != en_stmt_executed &&
		stmt->state != en_stmt_cursoropen)
	      {
		return SQL_ERROR;
	      }
	    if (!con)
	      {
		return SQL_INVALID_HANDLE;
	      }

            CALL_UDRIVER(con, stmt, retcode, hproc, unicode_driver, en_GetDiagField,
              (SQL_HANDLE_DBC, stmt->dhstmt, nRecNumber, nDiagIdentifier, 
               pDiagInfoPtr, nBufferLength, pnStringLengthPtr ));
            if (hproc == SQL_NULL_HPROC)
              {
		if (!con)
		  {
		    return SQL_INVALID_HANDLE;
		  }
		hproc = _iodbcdm_getproc (con, en_RowCount);
		if (!hproc)
		  {
		    return SQL_ERROR;
		  }
		CALL_DRIVER (stmt->hdbc, stmt, retcode, hproc,
		    (stmt->dhstmt, pDiagInfoPtr));
              }
	    return retcode;
	  }

	case SQL_DIAG_CURSOR_ROW_COUNT:
	case SQL_DIAG_DYNAMIC_FUNCTION:
	case SQL_DIAG_DYNAMIC_FUNCTION_CODE:

	  {
	    if (nHandleType != SQL_HANDLE_STMT || !stmt)
	      {
		return SQL_ERROR;
	      }

	    if (stmt->state != en_stmt_executed_with_info &&
	    	stmt->state != en_stmt_executed &&
		stmt->state != en_stmt_cursoropen)
	      {
		return SQL_ERROR;
	      }
	    if (!con)
	      {
		return SQL_INVALID_HANDLE;
	      }

            CALL_UDRIVER(con, stmt, retcode, hproc, unicode_driver, en_GetDiagField,
              (SQL_HANDLE_DBC, stmt->dhstmt, nRecNumber, nDiagIdentifier, 
               pDiagInfoPtr, nBufferLength, pnStringLengthPtr ));
            if (hproc == SQL_NULL_HPROC)
              return SQL_ERROR;
            else
	      return retcode;
	  }

	case SQL_DIAG_RETURNCODE:

	  if (pDiagInfoPtr)
	    *((SQLRETURN *) pDiagInfoPtr) = ((GENV_t *) Handle)->rc;
	  {
	    return SQL_SUCCESS;
	  }

	case SQL_DIAG_NUMBER:

	  if (pDiagInfoPtr)
	    {
	      (*(SQLINTEGER *) pDiagInfoPtr) = 0;
	      /* get the number from the driver */
	      if (con)
		{
                  CALL_UDRIVER(con, Handle, retcode, hproc, unicode_driver, en_GetDiagField,
                    (nHandleType, dhandle, 0, nDiagIdentifier, 
                     pDiagInfoPtr, nBufferLength, pnStringLengthPtr ));
                  if (hproc != SQL_NULL_HPROC)
                    {
		      if (retcode != SQL_SUCCESS)
			{
			  return retcode;
			}

		      /* and add the DM's value */
		      (*(SQLINTEGER *) pDiagInfoPtr) += error_rec_count (err);
                    }
		  else if (((ENV_t *) con->henv)->dodbc_ver == SQL_OV_ODBC2 &&
		      ((GENV_t *) Handle)->rc)
		    {		/* ODBC2 drivers can only have one error */
		      (*(SQLINTEGER *) pDiagInfoPtr) = 1;
		    }
		}
	      else if (genv)
		{
		  (*(SQLINTEGER *) pDiagInfoPtr) = error_rec_count (err);
		}

	    }
	  break;

	default:
	  return SQL_ERROR;
	}
      break;

    default:			/* status records */
      {
	int nRecs = 0;

	if (nRecNumber < 1)
	  {
	    return SQL_ERROR;
	  }
	nRecs = error_rec_count (err);
	if (nRecNumber <= nRecs)
	  {			/* DM Errors */
	    char *szval = "";
	    int ival = 0;
	    int isInt = 0;
	    sqlerr_t *rec = NULL;

	    rec = get_nth_error (err, nRecNumber - 1);

	    if (!rec)
	      {
		return (SQL_NO_DATA_FOUND);
	      }

	    switch (nDiagIdentifier)
	      {

	      case SQL_DIAG_SUBCLASS_ORIGIN:
	      case SQL_DIAG_CLASS_ORIGIN:
		isInt = 0;

		szval = (rec->code >= en_HY001
		    && rec->code <= en_IM014) ? (char *) "ODBC 3.0" : (char *) "ISO 9075";
		break;

	      case SQL_DIAG_COLUMN_NUMBER:

		if (nHandleType != SQL_HANDLE_STMT || !stmt)
		  {
		    return SQL_ERROR;
		  }
		if (!con)
		  {
		    return SQL_INVALID_HANDLE;
		  }

		if (pDiagInfoPtr)
		  *((SQLINTEGER *) pDiagInfoPtr) = SQL_COLUMN_NUMBER_UNKNOWN;

		return SQL_SUCCESS;

	      case SQL_DIAG_CONNECTION_NAME:
	      case SQL_DIAG_SERVER_NAME:

		isInt = 0;
		if (con)
		  {
		    if (waMode != 'W')
		       retcode = SQLGetInfo (con, SQL_DATA_SOURCE_NAME, 
		          pDiagInfoPtr,	nBufferLength, pnStringLengthPtr);
		    else
		       retcode = SQLGetInfoW (con, SQL_DATA_SOURCE_NAME, 
		          pDiagInfoPtr,	nBufferLength, pnStringLengthPtr);

		    return retcode;
		  }
		else
		  break;

	      case SQL_DIAG_MESSAGE_TEXT:

		isInt = 0;
		szval =
		    _iodbcdm_getsqlerrmsg (rec, (void *) sqlerrmsg_tab);
		break;

	      case SQL_DIAG_NATIVE:

		isInt = 1;
		ival = 0;
		break;

	      case SQL_DIAG_ROW_NUMBER:

		isInt = 1;
		if (nHandleType != SQL_HANDLE_STMT || !stmt)
		  {
		    return SQL_ERROR;
		  }
		if (!con)
		  {
		    return SQL_INVALID_HANDLE;
		  }
                CALL_UDRIVER(con, Handle, retcode, hproc, unicode_driver, en_GetDiagField,
                  (nHandleType, dhandle, nRecNumber, nDiagIdentifier, 
                   pDiagInfoPtr, nBufferLength, pnStringLengthPtr ));
               if (hproc != SQL_NULL_HPROC)
                 {
		    return retcode;
                 }
               else
                 {
		    ival = SQL_ROW_NUMBER_UNKNOWN;
		    break;
                 }

	      case SQL_DIAG_SQLSTATE:

		isInt = 0;
		szval = _iodbcdm_getsqlstate (rec, (void *) sqlerrmsg_tab);
		break;

	      default:
		return SQL_ERROR;
	      }
	    if (isInt)
	      {
		if (pDiagInfoPtr)
		  *((SQLINTEGER *) pDiagInfoPtr) = ival;
	      }
	    else
	      {
	        if (waMode != 'W')
	          {
		    int len = strlen (szval), len1;
		    len1 = len > nBufferLength ? nBufferLength : len;
		    if (pnStringLengthPtr)
		      *pnStringLengthPtr = len;
		    if (pDiagInfoPtr)
		      {
		        STRNCPY (pDiagInfoPtr, szval, len1);
		        *(((SQLCHAR *) pDiagInfoPtr) + len1) = 0;
		      }
		  }
		else
		  {
		    dm_StrCopyOut2_A2W((SQLCHAR *) szval, 
		    	(SQLWCHAR *) pDiagInfoPtr, nBufferLength, pnStringLengthPtr);
		  }
	      
	      }
	    break;
	  }
	else
	  {			/* Driver's errors */
	    nRecNumber -= nRecs;

	    if (!con)
	      {
		return SQL_NO_DATA_FOUND;
	      }

            if ((unicode_driver && waMode != 'W') 
                || (!unicode_driver && waMode == 'W'))
              {
                switch(nDiagIdentifier)
                  {
                  case SQL_DIAG_DYNAMIC_FUNCTION:
                  case SQL_DIAG_CLASS_ORIGIN:
                  case SQL_DIAG_CONNECTION_NAME:
                  case SQL_DIAG_MESSAGE_TEXT:
                  case SQL_DIAG_SERVER_NAME:
                  case SQL_DIAG_SQLSTATE:
                  case SQL_DIAG_SUBCLASS_ORIGIN:
                    if (waMode != 'W')
                      {
                      /* ansi=>unicode*/
                        if ((_DiagInfoPtr = malloc((nBufferLength + 1) * 
                               sizeof(wchar_t))) == NULL)
                          {
                            return SQL_ERROR;
                          }
                      }
                    else
                      {
                      /* unicode=>ansi*/
                        if ((_DiagInfoPtr = malloc(nBufferLength + 1)) == NULL)
                          {
                            return SQL_ERROR;
                          }
                      }
                    diagInfoPtr = _DiagInfoPtr;
                    break;
                  }
              }

            CALL_UDRIVER(con, Handle, retcode, hproc, unicode_driver, en_GetDiagField,
              (nHandleType, dhandle, nRecNumber, nDiagIdentifier, 
               diagInfoPtr, nBufferLength, pnStringLengthPtr ));
            if (hproc != SQL_NULL_HPROC)
              {
                if (pDiagInfoPtr
                    && SQL_SUCCEEDED (retcode)
                    && ((unicode_driver && waMode != 'W')
                        || (!unicode_driver && waMode == 'W')))
                  {
                    switch(nDiagIdentifier)
                      {
                      case SQL_DIAG_DYNAMIC_FUNCTION:
                      case SQL_DIAG_CLASS_ORIGIN:
                      case SQL_DIAG_CONNECTION_NAME:
                      case SQL_DIAG_MESSAGE_TEXT:
                      case SQL_DIAG_SERVER_NAME:
                      case SQL_DIAG_SQLSTATE:
                      case SQL_DIAG_SUBCLASS_ORIGIN:
                        if (waMode != 'W')
                          {
                          /* ansi<=unicode*/
                            dm_StrCopyOut2_W2A ((SQLWCHAR *) diagInfoPtr, 
				(SQLCHAR *) pDiagInfoPtr, 
				nBufferLength, pnStringLengthPtr);
                          }
                        else
                          {
                          /* unicode<=ansi*/
                            dm_StrCopyOut2_A2W ((SQLCHAR *)diagInfoPtr, 
			    	(SQLWCHAR *) pDiagInfoPtr, 
				nBufferLength, pnStringLengthPtr);
                          }
                      }
                  }

                MEM_FREE(_DiagInfoPtr);
		return retcode;
              }
            else
	      {			/* an ODBC2->ODBC3 translation */
		char *szval = "";
		wchar_t szState[6];
		SQLINTEGER nNative;

		if (nRecNumber > 1)
		  {
                    MEM_FREE(_DiagInfoPtr);
		    return SQL_NO_DATA_FOUND;
		  }

		if (nHandleType == SQL_HANDLE_DESC)
		  {
                    MEM_FREE(_DiagInfoPtr);
		    return SQL_INVALID_HANDLE;
		  }

		if (nDiagIdentifier != SQL_DIAG_MESSAGE_TEXT)
                   MEM_FREE(_DiagInfoPtr);

		switch (nDiagIdentifier)
		  {
		  case SQL_DIAG_SUBCLASS_ORIGIN:
		  case SQL_DIAG_CLASS_ORIGIN:
		    
		    CALL_UDRIVER (con, Handle, retcode, hproc, unicode_driver,
		      en_Error, (SQL_NULL_HENV,
		       nHandleType == SQL_HANDLE_DBC ? dhandle : SQL_NULL_HDBC,
		       nHandleType == SQL_HANDLE_STMT ? dhandle : SQL_NULL_HSTMT,
 		       szState, &nNative, NULL, 0, NULL));
                    if (hproc == SQL_NULL_HPROC)
                      {
		        return SQL_INVALID_HANDLE;
                      }
		    if (retcode != SQL_SUCCESS)
		      {
			return SQL_NO_DATA_FOUND;
		      }
		    if (waMode != 'W')
                      {
		        szval = !STRNEQ (szState, "IM", 2) ? (char *) "ODBC 3.0" : (char *) "ISO 9075";
                      }
		    else
                      {
                        if (szState[0] != L'I' && szState[1] != L'M')
		          szval = (char *) "ODBC 3.0";
                        else
		          szval = (char *) "ISO 9075";
                      }
		    break;

		  case SQL_DIAG_ROW_NUMBER:
		  case SQL_DIAG_COLUMN_NUMBER:
		    if (nHandleType != SQL_HANDLE_STMT || !stmt)
		      {
			return SQL_ERROR;
		      }
		    if (!con)
		      {
			return SQL_INVALID_HANDLE;
		      }
		    if (pDiagInfoPtr)
		      *((SQLINTEGER *) pDiagInfoPtr) =
			  SQL_COLUMN_NUMBER_UNKNOWN;
		    {
		      return SQL_SUCCESS;
		    }

		  case SQL_DIAG_SERVER_NAME:
		  case SQL_DIAG_CONNECTION_NAME:
		    break;

		  case SQL_DIAG_MESSAGE_TEXT:
		    CALL_UDRIVER (con, Handle, retcode, hproc, unicode_driver,
		      en_Error, (SQL_NULL_HENV,
		      nHandleType == SQL_HANDLE_DBC ? dhandle : SQL_NULL_HDBC,
		      nHandleType == SQL_HANDLE_STMT ? dhandle : SQL_NULL_HSTMT,
 		      szState, &nNative, diagInfoPtr, nBufferLength, 
 		      pnStringLengthPtr));
                    if (hproc == SQL_NULL_HPROC)
                      {
                        MEM_FREE(_DiagInfoPtr);
		        return SQL_INVALID_HANDLE;
                      }
                    if (pDiagInfoPtr
                        && SQL_SUCCEEDED (retcode)
                        && ((unicode_driver && waMode != 'W')
                            || (!unicode_driver && waMode == 'W')))
                      {
                        if (waMode != 'W')
                          {
                          /* ansi<=unicode*/
                            dm_StrCopyOut2_W2A ((SQLWCHAR *) diagInfoPtr, 
				(SQLCHAR *) pDiagInfoPtr, 
		      		nBufferLength, pnStringLengthPtr);
                          }
                        else
                          {
                          /* unicode<=ansi*/
                            dm_StrCopyOut2_A2W ((SQLCHAR *)diagInfoPtr, 
			    	(SQLWCHAR *) pDiagInfoPtr, 
				nBufferLength, pnStringLengthPtr);
                          }
                      }

                    MEM_FREE(_DiagInfoPtr);
		    return retcode;

		  case SQL_DIAG_NATIVE:
		    CALL_UDRIVER (con, Handle, retcode, hproc, unicode_driver,
		      en_Error, (SQL_NULL_HENV,
		      nHandleType == SQL_HANDLE_DBC ? dhandle : SQL_NULL_HDBC,
		      nHandleType == SQL_HANDLE_STMT ? dhandle : SQL_NULL_HSTMT,
 		      szState, &nNative, NULL, 0, NULL));
                    if (hproc == SQL_NULL_HPROC)
                      {
		        return SQL_INVALID_HANDLE;
                      }
		    if (pDiagInfoPtr)
		      *((SQLINTEGER *) pDiagInfoPtr) = nNative;
		    return retcode;

		  case SQL_DIAG_SQLSTATE:
		    CALL_UDRIVER (con, Handle, retcode, hproc, unicode_driver,
		      en_Error, (SQL_NULL_HENV,
		      nHandleType == SQL_HANDLE_DBC ? dhandle : SQL_NULL_HDBC,
		      nHandleType == SQL_HANDLE_STMT ? dhandle : SQL_NULL_HSTMT,
 		      szState, &nNative, NULL, 0, NULL));
                    if (hproc == SQL_NULL_HPROC)
                      {
		        return SQL_INVALID_HANDLE;
                      }
                    if (pDiagInfoPtr
                        && SQL_SUCCEEDED (retcode)
                        && ((unicode_driver && waMode != 'W')
                            || (!unicode_driver && waMode == 'W')))
                      {
                        if (waMode != 'W')
                          {
                          /* ansi<=unicode*/
                            dm_StrCopyOut2_W2A ((SQLWCHAR *) szState, 
				(SQLCHAR *) pDiagInfoPtr, 
		      		nBufferLength, pnStringLengthPtr);
                          }
                        else
                          {
                          /* unicode<=ansi*/
                            dm_StrCopyOut2_A2W ((SQLCHAR *)szState, 
			    	(SQLWCHAR *) pDiagInfoPtr, 
				nBufferLength, pnStringLengthPtr);
                          }
                      }

		    return retcode;

		  default:
		    return SQL_ERROR;
		  }

	        if (waMode != 'W')
	          {
		    if (pDiagInfoPtr)
		      {
		        int len = strlen (szval);
		        if (len > nBufferLength)
		          len = nBufferLength;
		        if (len)
		          _iodbcdm_strlcpy ((char *) pDiagInfoPtr, szval, len);
		      }
		    if (pnStringLengthPtr)
		      *pnStringLengthPtr = strlen (szval);
		  }
		else
		  {
		    dm_StrCopyOut2_A2W((SQLCHAR *) szval, 
		    	(SQLWCHAR *) pDiagInfoPtr, 
			nBufferLength, pnStringLengthPtr);
		  }
	      }			/* ODBC3->ODBC2 */
	  }			/* driver's errors */
      }				/* status records */
    }				/* switch (nRecNumber */
  return (SQL_SUCCESS);
}
예제 #14
0
void
vc4_qpu_disasm_pack_mul(FILE *out, uint32_t pack)
{
        fprintf(out, ".%s", DESC(qpu_pack_mul, pack));
}
예제 #15
0
파일: table.c 프로젝트: rohsaini/mkunity
	int	g:1;
#define	BYTES	0
#define PAGES	1
	int	base_31_24:8;
};
#define SEG_DESC_SIZE	8

#define DESC(base, limit, type, seg, gran)  \
	{ limit & 0xffff, base & 0xffff, (base >> 16) & 0xff, \
	  type, 1, DPL0, 1, (limit >> 16) & 0x0f, 0, 0, seg, gran, \
	  (base >> 24) & 0xff}

#define NGDTENT		6

const struct seg_desc Gdt[NGDTENT] = {
	DESC(0, 0, 0, 0, 0),			/* 0x0 : null */
	DESC(BOOTBASE, LIM32, CODE, SEG32, PAGES), /* 0x8 : boot code */
	DESC(BOOTBASE, LIM32, DATA, SEG32, PAGES), /* 0x10 : boot data */
	DESC(BOOTBASE, LIM16, CODE, SEG16, BYTES), /* 0x18 : boot code 16 */
	DESC(INITBASE, LIM32, DATA, SEG32, PAGES), /* 0x20 : init data */
	DESC(INITBASE, LIM32, CODE, SEG32, PAGES)  /* 0x28 : init code */
};

struct pseudo_desc {
	int	limit:16;
	int	base_low:16;
	int	base_high:16;
};

/*
 * boot is loaded at 4k, Gdt is located at 4k+512
예제 #16
0
/* Prints a usage message based on contents of optlist.
 * Parameters:
 *   scanner  - The scanner, already initialized with scanopt_init().
 *   fp       - The file stream to write to.
 *   usage    - Text to be prepended to option list.
 * Return:  Always returns 0 (zero).
 * The output looks something like this:

[indent][option, alias1, alias2...][indent][description line1
                                            description line2...]
 */
int     scanopt_usage (scanopt_t *scanner, FILE *fp, const char *usage)
{
	struct _scanopt_t *s;
	int     i, columns;
	const int indent = 2;
	usg_elem *byr_val = NULL;	/* option indices sorted by r_val */
	usg_elem *store;	/* array of preallocated elements. */
	int     store_idx = 0;
	usg_elem *ue;
	int     opt_col_width = 0, desc_col_width = 0;
	int     desccol;
	int     print_run = 0;

	s = (struct _scanopt_t *) scanner;

	if (usage) {
		fprintf (fp, "%s\n", usage);
	}
	else {
		fprintf (fp, _("Usage: %s [OPTIONS]...\n"), s->argv[0]);
	}
	fprintf (fp, "\n");

	/* Sort by r_val and string. Yes, this is O(n*n), but n is small. */
	store = malloc((size_t) s->optc * sizeof (usg_elem));
	for (i = 0; i < s->optc; i++) {

		/* grab the next preallocate node. */
		ue = store + store_idx++;
		ue->idx = i;
		ue->next = ue->alias = NULL;

		/* insert into list. */
		if (!byr_val)
			byr_val = ue;
		else {
			int     found_alias = 0;
			usg_elem **ue_curr, **ptr_if_no_alias = NULL;

			ue_curr = &byr_val;
			while (*ue_curr) {
				if (RVAL (s, (*ue_curr)->idx) ==
				    RVAL (s, ue->idx)) {
					/* push onto the alias list. */
					ue_curr = &((*ue_curr)->alias);
					found_alias = 1;
					break;
				}
				if (!ptr_if_no_alias
				    &&
				    strcasecmp (NAME (s, (*ue_curr)->idx),
						NAME (s, ue->idx)) > 0) {
					ptr_if_no_alias = ue_curr;
				}
				ue_curr = &((*ue_curr)->next);
			}
			if (!found_alias && ptr_if_no_alias)
				ue_curr = ptr_if_no_alias;
			ue->next = *ue_curr;
			*ue_curr = ue;
		}
	}

#if 0
	if (1) {
		printf ("ORIGINAL:\n");
		for (i = 0; i < s->optc; i++)
			printf ("%2d: %s\n", i, NAME (s, i));
		printf ("SORTED:\n");
		ue = byr_val;
		while (ue) {
			usg_elem *ue2;

			printf ("%2d: %s\n", ue->idx, NAME (s, ue->idx));
			for (ue2 = ue->alias; ue2; ue2 = ue2->next)
				printf ("  +---> %2d: %s\n", ue2->idx,
					NAME (s, ue2->idx));
			ue = ue->next;
		}
	}
#endif

	/* Now build each row of output. */

	/* first pass calculate how much room we need. */
	for (ue = byr_val; ue; ue = ue->next) {
		usg_elem *ap;
		int     len;

		len = PRINTLEN(s, ue->idx);

		for (ap = ue->alias; ap; ap = ap->next) {
			len += PRINTLEN(s, ap->idx) + (int) strlen(", ");
		}

		if (len > opt_col_width)
			opt_col_width = len;

		/* It's much easier to calculate length for description column! */
		len = (int) strlen (DESC (s, ue->idx));
		if (len > desc_col_width)
			desc_col_width = len;
	}

	/* Determine how much room we have, and how much we will allocate to each col.
	 * Do not address pathological cases. Output will just be ugly. */
	columns = get_cols () - 1;
	if (opt_col_width + desc_col_width + indent * 2 > columns) {
		/* opt col gets whatever it wants. we'll wrap the desc col. */
		desc_col_width = columns - (opt_col_width + indent * 2);
		if (desc_col_width < 14)	/* 14 is arbitrary lower limit on desc width. */
			desc_col_width = INT_MAX;
	}
	desccol = opt_col_width + indent * 2;

#define PRINT_SPACES(fp,n) \
	fprintf((fp), "%*s", (n), "")

	/* Second pass (same as above loop), this time we print. */
	/* Sloppy hack: We iterate twice. The first time we print short and long options.
	   The second time we print those lines that have ONLY long options. */
	while (print_run++ < 2) {
		for (ue = byr_val; ue; ue = ue->next) {
			usg_elem *ap;
			int     nwords = 0, nchars = 0, has_short = 0;

/* TODO: get has_short schtick to work */
			has_short = !(FLAGS (s, ue->idx) & IS_LONG);
			for (ap = ue->alias; ap; ap = ap->next) {
				if (!(FLAGS (s, ap->idx) & IS_LONG)) {
					has_short = 1;
					break;
				}
			}
			if ((print_run == 1 && !has_short) ||
			    (print_run == 2 && has_short))
				continue;

			PRINT_SPACES (fp, indent);
			nchars += indent;

/* Print, adding a ", " between aliases. */
#define PRINT_IT(i) do{\
                  if(nwords++)\
                      nchars+=fprintf(fp,", ");\
                  nchars+=fprintf(fp,"%s",s->options[i].opt_fmt);\
            }while(0)

			if (!(FLAGS (s, ue->idx) & IS_LONG))
				PRINT_IT (ue->idx);

			/* print short aliases first. */
			for (ap = ue->alias; ap; ap = ap->next) {
				if (!(FLAGS (s, ap->idx) & IS_LONG))
					PRINT_IT (ap->idx);
			}


			if (FLAGS (s, ue->idx) & IS_LONG)
				PRINT_IT (ue->idx);

			/* repeat the above loop, this time for long aliases. */
			for (ap = ue->alias; ap; ap = ap->next) {
				if (FLAGS (s, ap->idx) & IS_LONG)
					PRINT_IT (ap->idx);
			}

			/* pad to desccol */
			PRINT_SPACES (fp, desccol - nchars);

			/* Print description, wrapped to desc_col_width columns. */
			if (1) {
				const char *pstart;

				pstart = DESC (s, ue->idx);
				while (1) {
					int     n = 0;
					const char *lastws = NULL, *p;

					p = pstart;

					while (*p && n < desc_col_width
					       && *p != '\n') {
						if (isspace ((unsigned char)(*p))
						    || *p == '-') lastws =
								p;
						n++;
						p++;
					}

					if (!*p) {	/* hit end of desc. done. */
						fprintf (fp, "%s\n",
							 pstart);
						break;
					}
					else if (*p == '\n') {	/* print everything up to here then wrap. */
						fprintf (fp, "%.*s\n", n,
							 pstart);
						PRINT_SPACES (fp, desccol);
						pstart = p + 1;
						continue;
					}
					else {	/* we hit the edge of the screen. wrap at space if possible. */
						if (lastws) {
							fprintf (fp,
								 "%.*s\n",
								 (int)(lastws - pstart),
								 pstart);
							pstart =
								lastws + 1;
						}
						else {
							fprintf (fp,
								 "%.*s\n",
								 n,
								 pstart);
							pstart = p + 1;
						}
						PRINT_SPACES (fp, desccol);
						continue;
					}
				}
			}
		}
	}			/* end while */
	free (store);
	return 0;
}
예제 #17
0
파일: fprintf.c 프로젝트: bboozzoo/zephyr
#include <stdarg.h>
#include <stdio.h>

#define DESC(d) ((void *)d)

extern int _prf(int (*func)(), void *dest,
				const char *format, va_list vargs);

int fprintf(FILE *_MLIBC_RESTRICT F, const char *_MLIBC_RESTRICT format, ...)
{
	va_list vargs;
	int     r;

	va_start(vargs, format);
	r = _prf(fputc, DESC(F), format, vargs);
	va_end(vargs);

	return r;
}

int vfprintf(FILE *_MLIBC_RESTRICT F, const char *_MLIBC_RESTRICT format,
	     va_list vargs)
{
	int r;

	r = _prf(fputc, DESC(F), format, vargs);

	return r;
}