예제 #1
0
파일: frotz.c 프로젝트: a-martinez/rockbox
zchar os_read_key(int timeout, bool show_cursor)
{
    int r;
    char inputbuf[5];
    short key;
    zchar zkey;

    for(;;)
    {
        zkey = do_input(timeout, show_cursor);
        if (zkey != ZC_BAD)
            return zkey;

        inputbuf[0] = '\0';
        r = rb->kbd_input(inputbuf, 5);
        rb->lcd_setfont(FONT_SYSFIXED);
        dumb_dump_screen();
        if (!r)
        {
            rb->utf8decode(inputbuf, &key);
            if (key > 0 && key < 256)
                return (zchar)key;
        }
    }
}
예제 #2
0
파일: update.c 프로젝트: MaxLeiter/pong
void update() {
	do_input();
	ai_frame = !ai_frame;
	if (ai_frame) {
		update_ball();
		update_ai(&right_paddle);
	}
	ksleep(5);
}
예제 #3
0
파일: report.c 프로젝트: duke1swd/HSIM
/*
 * Top Level Flow Control
 */
int
main(int argc, char **argv)
{
	grok_args(argc, argv);

	if (do_input()) {
		set_fuel_type();
		print_report();
		rocksim_report();
	}
	putchar('\n');
	save_text_dump(stdout);
	exit(0);
}
예제 #4
0
/*
 * handle_file_insert()
 *
 * allows the user to insert a query file and execute it.
 * NOTE: right now the full path name must be specified.
 */
static void
handle_file_insert(FILE *ifp)
{
    char user_filename[50];
    FILE *nifp;

    fscanf(ifp, "%s",user_filename);
    nifp = fopen(user_filename, "r");
    if (nifp == (FILE *) NULL) {
        fprintf(stderr, "Cannot open %s\n", user_filename);
    } else {
        do_input(nifp);
        fclose (nifp);
    }
}
예제 #5
0
int main(int argc, char* argv[])
{ 
  clock_t time = clock();

  point p_mouse;
  light_source light;
  if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
      std::cerr << "Error initializing sdl" << std::endl;
      return 1;
    }
 
  SDL_Surface* screen = SDL_SetVideoMode(LENGTH, HEIGHT, 32, 0);
  redraw = true;
  if(argc == 2)
  	init_height_map_from_bmp(argv[1]);
  else
  	init_height_map();

  height_to_normal_map();
 
  //MAIN RENDER/INPUT LOOP
  while (do_input(p_mouse, light))
    {
      redraw = true;
      if (redraw)
        {
	  // Rerender
	  
	  // These two functions are to simulate an animated height map
	  // rendering loop
	  //	  apply_waves_to_height_map();
	  init_height_map();
	  height_to_normal_map();

	  shade(light);
	  
	  // Draw to screen
	  render_array(shade_map);
	  
          redraw = false;
        }
      SDL_Flip(screen);
    }
 
  return 0;
}
예제 #6
0
int main(int argc, char** argv)
{
    ToxGroup *g;

    if(argc != 1 && argc != 3) {
        printf("Usage: %s [ip port]\n", argv[0]);
        return 1;
    }

    curses_init();

    if(argc == 3) {
        uint32_t ip;
        uint16_t port;

        inet_pton(AF_INET, argv[1], &ip);
        port = strtol(argv[2], NULL, 0);

        g = toxgroup_new_bootstrap(ip, port);
    } else {
        g = toxgroup_new();
    }

    update_info(g);
    g->peer_callback = peer_callback;
    g->message_callback = message_callback;

    int z = 0;
    while(1) {
        toxgroup_do(g);

        do_input(g);
        if(info_change) {
            update_info(g);
            info_change = 0;
        }
        usleep(500);
        z++;
        if(z == 2000) {
            if(send_audio) {toxgroup_sendaudio(g);}
            z = 0;
        }
    }

    return 0;
}
예제 #7
0
파일: frotz.c 프로젝트: a-martinez/rockbox
zchar os_read_line(int max, zchar *buf, int timeout, int width, int continued)
{
    (void)continued;
    int r;
    char inputbuf[256];
    const char *in;
    char *out;
    short key;
    zchar zkey;

    for(;;)
    {
        zkey = do_input(timeout, true);
        if (zkey != ZC_BAD)
            return zkey;

        if (max > width)
            max = width;
        strcpy(inputbuf, buf);
        r = rb->kbd_input(inputbuf, 256);
        rb->lcd_setfont(FONT_SYSFIXED);
        dumb_dump_screen();
        if (!r)
        {
            in = inputbuf;
            out = buf;
            while (*in && max)
            {
                in = rb->utf8decode(in, &key);
                if (key > 0 && key < 256)
                {
                    *out++ = key;
                    max--;
                }
            }
            *out = '\0';
            os_display_string(buf);
            return ZC_RETURN;
        }
    }
}
예제 #8
0
static void process_remote(struct device_settings settings, const char *mac, int modes)
{
    int br;
    bool msg = true;
    unsigned char buf[128];

    int last_time_action = get_time();

    while (!io_canceled()) {
        br = read(isk, buf, sizeof(buf));
        if (msg) {
            syslog(LOG_INFO, "Connected 'PLAYSTATION(R)3 Remote (%s)'", mac);
            msg = false;
        }

        if (settings.timeout.enabled) {
            int current_time = get_time();
            if (was_active()) {
                last_time_action = current_time;
                set_active(false);
            } else if (current_time-last_time_action >= settings.timeout.timeout) {
                syslog(LOG_INFO, "Remote was not in use, and timeout reached, disconneting...");
                sig_term(0);
                break;
            }
        }

        if (br < 0) {
            break;
        } else if (br==13 && buf[0]==0xa1 && buf[1]==0x01) { //only continue if we've got a Remote
            if (settings.joystick.enabled) do_joystick(ufd->js, buf, settings.joystick);
            if (settings.remote.enabled) do_remote(ufd->mk, buf, modes);
            if (settings.input.enabled) do_input(ufd->mk, buf, settings.input);
        } else {
            if (debug) syslog(LOG_ERR, "Non-Remote packet received and ignored (0x%02x|0x%02x|0x%02x)", buf[0], buf[1], buf[2]);
        }
    }

    if (debug) syslog(LOG_ERR, "Read loop was broken on the Remote process");
}
예제 #9
0
int main(int argc, char* argv[])
{
    WNDCLASSEX wnd_class;

    wnd_class.cbSize = sizeof(wnd_class);
    wnd_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wnd_class.lpfnWndProc = WndProc;
    wnd_class.cbClsExtra = 0;
    wnd_class.cbWndExtra = 0;
    wnd_class.hInstance = hInstance;
    wnd_class.hIcon = 0;
    wnd_class.hCursor = 0;
    wnd_class.hbrBackground = 0;
    wnd_class.lpszMenuName = NULL;
    wnd_class.lpszClassName = "IxxliiWindowClass";
    wnd_class.hIconSm = 0;

    if (!RegisterClassEx(&wnd_class)) {
        return -1;
    }

    hInstance = hInstance;

    hWnd = CreateWindow("IxxliiWindowClass", "Ixxlii",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        wnd_width, wnd_height, NULL, NULL, hInstance, NULL);

    if (!hWnd) {
        return -1;
    }

    PIXELFORMATDESCRIPTOR pfd = {
        sizeof(pfd),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        32,
        0, 0, 0, 0, 0, 0,
        0,
        0,
        0,
        0, 0, 0, 0,
        24,
        0,
        0,
        PFD_MAIN_PLANE,
        0,
        0, 0, 0
    };

    if (!(hDC = GetDC(hWnd))) {
        return -1;
    }

    unsigned int pixelFormat;
    if (!(pixelFormat = ChoosePixelFormat(hDC, &pfd))) {
        return -1;
    }

    if (!SetPixelFormat(hDC, pixelFormat, &pfd)) {
        return -1;
    }

    if (!(hRC = wglCreateContext(hDC))) {
        return -1;
    }

    if (!wglMakeCurrent(hDC, hRC)) {
        return -1;
    }

    ShowWindow(hWnd, SW_SHOW);
    UpdateWindow(hWnd);

    ixx_render_init(&render, 800, 600);

    ixx_render_load_texture(&render, "data/test.bmp");

    DWORD curr_time;
    DWORD last_time = GetTickCount();

    IxxHuman h1;
    ixx_human_init(&h1);

    IxxMat4f aa;
    ixx_mat4f_identity(aa);
    ixx_mat4f_set_pos_xyz(aa, 1.0f, 2.0f, 3.0f);
    ixx_mat4f_set_x_rot(aa, 11.1f);
    ixx_mat4f_set_y_rot(aa, 22.1f);
    ixx_mat4f_set_z_rot(aa, 180.1f);
    ixx_mat4f_print(aa);
    ixx_mat4f_invert(aa);
    printf("\n");
    ixx_mat4f_print(aa);

    while (!closed) {
        /*
         * Calc delta time
         */
        curr_time = GetTickCount();
        dt = curr_time - last_time;
        last_time = curr_time;

        /*
         * Handle os messages
         */
        MSG msg;
        while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        /*
         * Input
         */
        do_input();

        /*
         * Simulate
         */
        update();

        static float r = 0.0f;
        r += 0.01f * dt;

        // parent
        IxxMat4f pos;
        ixx_mat4f_identity(pos);
        pos[IXX_MAT4F_POS_X] = -h1.bind_neck[IXX_MAT4F_POS_X];
        pos[IXX_MAT4F_POS_Y] = -h1.bind_neck[IXX_MAT4F_POS_Y];
        pos[IXX_MAT4F_POS_Z] = -h1.bind_neck[IXX_MAT4F_POS_Z];
        ixx_mat4f_set_x_rot(h1.b_neck, ixx_deg_to_rad(r));
        ixx_mat4f_mult(h1.b_neck, pos, h1.neck);

        // child bone
        IxxMat4f pos2;
        ixx_mat4f_identity(pos2);
        pos2[IXX_MAT4F_POS_X] = h1.bind_head[IXX_MAT4F_POS_X] - h1.bind_neck[IXX_MAT4F_POS_X];
        pos2[IXX_MAT4F_POS_Y] = h1.bind_head[IXX_MAT4F_POS_Y] - h1.bind_neck[IXX_MAT4F_POS_Y];
        pos2[IXX_MAT4F_POS_Z] = h1.bind_head[IXX_MAT4F_POS_Z] - h1.bind_neck[IXX_MAT4F_POS_Z];
        ixx_mat4f_mult(h1.b_neck, pos2, h1.b_head);
        
        // child
        IxxMat4f pos3;
        ixx_mat4f_identity(pos3);
        pos3[IXX_MAT4F_POS_X] = -h1.bind_head[IXX_MAT4F_POS_X];
        pos3[IXX_MAT4F_POS_Y] = -h1.bind_head[IXX_MAT4F_POS_Y];
        pos3[IXX_MAT4F_POS_Z] = -h1.bind_head[IXX_MAT4F_POS_Z];
        ixx_mat4f_set_x_rot(h1.b_head, ixx_deg_to_rad(-r));
        ixx_mat4f_mult(h1.b_head, pos3, h1.head);

        ixx_render_calc_view(&render);

        IxxVec2i curr_mouse = {curr_mouse_x, curr_mouse_y};
        IxxVec2i last_mouse = {last_mouse_x, last_mouse_y};

        int viewport[4];
        ixx_render_get_viewport(viewport);
        printf("%i %i %i %i\n", viewport[0], viewport[1], viewport[2], viewport[3]);

        IxxVec2f curr_mouse_norm;
        curr_mouse_norm[0] =
            ((2.0f * ((float)curr_mouse[0] - (float)viewport[0])) / (float)viewport[2]) - 1.0f;
        curr_mouse_norm[1] =
            1.0f - ((2.0f * ((float)curr_mouse[1] - (float)viewport[1])) / (float)viewport[3]);

        IxxMat4f vp;
        ixx_mat4f_mult(render.proj, render.view, vp);
        ixx_mat4f_invert(vp);

        IxxVec4f norm_vec = {curr_mouse_norm[0], curr_mouse_norm[1], -1.0f, 1.0f};
        IxxVec4f near_point;
        ixx_vec4f_mult_mat4f(norm_vec, vp, near_point);
        near_point[3] = 1.0f / near_point[3];
        near_point[0] *= near_point[3];
        near_point[1] *= near_point[3];
        near_point[2] *= near_point[3];

        last_mouse_x = curr_mouse_x;
        last_mouse_y = curr_mouse_y;

        /*
         * Render
         */
        ixx_render_begin(&render);

        IxxVec3f np = {near_point[0], near_point[1], near_point[2]};
        ixx_render_line_3f(
            np[0], np[1], np[2],
            -10.0f, 0.0f, 0.0f,
            1.0f, 0.0f, 0.0f, 1.0f,
            5.0f);

        ixx_draw_ground_line_grid(40, 0.5f, 0.5f, 0.5f, 1.0f);
        ixx_draw_human(&h1);

        ixx_render_end(&render);

        SwapBuffers(hDC);
        Sleep(1);
    }

    return 0;
}
예제 #10
0
int main(int argc, char **argv)
{
    int i, fd, nr;
    unsigned char buf[128];
    struct uinput_fd *ufd;
    struct device_settings settings;

    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " /dev/hidrawX" << std::endl;
        return 1;
    }

    if ((fd = open(argv[1], O_RDONLY)) < 0) {
        std::cerr << "sixad-raw::open(hidrawX) - failed to open hidraw device" << std::endl;
        return 1;
    }

    if ((nr=read(fd, buf, sizeof(buf))) < 0) {
        std::cerr << "sixad-raw::read(fd) - failed to read from device" << std::endl;
        return 1;
    }

    if (nr < 49 || nr > 50) {
        std::cerr <<  "sixad-raw::read(fd) - not a sixaxis (nr = " << nr << ")" << std::endl;
        return 1;
    }

    open_log("sixad-raw");
    settings = init_values("hidraw");

    // hidraw has no rumble/led support
    settings.remote.enabled = false;
    settings.led.enabled = false;
    settings.rumble.enabled = false;

    ufd = uinput_open(DEV_TYPE_SIXAXIS, "hidraw", settings);

    if (ufd->js < 0 || ufd->mk < 0) {
        return 1;
    } else if (ufd->js == 0 && ufd->mk == 0) {
        syslog(LOG_ERR, "sixaxis config has no joystick or input mode selected - please choose one!");
        return 1;
    }

    bool msg = true;
    while (true) {

        nr=read(fd, buf, sizeof(buf));

        if (nr < 49 || nr > 50) {
          std::cerr <<  "sixad-raw::read(fd, buf) - failed to read from device" << std::endl;
          break;
        } else if (nr == 49) {
          for (i=50; i>0; i--) {
            buf[i] = buf[i-1];
          }
        }

        if (msg) {
            syslog(LOG_INFO, "Connected 'PLAYSTATION(R)3 Controller (hidraw)' [Battery %02X]", buf[31]);
            if (nr == 49) syslog(LOG_INFO, "Notice: non-standard Sixaxis buffer size (49)");
            msg = false;
        }

        if (settings.joystick.enabled) do_joystick(ufd->js, buf, settings.joystick);
        if (settings.input.enabled) do_input(ufd->mk, buf, settings.input);
    }

    if (settings.joystick.enabled) {
        uinput_close(ufd->js, 0);
    }
    if (settings.input.enabled) {
        uinput_close(ufd->mk, 0);
    }

    std::cerr <<  "sixad-raw::read(buf) - connection has been broken" << std::endl;
    
    delete ufd;

    return 0;
}
예제 #11
0
파일: main.c 프로젝트: petabi/pkgsrc
int
main(int argc, char **argv)
{
    const char	*outname;
    const char	*format;
    const char	*check;
    const char	*alg;
    const char	*sub;
    const char	*sep;
    uint8_t		 raw[8192];
    char	 	 from[128];
    char	 	 to[128];
    int		 ok;
    int		 i;

    alg = "sha1";
    format = "multigest";
    sep = sub = outname = check = NULL;
    from[0] = to[0] = 0x0;
    while ((i = getopt(argc, argv, "F:S:a:c:o:rs:")) != -1) {
        switch(i) {
        case 'F':
            format = optarg;
            break;
        case 'S':
            sep = optarg;
            break;
        case 'a':
            alg = optarg;
            break;
        case 'c':
            check = optarg;
            break;
        case 'o':
            outname = optarg;
            break;
        case 'r':
            getsubst(sub = ",\\$(Id|NetBSD)[^\n]*\\$,\044NetBSD\044", from, sizeof(from), to, sizeof(to));
            break;
        case 's':
            getsubst(sub = optarg, from, sizeof(from), to, sizeof(to));
            break;
        default:
            break;
        }
    }
    ok = 1;
    if (check) {
        if (!read_check(check)) {
            ok = 0;
        }
    } else if (optind == argc) {
        if (do_input(alg, raw, from, to)) {
            multigest_print_hex(raw, alg, outname, NULL, sub, sep, format);
        } else {
            ok = 0;
        }
    } else {
        for (i = optind ; i < argc ; i++) {
            if (multigest_file(alg, argv[i], raw, from, to) == NULL) {
                ok = 0;
            } else {
                multigest_print_hex(raw, alg, outname, argv[i], sub, sep, format);
            }
        }
    }
    exit((ok) ? EXIT_SUCCESS : EXIT_FAILURE);
}
예제 #12
0
void test_decryption()
{
	gf2matrix *mix_columns_mixing_bijection, *inv_mix_columns_mixing_bijection;
	tbox_mixing_bijections_t tbox_mixing_bijections, inv_tbox_mixing_bijections;
	gf2matrix *initial_encoding, *initial_decoding;
	gf2matrix *final_encoding, *final_decoding;
	tbox_t tbox;
	typeIA_t typeIAs;
	typeII_t typeIIs;
	typeIII_t typeIIIs;
	typeIB_t typeIBs;
	typeIV_IA_t typeIV_IAs;
	typeIV_IB_t typeIV_IBs;
	typeIV_II_round_t typeIV_IIs[NR - 1];
	typeIV_III_round_t typeIV_IIIs[NR - 1];
	uint32_t mixed_key_schedule[4 * (NR + 1)];
	uint8_t key[KEY_SIZE] = {
			0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
			0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
	sboxes_8bit_t typeIA_input_sbox, typeIA_input_sbox_inv;
	sboxes_128bit_t typeIA_interim_sbox, typeIA_interim_sbox_inv;
	sboxes_8bit_t typeII_input_sbox[NR], typeII_input_sbox_inv[NR];
	sboxes_32bit_t typeII_interim_sbox[NR - 1], typeII_interim_sbox_inv[NR - 1];
	sboxes_8bit_t typeII_output_sbox[NR - 1], typeII_output_sbox_inv[NR - 1];
	sboxes_32bit_t typeIII_interim_sbox[NR - 1], typeIII_interim_sbox_inv[NR
			- 1];
	sboxes_128bit_t typeIB_interim_sbox, typeIB_interim_sbox_inv;
	sboxes_8bit_t typeIB_output_sbox, typeIB_output_sbox_inv;
	uint8_t state[4][4];
	uint8_t in[16];
	uint8_t out[16], out2[16];
	_4bit_strip32_t strips32;
	_4bit_strip128_t strips128;
	int round, row, col, i;

	int tries = 3;
	for (; tries != 0; --tries) {
		randomize_key(key);
		make_block_invertible_matrix_pair(&mix_columns_mixing_bijection,
				&inv_mix_columns_mixing_bijection, 32);
/* 		mix_columns_mixing_bijection = make_identity_matrix(32); */
/* 		inv_mix_columns_mixing_bijection = make_identity_matrix(32); */
		make_tbox_mixing_bijections(tbox_mixing_bijections,
				inv_tbox_mixing_bijections);
/* 		make_identity_tbox_mixing_bijections(tbox_mixing_bijections); */
/* 		make_identity_tbox_mixing_bijections(inv_tbox_mixing_bijections); */

		make_block_invertible_matrix_pair(&initial_encoding, &initial_decoding, 128);
/* 		initial_encoding = make_identity_matrix(128); */
/* 		initial_decoding = make_identity_matrix(128); */
		make_block_invertible_matrix_pair(&final_encoding, &final_decoding, 128);
/* 		final_encoding = make_identity_matrix(128); */
/* 		final_decoding = make_identity_matrix(128); */

		expand_key(key, SBox, mixed_key_schedule, 4);
		mix_expanded_key(mixed_key_schedule);
		make_inv_tbox(tbox, ISBox, mixed_key_schedule, tbox_mixing_bijections);

		make_sbox_pair_8(typeIA_input_sbox, typeIA_input_sbox_inv);
/* 		make_identity_sboxes8(typeIA_input_sbox); */
/* 		make_identity_sboxes8(typeIA_input_sbox_inv); */
		make_sbox_pair_128(typeIA_interim_sbox, typeIA_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIA_interim_sbox); */
/* 		make_identity_sboxes128(typeIA_interim_sbox_inv); */
		make_rounds_sbox_pair_8(typeII_input_sbox, typeII_input_sbox_inv, NR);
/* 		for(i =0; i < NR; ++i) { */
/* 			make_identity_sboxes8(typeII_input_sbox[i]); */
/* 			make_identity_sboxes8(typeII_input_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_32(typeII_interim_sbox, typeII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeII_interim_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_8(typeII_output_sbox, typeII_output_sbox_inv, NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes8(typeII_output_sbox[i]); */
/* 			make_identity_sboxes8(typeII_output_sbox_inv[i]); */
/* 		} */

		make_rounds_sbox_pair_32(typeIII_interim_sbox, typeIII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeIII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeIII_interim_sbox_inv[i]); */
/* 		} */
		make_sbox_pair_128(typeIB_interim_sbox, typeIB_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIB_interim_sbox); */
/* 		make_identity_sboxes128(typeIB_interim_sbox_inv); */
		make_sbox_pair_8(typeIB_output_sbox, typeIB_output_sbox_inv);
/* 		make_identity_sboxes8(typeIB_output_sbox); */
/* 		make_identity_sboxes8(typeIB_output_sbox_inv); */


		make_typeIA(typeIAs, inv_tbox_mixing_bijections[NR - 1], initial_decoding,
				typeIA_input_sbox_inv, typeIA_interim_sbox);
		make_typeIV_IA(typeIV_IAs, typeIA_interim_sbox_inv,
				typeII_input_sbox[NR - 1], typeII_input_sbox_inv[NR-1]);
		make_inv_typeII(typeIIs, tbox, mix_columns_mixing_bijection,
				&typeII_input_sbox_inv[1], typeII_interim_sbox);
		make_typeIV_II(typeIV_IIs, typeII_interim_sbox_inv, typeII_output_sbox,
				typeII_output_sbox_inv);
		make_typeIII(typeIIIs, inv_mix_columns_mixing_bijection,
				inv_tbox_mixing_bijections, typeII_output_sbox_inv,
				typeIII_interim_sbox);
		make_typeIV_III(typeIV_IIIs, typeIII_interim_sbox_inv,
				typeII_input_sbox, typeII_input_sbox_inv);
		make_inv_typeIB(typeIBs, tbox[0], final_encoding,
				typeII_input_sbox_inv[0], typeIB_interim_sbox);
		make_typeIV_IB(typeIV_IBs, typeIB_interim_sbox_inv, typeIB_output_sbox,
				typeIB_output_sbox_inv);

		for (i = 0; i < 16; ++i) {
			in[i] = rand();
		}
		dump_hex("input: ", in, 16);
		printf("White-box inverse cipher:\n");
		do_input(state, in, initial_encoding, typeIA_input_sbox);

		dump_state("State before ", state);
		do_typeIA(strips128, state, typeIAs);
		do_typeIV_IA(state, strips128, typeIV_IAs);
		for (round = NR - 2; round != -1; --round) {
			printf("round %d: ", round + 2);
			dump_state("", state);
			inv_shift_rows(state);
			do_typeII(strips32, state, typeIIs[round]);
			do_typeIV_II(state, strips32, typeIV_IIs[round]);
			do_typeIII(strips32, state, typeIIIs[round]);
			do_typeIV_III(state, strips32, typeIV_IIIs[round]);
		}
		inv_shift_rows(state);
		dump_state("rounds 1 and 0: ", state);
		do_typeIB(strips128, state, typeIBs);
		do_typeIV_IB(state, strips128, typeIV_IBs);

		do_output(out, state, final_decoding, typeIB_output_sbox_inv);

		printf("Original AES Equivalent Inverse Cipher on same input using same key:\n");
		eqv_decipher(in, out2, ISBox, mixed_key_schedule);
		dump_hex("WB Output ", out, 16);
		dump_hex("AES Output ", out2, 16);
		ASSERT(memcmp(out, out2, 16) == 0);
		free_matrix(mix_columns_mixing_bijection);
		free_matrix(inv_mix_columns_mixing_bijection);
		free_tbox_mixing_bijections(tbox_mixing_bijections);
		free_tbox_mixing_bijections(inv_tbox_mixing_bijections);
		free_matrix(final_decoding);
		free_matrix(final_encoding);
		free_matrix(initial_decoding);
		free_matrix(initial_encoding);
	}
}
예제 #13
0
void goto_convertt::do_function_call_symbol(
  const exprt &lhs,
  const symbol_exprt &function,
  const exprt::operandst &arguments,
  goto_programt &dest)
{
  if(function.get_bool("#invalid_object"))
    return; // ignore

  // lookup symbol
  const irep_idt &identifier=function.get_identifier();

  const symbolt *symbol;
  if(ns.lookup(identifier, symbol))
  {
    err_location(function);
    throw "error: function `"+id2string(identifier)+"' not found";
  }

  if(symbol->type.id()!=ID_code)
  {
    err_location(function);
    throw "error: function `"+id2string(identifier)+"' type mismatch: expected code";
  }
  
  if(identifier==CPROVER_PREFIX "assume" ||
     identifier=="__VERIFIER_assume")
  {
    if(arguments.size()!=1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one argument";
    }

    goto_programt::targett t=dest.add_instruction(ASSUME);
    t->guard=arguments.front();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier=="__VERIFIER_error")
  {
    if(!arguments.empty())
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have no arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(has_prefix(id2string(identifier), "java::java.lang.AssertionError.<init>:"))
  {
    // insert function call anyway
    code_function_callt function_call;
    function_call.lhs()=lhs;
    function_call.function()=function;
    function_call.arguments()=arguments;
    function_call.add_source_location()=function.source_location();

    copy(function_call, FUNCTION_CALL, dest);

    if(arguments.size()!=1 && arguments.size()!=2)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one or two arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);    
    t->source_location.set_comment("assertion at "+function.source_location().as_string());
  }
  else if(identifier=="assert" &&
          !ns.lookup(identifier).location.get_function().empty())
  {
    if(arguments.size()!=1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one argument";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=arguments.front();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment("assertion "+id2string(from_expr(ns, "", t->guard)));
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier==CPROVER_PREFIX "assert")
  {
    if(arguments.size()!=2)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have two arguments";
    }
    
    const irep_idt description=
      get_string_constant(arguments[1]);

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=arguments[0];
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier==CPROVER_PREFIX "printf")
  {
    do_printf(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "scanf")
  {
    do_scanf(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "input" ||
          identifier=="__CPROVER::input")
  {
    do_input(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "output" ||
          identifier=="__CPROVER::output")
  {
    do_output(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "atomic_begin" ||
          identifier=="__CPROVER::atomic_begin" ||
          identifier=="__VERIFIER_atomic_begin")
  {
    do_atomic_begin(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "atomic_end" ||
          identifier=="__CPROVER::atomic_end" ||
          identifier=="__VERIFIER_atomic_end")
  {
    do_atomic_end(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "prob_biased_coin")
  {
    do_prob_coin(lhs, function, arguments, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "prob_uniform_"))
  {
    do_prob_uniform(lhs, function, arguments, dest);
  }
  else if(has_prefix(id2string(identifier), "nondet_") ||
          has_prefix(id2string(identifier), "__VERIFIER_nondet_"))
  {
    // make it a side effect if there is an LHS
    if(lhs.is_nil()) return;
    
    exprt rhs;
    
    // We need to special-case for _Bool, which
    // can only be 0 or 1.
    if(lhs.type().id()==ID_c_bool)
    {
      rhs=side_effect_expr_nondett(bool_typet());
      rhs.add_source_location()=function.source_location();
      rhs.set(ID_C_identifier, identifier);
      rhs=typecast_exprt(rhs, lhs.type());
    } 
    else
    {
      rhs=side_effect_expr_nondett(lhs.type());
      rhs.add_source_location()=function.source_location();
      rhs.set(ID_C_identifier, identifier);
    }

    code_assignt assignment(lhs, rhs);
    assignment.add_source_location()=function.source_location();
    copy(assignment, ASSIGN, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "uninterpreted_"))
  {
    // make it a side effect if there is an LHS
    if(lhs.is_nil()) return;

    function_application_exprt rhs;
    rhs.type()=lhs.type();
    rhs.add_source_location()=function.source_location();
    rhs.function()=function;
    rhs.arguments()=arguments;

    code_assignt assignment(lhs, rhs);
    assignment.add_source_location()=function.source_location();
    copy(assignment, ASSIGN, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "array_set"))
  {
    do_array_set(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "array_equal" ||
          identifier=="__CPROVER::array_equal")
  {
    do_array_equal(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "array_copy" ||
          identifier=="__CPROVER::array_equal")
  {
    do_array_copy(lhs, function, arguments, dest);
  }
  else if(identifier=="printf")
  /*
          identifier=="fprintf" ||
          identifier=="sprintf" ||
          identifier=="snprintf")
  */
  {
    do_printf(lhs, function, arguments, dest);
  }
  else if(identifier=="__assert_fail" ||
          identifier=="_assert" ||
          identifier=="__assert_c99" ||
          identifier=="_wassert")
  {
    // __assert_fail is Linux
    // These take four arguments:
    // "expression", "file.c", line, __func__
    // klibc has __assert_fail with 3 arguments
    // "expression", "file.c", line

    // MingW has
    // void _assert (const char*, const char*, int);
    // with three arguments:
    // "expression", "file.c", line

    // This has been seen in Solaris 11.
    // Signature:
    // void __assert_c99(const char *desc, const char *file, int line, const char *func);

    // _wassert is Windows. The arguments are
    // L"expression", L"file.c", line

    if(arguments.size()!=4 &&
       arguments.size()!=3)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }
    
    const irep_idt description=
      "assertion "+id2string(get_string_constant(arguments[0]));

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier=="__assert_rtn" ||
          identifier=="__assert")
  {
    // __assert_rtn has been seen on MacOS;
    // __assert is FreeBSD and Solaris 11.
    // These take four arguments:
    // __func__, "file.c", line, "expression"
    // On Solaris 11, it's three arguments:
    // "expression", "file", line
    
    irep_idt description;
    
    if(arguments.size()==4)
    {
      description=
        "assertion "+id2string(get_string_constant(arguments[3]));
    }
    else if(arguments.size()==3)
    {
      description=
        "assertion "+id2string(get_string_constant(arguments[1]));
    }
    else
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier=="__assert_func")
  {
    // __assert_func is newlib (used by, e.g., cygwin)
    // These take four arguments:
    // "file.c", line, __func__, "expression"
    if(arguments.size()!=4)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }

    const irep_idt description=
      "assertion "+id2string(get_string_constant(arguments[3]));

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier==CPROVER_PREFIX "fence")
  {
    if(arguments.size()<1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have at least one argument";
    }

    goto_programt::targett t=dest.add_instruction(OTHER);
    t->source_location=function.source_location();
    t->code.set(ID_statement, ID_fence);

    forall_expr(it, arguments)
    {
      const irep_idt kind=get_string_constant(*it);
      t->code.set(kind, true);
    }
  }
  else if(identifier=="__builtin_prefetch")
예제 #14
0
void
main(int argc, char **argv)
{
    int c;
    int errflag = 0;
    char *progname;
    char *debug_file;
    char *dbname;
    char *command;
    int exit_status = 0;
    char errbuf[ERROR_MSG_LENGTH];
    char *username, usernamebuf[NAMEDATALEN + 1];

    char *pghost = NULL;
    char *pgtty = NULL;
    char *pgoptions = NULL;
    char *pgport = NULL;
    int  pgtracep = 0;

    /* 
     * Processing command line arguments.
     *
     * h : sets the hostname.
     * p : sets the coom. port
     * t : sets the tty.
     * o : sets the other options. (see doc/libpq)
     * d : enable debugging mode.
     * q : run in quiet mode
     * Q : run in VERY quiet mode (no output except on errors)
     * c : monitor will run one POSTQUEL command and exit
     *
     * s : step mode (pauses after each command)
     * S : don't use semi colon as \g
     *
     * T : terse mode - no formatting
     * N : no attribute names - only columns of data
     *     (these two options are useful in conjunction with the "-c" option
     *      in scripts.)
     */

    progname = *argv;
    Debugging = false;
    Verbose = true;
    Silent = false;

    /* prepend PGOPTION, if any */
    argsetup(&argc, &argv);

    while ((c = getopt(argc, argv, "a:h:f:p:t:d:qsSTNQc:")) != EOF) {
	switch (c) {
	    case 'a':
	      fe_setauthsvc(optarg, errbuf);
	      break;
	    case 'h' :
	      pghost = optarg;
	      break;
	    case 'f' :
	      RunOneFile = optarg;
	      break;
	    case 'p' :
	      pgport = optarg;
	      break;
	    case 't' :
	      pgtty = optarg;
	      break;
	    case 'T' :
	      TerseOutput = true;
	      break;
	    case 'N' :
	      PrintAttNames = false;
	      break;
	    case 'd' :

	      /*
	       *  When debugging is turned on, the debugging messages
	       *  will be sent to the specified debug file, which
	       *  can be a tty ..
	       */

	      Debugging = true;
	      debug_file = optarg;
	      debug_port = fopen(debug_file,"w+");
	      if (debug_port == NULL) {
		  fprintf(stderr,"Unable to open debug file %s \n", debug_file);
		  exit(1);
	      }
	      pgtracep = 1;
	      break;
	    case 'q' :
	      Verbose = false;
	      break;
	    case 's' :
	      SingleStepMode = true;
	      SemicolonIsGo = true;
	      break;
	    case 'S' :
	      SemicolonIsGo = false;
	      break;
	    case 'Q' :
	      Verbose = false;
	      Silent = true;
	      break;
	    case 'c' :
	      Verbose = false;
	      Silent = true;
	      RunOneCommand = true;
	      command = optarg;
	      break;
	    case '?' :
	    default :
	      errflag++;
	      break;
	}
    }

    if (errflag ) {
      fprintf(stderr, "usage: %s [options...] [dbname]\n", progname);
      fprintf(stderr, "\t-a authsvc\tset authentication service\n");
      fprintf(stderr, "\t-c command\t\texecute one command\n");
      fprintf(stderr, "\t-d debugfile\t\tdebugging output file\n");
      fprintf(stderr, "\t-h host\t\t\tserver host name\n");
      fprintf(stderr, "\t-f file\t\t\trun query from file\n");
      fprintf(stderr, "\t-p port\t\t\tserver port number\n");
      fprintf(stderr, "\t-q\t\t\tquiet output\n");
      fprintf(stderr, "\t-t logfile\t\terror-logging tty\n");
      fprintf(stderr, "\t-N\t\t\toutput without attribute names\n");
      fprintf(stderr, "\t-Q\t\t\tREALLY quiet output\n");
      fprintf(stderr, "\t-T\t\t\tterse output\n");
      exit(2);
    }

    /* Determine our username (according to the authentication system, if
     * there is one).
     */
    if ((username = fe_getauthname(errbuf)) == (char *) NULL) {
	    fprintf(stderr, "%s: could not find a valid user name\n",
		    progname);
	    exit(2);
    }
    memset(usernamebuf, 0, sizeof(usernamebuf));
    (void) strncpy(usernamebuf, username, NAMEDATALEN);
    username = usernamebuf;
    
    /* find database */
    if (!(dbname = argv[optind]) &&
	!(dbname = getenv("DATABASE")) &&
	!(dbname = username)) {
	    fprintf(stderr, "%s: no database name specified\n", progname);
	    exit (2);
    }

    conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbname);
    if (PQstatus(conn) == CONNECTION_BAD) {
      fprintf(stderr,"Connection to database '%s' failed.\n", dbname);
      fprintf(stderr,"%s",PQerrorMessage(conn));
      exit(1);
    }

    if (pgtracep)
      PQtrace(conn,debug_port);

    /* print out welcome message and start up */
    welcome();
    init_tmon(); 

    /* parse input */
    if (RunOneCommand) {
	exit_status = handle_execution(command);
    } else if (RunOneFile) {
	bool oldVerbose;
	FILE *ifp;

	if ((ifp = fopen(RunOneFile, "r")) == NULL) {
	    fprintf(stderr, "Cannot open %s\n", RunOneFile);
	}
	
	if (SingleStepMode) {
	    oldVerbose = Verbose;
	    Verbose = false;
	}
	do_input(ifp);
	fclose(ifp);
	if (SingleStepMode)
	    Verbose = oldVerbose;
    } else {
	do_input(stdin);
    }

    handle_exit(exit_status);
}
예제 #15
0
파일: mynano.c 프로젝트: mtawaken/gits
int main(int argc, char *argv[])
{
  getchar();

  setlocale(LC_ALL,""); //???
  ///////////////////////////////////////////////
  //init window

  //tcgetattr  

  //curses
  initscr();
  raw(); noecho();
  
  //window
  topwin = newwin(1,COLS,0,0);
  editwin = newwin(10,COLS,1,0);
  bottomwin = newwin(1,COLS,11,0);
  keypad(topwin, TRUE); keypad(editwin, TRUE); keypad(bottomwin, TRUE);

  //prompt
  start_color(); 
  init_pair(1, COLOR_RED, COLOR_BLACK);
  wattrset(topwin,COLOR_PAIR(1)); wattrset(bottomwin,COLOR_PAIR(1)); 
    //wattron?
  mvwprintw(topwin, 0, 0, "%s",    "-------------------mynano");
  mvwprintw(bottomwin, 0, 0, "%s", "-------------------CtrlX to exit");
  
  wrefresh(topwin); wrefresh(bottomwin); 
  
  //////////////////////////////////////////////////
  //init data
  funcstruct* func,*tmpfunc2;
    func = malloc(sizeof(funcstruct));
    func->func2 =&do_exit;
    func->seq = 'X'-64;  //无论是输入X还是x都触发
    func->next = NULL;
    tmpfunc2 = func;

    //ctrl_?与keyleft等的冲突?
    createfunc(&func,&tmpfunc2,(int)&do_backspace,8); //望8完8王 最后才得到王
    createfunc(&func,&tmpfunc2,(int)&do_backspace,KEY_BACKSPACE);
    createfunc(&func,&tmpfunc2,(int)&do_left,KEY_LEFT);
    createfunc(&func,&tmpfunc2,(int)&do_right,KEY_RIGHT);
    createfunc(&func,&tmpfunc2,(int)&do_delete,KEY_DC);
    createfunc(&func,&tmpfunc2,(int)&do_enter,'\n');
    createfunc(&func,&tmpfunc2,(int)&do_up,KEY_UP);
    createfunc(&func,&tmpfunc2,(int)&do_down,KEY_DOWN);
    
    funcs=func;

  //if args then readfile
  if (argc>1) 
     readfile(argv[1]);
  else
  {
    curline=malloc(sizeof(linestruct));
    memset(curline,0,sizeof(linestruct));
    curline->pdata_x=curline->data = malloc(1); memset(curline->data,0,1); 
  }

  //output
  wmove(editwin,0,0); //为何光标跑到了bottomwin?
  wrefresh(editwin);
  //////////////////////////////////////////////////
  //main
  int cInput; 
  while(true)
  {
    cInput = do_input();
    do_output(cInput);
  }
  
  exit(0); 
}
예제 #16
0
파일: tty.c 프로젝트: Hooman3/minix
/*===========================================================================*
 *				tty_task				     *
 *===========================================================================*/
int main(void)
{
/* Main routine of the terminal task. */

  message tty_mess;		/* buffer for all incoming messages */
  int ipc_status;
  int line;
  int r;
  register tty_t *tp;

  /* SEF local startup. */
  sef_local_startup();
  while (TRUE) {
	/* Check for and handle any events on any of the ttys. */
	for (tp = FIRST_TTY; tp < END_TTY; tp++) {
		if (tp->tty_events) handle_events(tp);
	}

	/* Get a request message. */
	r= driver_receive(ANY, &tty_mess, &ipc_status);
	if (r != 0)
		panic("driver_receive failed with: %d", r);

	/* First handle all kernel notification types that the TTY supports. 
	 *  - An alarm went off, expire all timers and handle the events. 
	 *  - A hardware interrupt also is an invitation to check for events. 
	 *  - A new kernel message is available for printing.
	 *  - Reset the console on system shutdown. 
	 * Then see if this message is different from a normal device driver
	 * request and should be handled separately. These extra functions
	 * do not operate on a device, in constrast to the driver requests. 
	 */

	if (is_ipc_notify(ipc_status)) {
		switch (_ENDPOINT_P(tty_mess.m_source)) {
			case CLOCK:
				/* run watchdogs of expired timers */
				expire_timers(tty_mess.m_notify.timestamp);
				break;
			case HARDWARE: 
				/* hardware interrupt notification */

#if NR_RS_LINES > 0
				/* serial I/O */
				if (tty_mess.m_notify.interrupts & rs_irq_set)
					rs_interrupt(&tty_mess);
#endif
				/* run watchdogs of expired timers */
				expire_timers(tty_mess.m_notify.timestamp);
				break;
			default:
				/* do nothing */
				break;
		}

		/* done, get new message */
		continue;
	}

	switch (tty_mess.m_type) { 
	case TTY_FKEY_CONTROL:		/* (un)register a fkey observer */
		do_fkey_ctl(&tty_mess);
		continue;
	case TTY_INPUT_UP:
	case TTY_INPUT_EVENT:
		do_input(&tty_mess);
		continue;
	default:			/* should be a driver request */
		;			/* do nothing; end switch */
	}

	if (!IS_CDEV_RQ(tty_mess.m_type)) {
		chardriver_process(&tty_tab, &tty_mess, ipc_status);
		continue;
	}

	/* Only device requests should get to this point.
	 * All requests have a minor device number.
	 */
	if (OK != chardriver_get_minor(&tty_mess, &line))
		continue;

	if (line == VIDEO_MINOR) {
		do_video(&tty_mess, ipc_status);
		continue;
	}

	/* Execute the requested device driver function. */
	chardriver_process(&tty_tab, &tty_mess, ipc_status);
  }

  return 0;
}
예제 #17
0
파일: main.c 프로젝트: WndSks/msys
int
main(int argc, char **argv)
{
	int c;
	char *scan;
	/* the + on the front tells GNU getopt not to rearrange argv */
	const char *optlist = "+F:f:v:W;m:D";
	int stopped_early = FALSE;
	int old_optind;
	extern int optind;
	extern int opterr;
	extern char *optarg;
	int i;
	int stdio_problem = FALSE;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_tidy_mem = TRUE;

	if (getenv("WHINY_USERS") != NULL)
		whiny_users = TRUE;

#ifdef HAVE_MCHECK_H
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MCHECK_H */
	
#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#ifdef MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
	(void) signal(SIGSEGV, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif

	myname = gawk_name(argv[0]);
        argv[0] = (char *) myname;
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	/* remove sccs gunk */
	if (strncmp(version_string, "@(#)", 4) == 0)
		version_string += 4;

	if (argc < 2)
		usage(1, stderr);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* we do error messages ourselves on invalid options */
	opterr = FALSE;

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = TRUE;

		switch (c) {
		case 'F':
			preassigns_add(PRE_ASSIGN_FS, optarg);
			break;

		case 'S':
			disallow_var_assigns = TRUE;
			/* fall through */
		case 'f':
			/*
			 * a la MKS awk, allow multiple -f options.
			 * this makes function libraries real easy.
			 * most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (ISSPACE(*scan))
					scan++;
			srcfiles_add(SOURCEFILE,
				(*scan == '\0' ? argv[optind++] : optarg));
			break;

		case 'v':
			preassigns_add(PRE_ASSIGN, optarg);
			break;

		case 'm':
			/*
			 * Research awk extension.
			 *	-mf nnn		set # fields, gawk ignores
			 *	-mr nnn		set record length, ditto
			 */
			if (do_lint)
				lintwarn(_("`-m[fr]' option irrelevant in gawk"));
			if (optarg[0] != 'r' && optarg[0] != 'f')
				warning(_("-m option usage: `-m[fr] nnn'"));
			/*
			 * Set fixed length records for Tandem,
			 * ignored on other platforms (see io.c:get_a_record).
			 */
			if (optarg[0] == 'r') {
				if (ISDIGIT(optarg[1]))
					MRL = atoi(optarg+1);
				else {
					MRL = atoi(argv[optind]);
					optind++;
				}
			} else if (optarg[1] == '\0')
				optind++;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		/* These can only come from long form options */
		case 'C':
			copyleft();
			break;

		case 'd':
			do_dump_vars = TRUE;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'l':
#ifndef NO_LINT
			do_lint = LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0)
					do_lint = LINT_INVALID;
			}
#endif
			break;

		case 'p':
			do_profiling = TRUE;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 's':
			if (optarg[0] == '\0')
				warning(_("empty argument to `--source' ignored"));
			else
				srcfiles_add(CMDLINE, optarg);
			break;

		case 'u':
			usage(0, stdout);	/* per coding stds */
			break;

		case 'V':
			version();
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'D':
#ifdef GAWKDEBUG
			yydebug = 2;
			break;
#endif
			/* if not debugging, fall through */

		case '?':
		default:
			/*
			 * New behavior.  If not posix, an unrecognized
			 * option stops argument processing so that it can
			 * go into ARGV for the awk program to see. This
			 * makes use of ``#! /bin/gawk -f'' easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = TRUE;
				goto out;
			} else if (optopt != '\0')
				/* Use 1003.2 required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'S')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_posix = TRUE;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_traditional = TRUE;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_non_decimal_data = FALSE;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

	/*
	 * Force profiling if this is pgawk.
	 * Don't bother if the command line already set profiling up.
	 */
	if (! do_profiling)
		init_profiling(& do_profiling, DEFAULT_PROFILE);

	/* load group set */
	init_groupset();

	/* initialize the null string */
	Nnull_string = make_string("", 0);
	Nnull_string->numbr = 0.0;
	Nnull_string->type = Node_val;
	Nnull_string->flags = (PERM|STRCUR|STRING|NUMCUR|NUMBER);

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++)
		if (preassigns[i].stype == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, TRUE);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
	free(preassigns);

	if ((BINMODE & 1) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & 2) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (isatty(fileno(stdout)))
		output_is_tty = TRUE;
	/* No -f or --source options, use next arg */
	if (numfiles == -1) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(1, stderr);
		srcfiles_add(CMDLINE, argv[optind]);
		optind++;
	}

	init_args(optind, argc, (char *) myname, argv);
	(void) tokexpand();

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif

	/* Read in the program */
	if (yyparse() != 0 || errcount != 0)
		exit(1);

	free(srcfiles);

	if (do_intl)
		exit(0);

	if (do_lint && begin_block == NULL && expression_value == NULL
	     && end_block == NULL)
		lintwarn(_("no program text at all!"));

	if (do_lint)
		shadow_funcs();

	init_profiling_signals();

#if defined(LC_NUMERIC)
	/* See comment above. */
	setlocale(LC_NUMERIC, "");
#endif

#if defined(HAVE_LOCALE_H)
	loc = *localeconv();	/* Make a local copy of locale numeric info */
#endif

	/* Whew. Finally, run the program. */
	if (begin_block != NULL) {
		in_begin_rule = TRUE;
		(void) interpret(begin_block);
	}
	in_begin_rule = FALSE;
	if (! exiting && (expression_value != NULL || end_block != NULL))
		do_input();
	if (end_block != NULL) {
		in_end_rule = TRUE;
		(void) interpret(end_block);
	}
	in_end_rule = FALSE;
	/*
	 * This used to be:
	 *
	 * if (close_io() != 0 && ! exiting && exit_val == 0)
	 * 	exit_val = 1;
	 *
	 * Other awks don't care about problems closing open files
	 * and pipes, in that it doesn't affect their exit status.
	 * So we no longer do either.
	 */
	(void) close_io(& stdio_problem);
	/*
	 * However, we do want to exit non-zero if there was a problem
	 * with stdout/stderr, so we reinstate a slightly different
	 * version of the above:
	 */
	if (stdio_problem && ! exiting && exit_val == 0)
		exit_val = 1;

	if (do_profiling) {
		dump_prog(begin_block, expression_value, end_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();

	exit(exit_val);		/* more portable */
	return exit_val;	/* to suppress warnings */
}