Exemplo n.º 1
0
int
main(int argc, char **argv)
{
    FBIO *fbp;
    unsigned char *scan_buf;
    int y;
    int cm_save_needed;

    outrle.rle_file = stdout;
    if (!get_args(argc, argv)) {
	(void)fputs(usage, stderr);
	bu_exit(1, NULL);
    }

    /* If screen size = default & file size is given, track file size */
    if (screen_width == 0 && file_width > 0)
	screen_width = file_width;
    if (screen_height == 0 && file_height > 0)
	screen_height = file_height;

    if ((fbp = fb_open(framebuffer, screen_width, screen_height)) == FBIO_NULL)
	bu_exit(12, NULL);

    /* Honor original screen size desires, if set, unless they shrank */
    if (screen_width == 0 || fb_getwidth(fbp) < screen_width)
	screen_width = fb_getwidth(fbp);
    if (screen_height == 0 || fb_getheight(fbp) < screen_height)
	screen_height = fb_getheight(fbp);

    /* If not specified, output file size tracks screen size */
    if (file_width == 0)
	file_width = screen_width;
    if (file_height == 0)
	file_height = screen_height;

    /* Clip below and to left of (0, 0) */
    if (screen_xoff < 0) {
	file_width += screen_xoff;
	screen_xoff = 0;
    }
    if (screen_yoff < 0) {
	file_height += screen_yoff;
	screen_yoff = 0;
    }

    /* Clip up and to the right */
    if (screen_xoff + file_width > screen_width)
	file_width = screen_width - screen_xoff;
    if (screen_yoff + file_height > screen_height)
	file_height = screen_height - screen_yoff;

    if (file_width <= 0 || file_height <= 0) {
	fprintf(stderr,
		"fb-rle: Error: image rectangle entirely off screen\n");
	bu_exit(1, NULL);
    }

    /* Read color map, see if it is linear */
    cm_save_needed = 1;
    if (fb_rmap(fbp, &cmap) == -1)
	cm_save_needed = 0;
    if (cm_save_needed && fb_is_linear_cmap(&cmap))
	cm_save_needed = 0;
    if (crunch && (cm_save_needed == 0))
	crunch = 0;

    /* Convert to Utah format */
    if (cm_save_needed) for (y=0; y<256; y++) {
	    rlemap[y+0*256] = cmap.cm_red[y];
	    rlemap[y+1*256] = cmap.cm_green[y];
	    rlemap[y+2*256] = cmap.cm_blue[y];
	}

    scan_buf = (unsigned char *)malloc(sizeof(RGBpixel) * screen_width);

    /* Build RLE header */
    outrle.ncolors = 3;
    RLE_SET_BIT(outrle, RLE_RED);
    RLE_SET_BIT(outrle, RLE_GREEN);
    RLE_SET_BIT(outrle, RLE_BLUE);
    outrle.background = 2;		/* use background */
    outrle.bg_color = background;
    outrle.alpha = 0;			/* no alpha channel */
    if (cm_save_needed && !crunch) {
	outrle.ncmap = 3;
	outrle.cmaplen = 8;		/* 1<<8 = 256 */
	outrle.cmap = rlemap;
    } else {
	outrle.ncmap = 0;		/* no color map */
	outrle.cmaplen = 0;
	outrle.cmap = (rle_map *)0;
    }
    outrle.xmin = screen_xoff;
    outrle.ymin = screen_yoff;
    outrle.xmax = screen_xoff + file_width - 1;
    outrle.ymax = screen_yoff + file_height - 1;
    outrle.comments = (const char **)0;

    /* Add comments to the header file, since we have one */
    if (framebuffer == (char *)0)
	framebuffer = fbp->if_name;
    snprintf(comment, COMMENT_SIZE, "encoded_from=%s", framebuffer);
    rle_putcom(bu_strdup(comment), &outrle);
    now = time(0);
    snprintf(comment, COMMENT_SIZE, "encoded_date=%24.24s", ctime(&now));
    rle_putcom(bu_strdup(comment), &outrle);
    if ((who = getenv("USER")) != (char *)0) {
	snprintf(comment, COMMENT_SIZE, "encoded_by=%s", who);
	rle_putcom(bu_strdup(comment), &outrle);
    }
# if HAVE_GETHOSTNAME
    gethostname(host, sizeof(host));
    snprintf(comment, COMMENT_SIZE, "encoded_host=%s", host);
    rle_putcom(bu_strdup(comment), &outrle);
# endif

    rle_put_setup(&outrle);
    rle_row_alloc(&outrle, &rows);

    /* Read the image a scanline at a time, and encode it */
    for (y = 0; y < file_height; y++) {
	if (fb_read(fbp, screen_xoff, y+screen_yoff, scan_buf,
		    file_width) == -1) {
	    (void) fprintf(stderr,
			   "fb-rle: read of %d pixels on line %d failed!\n",
			   file_width, y+screen_yoff);
	    bu_exit(1, NULL);
	}

	if (crunch)
	    cmap_crunch((RGBpixel *)scan_buf, file_width, &cmap);

	/* Grumble, convert to Utah layout */
	{
	    unsigned char *pp = (unsigned char *)scan_buf;
	    rle_pixel *rp = rows[0];
	    rle_pixel *gp = rows[1];
	    rle_pixel *bp = rows[2];
	    int i;

	    for (i=0; i<file_width; i++) {
		*rp++ = *pp++;
		*gp++ = *pp++;
		*bp++ = *pp++;
	    }
	}
	rle_putrow(rows, file_width, &outrle);
    }
    rle_puteof(&outrle);

    fb_close(fbp);
    fclose(outrle.rle_file);
    return 0;
}
Exemplo n.º 2
0
int
main(int argc, char **argv) {

    if (argc == 2 && strcmp(argv[1], "adbd") == 0) {
        adb_main();
        return 0;
    }

    // Recovery needs to install world-readable files, so clear umask
    // set by init
    umask(0);

    if (strcmp(basename(argv[0]), "recovery") != 0)
    {
        if (strstr(argv[0], "minizip") != NULL)
            return minizip_main(argc, argv);
        if (strstr(argv[0], "dedupe") != NULL)
            return dedupe_main(argc, argv);
        if (strstr(argv[0], "flash_image") != NULL)
            return flash_image_main(argc, argv);
        if (strstr(argv[0], "volume") != NULL)
            return volume_main(argc, argv);
        if (strstr(argv[0], "edify") != NULL)
            return edify_main(argc, argv);
        if (strstr(argv[0], "dump_image") != NULL)
            return dump_image_main(argc, argv);
        if (strstr(argv[0], "erase_image") != NULL)
            return erase_image_main(argc, argv);
        if (strstr(argv[0], "mkyaffs2image") != NULL)
             return mkyaffs2image_main(argc, argv);
        if (strstr(argv[0], "make_ext4fs") != NULL)
            return make_ext4fs_main(argc, argv);
        if (strstr(argv[0], "unyaffs") != NULL)
            return unyaffs_main(argc, argv);
        if (strstr(argv[0], "nandroid"))
            return nandroid_main(argc, argv);
        if (strstr(argv[0], "bu") == argv[0] + strlen(argv[0]) - 2)
            return bu_main(argc, argv);
        if (strstr(argv[0], "reboot"))
            return reboot_main(argc, argv);
#ifdef BOARD_RECOVERY_HANDLES_MOUNT
        if (strstr(argv[0], "mount") && argc == 2 && !strstr(argv[0], "umount"))
        {
            load_volume_table();
            return ensure_path_mounted(argv[1]);
        }
#endif
        if (strstr(argv[0], "poweroff")){
            return reboot_main(argc, argv);
        }
        if (strstr(argv[0], "setprop"))
            return setprop_main(argc, argv);
        if (strstr(argv[0], "getprop"))
            return getprop_main(argc, argv);
        return busybox_driver(argc, argv);
    }
    __system("/sbin/postrecoveryboot.sh");

    int is_user_initiated_recovery = 0;
    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
    printf("Starting recovery on %s", ctime(&start));

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_VERSION)"\n");
    load_volume_table();
    process_volumes();
    LOGI("Processing arguments.\n");
    get_args(&argc, &argv);

    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0;
    int sideload = 0;

    LOGI("Checking arguments.\n");
    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': 
#ifndef BOARD_RECOVERY_ALWAYS_WIPES
        wipe_data = wipe_cache = 1;
#endif
        break;
        case 'c': wipe_cache = 1; break;
        case 't': ui_show_text(1); break;
        case 'l': sideload = 1; break;
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    struct selinux_opt seopts[] = {
      { SELABEL_OPT_PATH, "/file_contexts" }
    };

    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);

    if (!sehandle) {
        fprintf(stderr, "Warning: No file_contexts\n");
        // ui_print("Warning:  No file_contexts\n");
    }

    LOGI("device_recovery_start()\n");
    device_recovery_start();

    printf("Command:");
    for (arg = 0; arg < argc; arg++) {
        printf(" \"%s\"", argv[arg]);
    }
    printf("\n");

    if (update_package) {
        // For backwards compatibility on the cache partition only, if
        // we're given an old 'root' path "CACHE:foo", change it to
        // "/cache/foo".
        if (strncmp(update_package, "CACHE:", 6) == 0) {
            int len = strlen(update_package) + 10;
            char* modified_path = malloc(len);
            strlcpy(modified_path, "/cache/", len);
            strlcat(modified_path, update_package+6, len);
            printf("(replacing path \"%s\" with \"%s\")\n",
                   update_package, modified_path);
            update_package = modified_path;
        }
    }
    printf("\n");

    property_list(print_property, NULL);
    printf("\n");

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        status = install_package(update_package);
        if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        if (erase_volume("/data")) status = INSTALL_ERROR;
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
    } else if (sideload) {
        signature_check_enabled = 0;
        ui_set_show_text(1);
        if (0 == apply_from_adb()) {
            status = INSTALL_SUCCESS;
            ui_set_show_text(0);
        }
    } else {
        LOGI("Checking for extendedcommand...\n");
        status = INSTALL_ERROR;  // No command specified
        // we are starting up in user initiated recovery here
        // let's set up some default options
        signature_check_enabled = 0;
        script_assert_enabled = 0;
        is_user_initiated_recovery = 1;
        ui_set_show_text(1);
        ui_set_background(BACKGROUND_ICON_CLOCKWORK);
        
        if (extendedcommand_file_exists()) {
            LOGI("Running extendedcommand...\n");
            int ret;
            if (0 == (ret = run_and_remove_extendedcommand())) {
                status = INSTALL_SUCCESS;
                ui_set_show_text(0);
            }
            else {
                handle_failure(ret);
            }
        } else {
            LOGI("Skipping execution of extendedcommand, file not found...\n");
        }
    }

    setup_adbd();

    if (status != INSTALL_SUCCESS && !is_user_initiated_recovery) {
        ui_set_show_text(1);
        ui_set_background(BACKGROUND_ICON_ERROR);
    }
    if (status != INSTALL_SUCCESS || ui_text_visible()) {
        prompt_and_wait();
    }

    verify_root_and_recovery();

    // If there is a radio image pending, reboot now to install it.
    maybe_install_firmware_update(send_intent);

    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);

    sync();
    if(!poweroff) {
        ui_print("Rebooting...\n");
        android_reboot(ANDROID_RB_RESTART, 0, 0);
    }
    else {
        ui_print("Shutting down...\n");
        android_reboot(ANDROID_RB_POWEROFF, 0, 0);
    }
    return EXIT_SUCCESS;
}
Exemplo n.º 3
0
int
main(int argc, char **argv) {
	if (strcmp(basename(argv[0]), "recovery") != 0)
	{
        if (strstr(argv[0], "flash_image") != NULL)
            return flash_image_main(argc, argv);
        if (strstr(argv[0], "dump_image") != NULL)
            return dump_image_main(argc, argv);
        if (strstr(argv[0], "erase_image") != NULL)
            return erase_image_main(argc, argv);
        if (strstr(argv[0], "mkyaffs2image") != NULL)
            return mkyaffs2image_main(argc, argv);
        if (strstr(argv[0], "unyaffs") != NULL)
            return unyaffs_main(argc, argv);
        if (strstr(argv[0], "nandroid"))
            return nandroid_main(argc, argv);
        if (strstr(argv[0], "reboot"))
            return reboot_main(argc, argv);
#ifdef BOARD_RECOVERY_HANDLES_MOUNT
        if (strstr(argv[0], "mount") && argc == 2 && !strstr(argv[0], "umount"))
        {
            load_volume_table();
            return ensure_path_mounted(argv[1]);
        }
#endif
        if (strstr(argv[0], "poweroff")){
            return reboot_main(argc, argv);
        }
    }
	__system("/sbin/postrecoveryboot.sh");

    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
#ifndef DEBUG
    unlink(TEMPORARY_LOG_FILE);
#endif

    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
    printf("Starting recovery on %s", ctime(&start));
    //miuiIntent init
    miuiIntent_init(10);
    miuiIntent_register(INTENT_MOUNT, &intent_mount);
    miuiIntent_register(INTENT_ISMOUNT, &intent_ismount);
    miuiIntent_register(INTENT_UNMOUNT, &intent_unmount);
    miuiIntent_register(INTENT_REBOOT, &intent_reboot);
    miuiIntent_register(INTENT_INSTALL, &intent_install);
    miuiIntent_register(INTENT_WIPE, &intent_wipe);
    miuiIntent_register(INTENT_TOGGLE, &intent_toggle);
    miuiIntent_register(INTENT_FORMAT, &intent_format);
    miuiIntent_register(INTENT_RESTORE, &intent_restore);
    miuiIntent_register(INTENT_BACKUP, &intent_backup);
    miuiIntent_register(INTENT_ADVANCED_BACKUP, &intent_advanced_backup);
    miuiIntent_register(INTENT_SYSTEM, &intent_system);
    miuiIntent_register(INTENT_COPY, &intent_copy);
    device_ui_init();
    load_volume_table();
    get_args(&argc, &argv);

    struct bootloader_message boot;
    memset(&boot, 0, sizeof(boot));
    set_bootloader_message(&boot);
	create_fstab();
    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0;

    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': wipe_data = wipe_cache = 1; break;
        case 'c': wipe_cache = 1; break;
        //case 't': ui_show_text(1); break;
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    device_recovery_start();

    printf("Command:");
    for (arg = 0; arg < argc; arg++) {
        printf(" \"%s\"", argv[arg]);
    }
    printf("\n");

    if (update_package) {
        // For backwards compatibility on the cache partition only, if
        // we're given an old 'root' path "CACHE:foo", change it to
        // "/cache/foo".
        if (strncmp(update_package, "CACHE:", 6) == 0) {
            int len = strlen(update_package) + 10;
            char* modified_path = malloc(len);
            strlcpy(modified_path, "/cache/", len);
            strlcat(modified_path, update_package+6, len);
            printf("(replacing path \"%s\" with \"%s\")\n",
                   update_package, modified_path);
            update_package = modified_path;
        }
    }
    printf("\n");

    property_list(print_property, NULL);
    printf("\n");

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        if (wipe_cache) erase_volume("/cache");
        miuiIntent_send(INTENT_INSTALL, 3, update_package,"0", "0");
        //if echo 0 ,don't print success dialog 
        status = miuiIntent_result_get_int();
        if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        if (erase_volume("/data")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
    } else {
        status = INSTALL_ERROR;  // No command specified
    }
    if (status != INSTALL_SUCCESS) device_main_ui_show();//show menu
    device_main_ui_release();
    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);
    ui_print("Rebooting...\n");
    android_reboot(ANDROID_RB_RESTART, 0, 0);
    return EXIT_SUCCESS;
}
Exemplo n.º 4
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	snd_seq_event_t ev;
	struct input_event iev;
	snd_seq_addr_t addr;

	fprintf( stderr, "lsmi-mouse" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Initializing mouse interface...\n" );

	if ( -1 == ( fd = open( device, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		exit(1);
	}

	init_mouse();

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME  );
	port = open_output_port( seq );

	if ( sub_name )
	{
		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}
	
	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	set_traps();

	fprintf( stderr, "Waiting for packets...\n" );

	for ( ;; )
	{
		int i;

		read( fd, &iev, sizeof( iev ) );

		if ( iev.type != EV_KEY )
			continue;

		switch ( iev.code )
		{
			case BTN_LEFT:		i = 0; break;
			case BTN_MIDDLE:	i = 1; break;
			case BTN_RIGHT:		i = 2; break;
				break;
			default:
				continue;
				break;
		}

		snd_seq_ev_clear( &ev );

		switch ( ev.type = map[i].ev_type )
		{
			case SND_SEQ_EVENT_CONTROLLER:

				snd_seq_ev_set_controller( &ev, map[i].channel,
												map[i].number,
												iev.value == DOWN ? 127 : 0 );
				break;

			case SND_SEQ_EVENT_NOTEON:
				
				snd_seq_ev_set_noteon( &ev, map[i].channel,
											map[i].number,
											iev.value == DOWN ? 127 : 0 );
				break;

			default:
				fprintf( stderr,
						 "Internal error: invalid mapping!\n" );
				continue;
				break;
		}

		send_event( &ev );
	}
}
Exemplo n.º 5
0
int
main(int argc, char **argv) {
//    while(1);
	time_t start = time(NULL);
	// If these fail, there's not really anywhere to complain...
	freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
	freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
	//    printf("Starting recovery on %s", ctime(&start));
//	printf("............just for aibing debug \n\r");
//	while(1);
	ui_init();
	//    ui_set_background(BACKGROUND_ICON_INSTALLING);
	load_volume_table();
	get_args(&argc, &argv);

	int previous_runs = 0;
	const char *send_intent = NULL;
	const char *update_package = NULL;
	const char *encrypted_fs_mode = NULL;
	int wipe_data = 0, wipe_cache = 0;
	int toggle_secure_fs = 0;
	encrypted_fs_info encrypted_fs_data; 
	int arg;
	while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
		switch (arg) {
			case 'p': previous_runs = atoi(optarg); break;
			case 's': send_intent = optarg; break;
			case 'u': update_package = optarg; break;
			case 'w': wipe_data = wipe_cache = 1; break;
			case 'c': wipe_cache = 1; break;
			case 'e': encrypted_fs_mode = optarg; toggle_secure_fs = 1; break;
			case 't': ui_show_text(1); break;
			case '?':
				  LOGE("Invalid command argument\n");
				  continue;
		}
	}
	//reinit wipe_data and wipe_cache as it will do in clean boot;
	wipe_data = wipe_cache = 0;

	device_recovery_start();

	printf("Aibing test Command:");
	for (arg = 0; arg < argc; arg++) {
		printf(" \"%s\"", argv[arg]);
	}
	printf("\n");
	if (update_package) {
		printf("in update_package run?????\n");
		// For backwards compatibility on the cache partition only, if
		// we're given an old 'root' path "CACHE:foo", change it to
		// "/cache/foo".
		if (strncmp(update_package, "CACHE:", 6) == 0) {
			int len = strlen(update_package) + 10;
			char* modified_path = malloc(len);
			strlcpy(modified_path, "/cache/", len);
			strlcat(modified_path, update_package+6, len);
			printf("(replacing path \"%s\" with \"%s\")\n",
					update_package, modified_path);
			update_package = modified_path;
		}
	}
	printf("list start\n");

	property_list(print_property, NULL);
	printf("list end\n");

	int status = INSTALL_SUCCESS;
	int mcu_status = INSTALL_SUCCESS;
	int mpeg_status = INSTALL_SUCCESS;
	int overridekey_status = INSTALL_SUCCESS;
	int tractor_prop_status = INSTALL_SUCCESS;
	int radio_status = INSTALL_SUCCESS;
	if (toggle_secure_fs) {
		if (strcmp(encrypted_fs_mode,"on") == 0) {
			encrypted_fs_data.mode = MODE_ENCRYPTED_FS_ENABLED;
			printf("Enabling Encrypted FS.\n");
		} else if (strcmp(encrypted_fs_mode,"off") == 0) {
			encrypted_fs_data.mode = MODE_ENCRYPTED_FS_DISABLED;
			printf("Disabling Encrypted FS.\n");
		} else {
			printf("Error: invalid Encrypted FS setting.\n");
			status = INSTALL_ERROR;
		}

		// Recovery strategy: if the data partition is damaged, disable encrypted file systems.
		// This preventsthe device recycling endlessly in recovery mode.
		if ((encrypted_fs_data.mode == MODE_ENCRYPTED_FS_ENABLED) &&
				(read_encrypted_fs_info(&encrypted_fs_data))) {
			printf("Encrypted FS change aborted, resetting to disabled state.\n");
			encrypted_fs_data.mode = MODE_ENCRYPTED_FS_DISABLED;
		}

		if (status != INSTALL_ERROR) {
			if (erase_volume("/data")) {
				printf("Data wipe failed.\n");
				status = INSTALL_ERROR;
			} else if (erase_volume("/cache")) {
				printf("Cache wipe failed.\n");
				status = INSTALL_ERROR;
			} else if ((encrypted_fs_data.mode == MODE_ENCRYPTED_FS_ENABLED) &&
					(restore_encrypted_fs_info(&encrypted_fs_data))) {
				printf("Encrypted FS change aborted.\n");
				status = INSTALL_ERROR;
			} else {
				printf("Successfully updated Encrypted FS.\n");
				status = INSTALL_SUCCESS;
			}
		}
	} else if (update_package != NULL) {
		status = install_package(update_package);
		if (status != INSTALL_SUCCESS) printf("Installation aborted.\n");
	} else if (wipe_data) {
		if (device_wipe_data()) status = INSTALL_ERROR;
		if (erase_volume("/data")) status = INSTALL_ERROR;
		if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
		if (status != INSTALL_SUCCESS) printf("Data wipe failed.\n");
	} else if (wipe_cache) {
		if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
		if (status != INSTALL_SUCCESS) printf("Cache wipe failed.\n");
	} else {
		status = INSTALL_ERROR;  // No command specified
	}
	
	printf("Recovery svn version:%d, Compile Time: %s %s\n", 
			SVN_VERSION,__DATE__,  __TIME__);
	sprintf(version_buf, "Recovery svn version:%d, Compile Time: %s %s", 
			SVN_VERSION,__TIME__, __DATE__);
	
	int fd = 0;
	fd = open("/dev/recovery",O_RDWR | O_CREAT | O_TRUNC);
	if(fd < 0) {
		printf("open recovery devices error\n");
		return EXIT_SUCCESS;
	} 
	
	int recovery_mode = 0;
	ioctl(fd, RECOVERY_GET_VAL, &recovery_mode);
//	recovery_mode = UPDATE_SYSTEM;

	/*	test_functions()  */
	//remove_logo_config_file();

	if(recovery_mode == CLEAN_MODE) {
		ui_set_cleanboot_background();
		ui_set_cleanboot_system();
		clean_boot();
		while(system_cleanboot_end == 0) {
			//printf("waiting thread is end");
			usleep(50000);
		}
		sync();
		ui_set_cleanboot_succ();
		sleep(3);
		close_backlight();
		reboot(RB_AUTOBOOT);
		printf("reboot end, it should never been output\n");
	} else if (recovery_mode == UPDATE_RECOVERY){
		ui_set_prepare_background();
		sleep(1);
		burning_recovery_image();
	} else if (recovery_mode == UPDATE_SYSTEM  || recovery_mode == BACKUP_MODE){
		ui_set_burning_background(BURNING_MISC_UPDATING);
		sleep(1);
		overridekey_status = update_overridekey();
		tractor_prop_status = update_tractorprop();
		radio_status = update_radioCFG();
		mpeg_status = mpeg_update();
		update_status &= ~(0x03 << 2);
		update_status |= mpeg_status << 2;
		ui_set_burning_reflesh(update_status);
		sleep(1);
		printf("mcu_start\n");
		mcu_status = mcu_update();		
		update_status &= ~(0x03 << 4);
		update_status |= (mcu_status << 4);
		ui_set_burning_reflesh(update_status);
		sleep(1);
		if(status == INSTALL_ERROR){
			printf("++check auto Burning update.zip in data tractor...\n");
			status = device_burn_data_if_exist();
			if(status == INSTALL_SUCCESS) {
				//burning_recovery_image();
			}
			ui_set_burning_status();
			printf("--check auto Burning update.zip in data tractor: %d\n", status);	 
			update_status &= ~(0x03);
			update_status |= status;
		}
		ui_set_burning_reflesh(update_status);
		sleep(3);
/*		
		if ( (mcu_status == INSTALL_SUCCESS) ||
				(status == INSTALL_SUCCESS)  || 
				(mpeg_status == INSTALL_SUCCESS)||
				(overridekey_status == INSTALL_SUCCESS)) {
			if (set_skip() == INSTALL_ERROR) {
				ui_set_burning_background(BURNING_RESULT_FAILURE);
				sleep(3);
				mcu_reset_cpu();
				return EXIT_FAILURE;
			}
		}
*/
		printf("end \n");
		if ( (status != INSTALL_SUCCESS) && 
				(mcu_status != INSTALL_SUCCESS) &&
				(mpeg_status != INSTALL_SUCCESS) && 
				(overridekey_status != INSTALL_SUCCESS)&& 
				(radio_status != INSTALL_SUCCESS)) {
			ui_set_burning_background(BURNING_RESULT_FAILURE);
			sleep(3);
			mcu_reset_cpu();
			return EXIT_FAILURE;
		}
		sync();
		ui_set_burning_background(BURNING_RESULT_SUCCESS);
		sleep(3);
		//while mcu is burning,  the mcu need to restart and reset the main cpu. 
		if (mcu_status == INSTALL_SUCCESS) {
			mcu_reset_cpu();
		} else {
			close_backlight();
			reboot(RB_AUTOBOOT);
		}
	}while(0);
	return EXIT_SUCCESS;
}
int
main(int argc, char **argv)
{
#define PORTSZ 32
    char	portname[PORTSZ];

    max_fd = 0;

    /* No disk files on remote machine */
    _fb_disk_enable = 0;
    memset((void *)clients, 0, sizeof(struct pkg_conn *) * MAX_CLIENTS);

#ifdef SIGALRM
    (void)signal( SIGPIPE, SIG_IGN );
    (void)signal( SIGALRM, sigalarm );
#endif
    /*alarm(1)*/

    FD_ZERO(&select_list);
    fb_server_select_list = &select_list;
    fb_server_max_fd = &max_fd;

#ifndef _WIN32
    /*
     * Inetd Daemon.
     * Check to see if we were invoked by /etc/inetd.  If so
     * we will have an open network socket on fd=0.  Become
     * a Transient PKG server if this is so.
     */
    netfd = 0;
    if ( is_socket(netfd) ) {
	init_syslog();
	new_client( pkg_transerver( fb_server_pkg_switch, comm_error ) );
	max_fd = 8;
	once_only = 1;
	main_loop();
	return 0;
    }
#endif

    /* for now, make them set a port_num, for usage message */
    if ( !get_args( argc, argv ) || !port_set ) {
	(void)fputs(usage, stderr);
	return 1;
    }

    /* Single-Frame-Buffer Server */
    if ( framebuffer != NULL ) {
	fb_server_retain_on_close = 1;	/* don't ever close the frame buffer */

	/* open a frame buffer */
	if ( (fb_server_fbp = fb_open(framebuffer, width, height)) == FB_NULL )
	    bu_exit(1, NULL);
	max_fd = fb_set_fd(fb_server_fbp, &select_list);

	/* check/default port */
	if ( port_set ) {
	    if ( port < 1024 )
		port += 5559;
	}
	snprintf(portname, PORTSZ, "%d", port);

	/*
	 * Hang an unending listen for PKG connections
	 */
	if ( (netfd = pkg_permserver(portname, 0, 0, comm_error)) < 0 )
	    bu_exit(-1, NULL);
	FD_SET(netfd, &select_list);
	V_MAX(max_fd, netfd);

	main_loop();
	return 0;
    }

#ifndef _WIN32
    /*
     * Stand-Alone Daemon
     */
    /* check/default port */
    if ( port_set ) {
	if ( port < 1024 )
	    port += 5559;
	sprintf(portname, "%d", port);
    } else {
	snprintf(portname, PORTSZ, "%s", "remotefb");
    }

    init_syslog();
    while ( (netfd = pkg_permserver(portname, 0, 0, comm_error)) < 0 ) {
	static int error_count=0;
	sleep(1);
	if (error_count++ < 60) {
	    continue;
	}
	comm_error("Unable to start the stand-alone framebuffer daemon after 60 seconds, giving up.");
	return 1;
    }

    while (1) {
	int fbstat;
	struct pkg_conn	*pcp;

	pcp = pkg_getclient( netfd, fb_server_pkg_switch, comm_error, 0 );
	if ( pcp == PKC_ERROR )
	    break;		/* continue is unlikely to work */

	if ( fork() == 0 )  {
	    /* 1st level child process */
	    (void)close(netfd);	/* Child is not listener */

	    /* Create 2nd level child process, "double detach" */
	    if ( fork() == 0 )  {
		/* 2nd level child -- start work! */
		new_client( pcp );
		once_only = 1;
		main_loop();
		return 0;
	    } else {
		/* 1st level child -- vanish */
		return 1;
	    }
	} else {
	    /* Parent: lingering server daemon */
	    pkg_close(pcp);	/* Daemon is not the server */
	    /* Collect status from 1st level child */
	    (void)wait( &fbstat );
	}
    }
#endif  /* _WIN32 */

    return 2;
}
Exemplo n.º 7
0
/*
 *			M A I N
 */
int
main(int argc, char **argv)
{
    register FBIO	*fbp = FBIO_NULL;
    int scene_number = 1;
    int start_frame = 1;
    int number_of_frames=0;
    int number_of_images=0;
    int start_seq_number=0;
    int	exit_code;

    exit_code = 0;

    bu_log(""
	   "*** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***\n"
	   "\n"
	   "This tool is deprecated and under consideration for removal from\n"
	   "BRL-CAD.  If you use this tool, please contact the developers via\n"
	   "[email protected] to express your interest and justification for not\n"
	   "removing this tool.  Otherwise, this tool will likely be removed from\n"
	   "a future release of BRL-CAD.\n"
	   "\n"
	   "*** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***\n"
	   "\n");

    if ( !get_args( argc, argv ) )  {
	usage();
	bu_exit( 1, NULL );
    }

    argc -= (bu_optind-1);
    argv += (bu_optind-1);

    /*
     *  First group of commands.
     *  No checking of VAS IV status is performed first.
     */
    if (strcmp(argv[1], "init") == 0) {
	vas_open();
	if ( get_vas_status() < 0 )
	    bu_exit(1, NULL);
	vas_putc(C_INIT);
	vas_await(R_INIT, 5);
	if ( get_vtr_status(0) < 0 )
	    exit_code = 1;
	goto done;
    }
    else if (strcmp(argv[1], "status") == 0) {
	vas_open();
	(void)get_vas_status();
	(void)get_vtr_status(1);
	get_tape_position();
	(void)get_frame_code();
	goto done;
    }
    else if (strcmp(argv[1], "sequence") == 0) {
	if (argc == 2) {
	    number_of_images = 1;
	    number_of_frames = 1;
	    start_seq_number = 1;
	}
	else if (argc == 4) {
	    number_of_images = atoi(argv[2]);
	    if (number_of_images < 1)
		usage_seq();
	    number_of_frames = str2frames(argv[3]);
	    if (number_of_frames < 1)
		usage_seq();
	    start_seq_number = 1;
	}
	else if (argc == 5) {
	    number_of_images = atoi(argv[2]);
	    if (number_of_images < 1)
		usage_seq();
	    number_of_frames = str2frames(argv[3]);
	    if (number_of_frames < 1)
		usage_seq();
	    start_seq_number = atoi(argv[4]);
	}
	else
	    usage_seq();


	record_seq(number_of_images, number_of_frames, start_seq_number);
	goto done;
    }

    /*
     *  Second group of commands.
     *  VAS IV is opened, and status of VAS is checked first
     *  but VTR is not queried.
     */
    vas_open();
    if ( get_vas_status() < 0 )
	bu_exit(1, NULL);

    if (strcmp(argv[1], "rewind") == 0) {
	vas_putc(C_REWIND);
	goto done;
    }
    else if (strcmp(argv[1], "play") == 0) {
	vas_putc(C_PLAY);
	goto done;
    }
    else if (strcmp(argv[1], "stop") == 0) {
	vas_putc(C_STOP);
	goto done;
    }
    else if (strcmp(argv[1], "fforward") == 0) {
	vas_putc(C_FFORWARD);
	goto done;
    }

    /*
     *  Third group of commands.
     *  VAS IV is opened and checked above,
     *  and VTR status is checked here.
     */
    if ( get_vtr_status(0) < 0 )  {
	exit_code = 1;
	goto done;
    }
    if ( strcmp(argv[1], "search") == 0 )  {
	if ( argc >= 3 )
	    start_frame = str2frames(argv[2]);
	else
	    start_frame = 1;
	exit_code = search_frame(start_frame);
	goto done;
    }
    else if ( strcmp(argv[1], "time0") == 0 )  {
	exit_code = time0();
	goto done;
    }
    else if ( strcmp( argv[1], "reset_time" ) == 0 )  {
	exit_code = reset_tape_time();
	goto done;
    }

    /*
     *  If this is running on a workstation, and a window has to be
     *  opened to cause image to be re-displayed, do so now.
     */
    if ( framebuffer != (char *)0 )  {
	if ( (fbp = fb_open( framebuffer, scr_width, scr_height )) == FBIO_NULL )  {
	    exit_code = 12;
	    goto done;
	}
    }

    /*
     *  Commands that will actually record some image onto tape
     */
    if (strcmp(argv[1], "new") == 0) {
	if ( argc >= 4 )  {
	    if ( (start_frame = str2frames(argv[3])) < 1 )
		usage_new();
	}
	if (argc >= 3) {
	    if ( (scene_number = atoi(argv[2])) < 1 )
		usage_new();
	}
	else if (argc == 2) {
	    scene_number = 1;
	}
	else {
	    usage_new();
	}
	program_recording(1, scene_number, start_frame);
	goto done;
    }
    else if (strcmp(argv[1], "old") == 0) {
	if ( argc >= 4 )  {
	    if ( (start_frame = str2frames(argv[3])) < 1 )
		usage_new();
	}
	if (argc >= 3) {
	    if ( (scene_number = atoi(argv[2])) < 1 )
		usage_new();
	}
	else if (argc == 2) {
	    scene_number = 1;
	}
	else {
	    usage_new();
	}
	/* May need one more parameter here, eventually */
	program_recording(0, scene_number, start_frame);
	goto done;
    }
    else if (strcmp(argv[1], "record") == 0) {
	if (argc == 3) {
	    number_of_frames = str2frames(argv[2]);
	    if (number_of_frames < 1) {
		usage_record();
	    }
	}
	else if (argc == 2) {
	    number_of_frames = 1;
	}
	else {
	    usage_record();
	}
	record_add_to_scene(number_of_frames);
	goto done;
    } else {
	/* None of the above */
	usage();
	exit_code = 1;
    }

 done:
    vas_close();
    if (fbp) fb_close(fbp);
    bu_exit(exit_code, NULL);
}
Exemplo n.º 8
0
void execute(char* cmdline) {

	int pid, pid2, async, i, pflag=0;
	char* args[MAX_ARGS];
	int iFile =-1,oFile=-1, pp[2];
	int nargs = get_args(cmdline, args);

	if(nargs <= 0) 
		return;

	if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) 
		exit(0);

	/* check if async call */
	if(!strcmp(args[nargs-1], "&")) { async = 1; args[--nargs] = 0; }
	else async = 0;

	for(i=0;i<nargs;i++){
		if(!strcmp(args[i], ">")){
			oFile = open(args[i+1], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
			if(oFile < 0) { perror("open failed!!"); exit(-1); }
			args[i++]=0;
			args[i]=0;  
		}
		else if(!strcmp(args[i], ">>")){
			oFile = open(args[i+1], O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
			if(oFile < 0) { perror("open failed!!"); exit(-1); }
			args[i++]=0;
			args[i]=0;	  
		}		
		else if(!strcmp(args[i], "<")){
			iFile = open(args[i+1], O_RDONLY);
			if(iFile < 0) { perror("open failed!!"); exit(-1); }
			args[i++]=0;
			args[i]=0;
		}	
		else if(!strcmp(args[i], "|")){
			args[i++]=0;
			pflag=1;

			if(pipe(pp) < 0) { perror("pipe failed"); exit(-1); }

			pid2 = fork();
			if(pid2 == 0) { //child process 

				dup2(pp[0], STDIN_FILENO);
				close(pp[1]);

				execvp(args[i], &args[i]);
				// return only when exec fails 
				perror("exec failed");
				exit(-1);
			} 
			else if(pid2 > 0) { // parent process 

			} 
			else { // error occurred 
				perror("pipe fork failed");
				exit(1);
			}
			break;
		}			
	}


	pid = fork();
	if(pid == 0) { /* child process */

		if(!pflag){
			if(iFile>0){dup2(iFile, STDIN_FILENO);close(iFile);}
			if(oFile>0){dup2(oFile, STDOUT_FILENO);close(oFile);}
		}

		dup2(pp[1], STDOUT_FILENO);
		close(pp[0]);

		execvp(args[0], args);
		/* return only when exec fails */
		perror("exec failed");
		exit(-1);
	} 
	else if(pid > 0) { /* parent process */
		close(pp[0]);
		close(pp[1]);

		if(!async) waitpid(pid, NULL, 0);
		else printf("this is an async call\n");
		
		if(pid2) 
			waitpid(pid2, NULL, 0);

	} 
	else { /* error occurred */
		perror("fork failed");
		exit(1);
	}
}
Exemplo n.º 9
0
int test_utils(bool verbose) {
    map_args_t args;
    multimap_args_t multiArgs;

    // nominal use
    int rc = get_args(&multiArgs, "arg1 (aaa = 123, bb = AZERTY); arg2 (aaa = O0, cc = 000); arg3; arg4 (bb = f, aaa=0)", ";", "(", ")");
    abadoorand_assert(rc == 0);
    abadoorand_assert(multiArgs.size() == 4);
    auto arg = multiArgs.find("arg1");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa = 123, bb = AZERTY");
    arg = multiArgs.find("arg2");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa = O0, cc = 000");
    arg = multiArgs.find("arg3");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "");
    arg = multiArgs.find("arg4");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "bb = f, aaa=0");
    multiArgs.clear();

    // nominal use with duplicate arguments
    rc = get_args(&multiArgs, "arg1 (aaa = 123, bb = AZERTY); arg2 (aaa = O0, cc = 000); arg1; arg1 (bb = f, aaa=0)", ";", "(", ")");
    abadoorand_assert(rc == 0);
    abadoorand_assert(multiArgs.size() == 4);
    std::set<std::string> arg1Args = {"aaa = 123, bb = AZERTY", "bb = f, aaa=0", ""};
    for (auto arg : multiArgs) {
        if (arg.first == "arg1") {
            auto arg1Arg = arg1Args.find(arg.second);
            abadoorand_assert(arg1Arg != arg1Args.end());
            arg1Args.erase(arg1Arg);
        }
        else {
            abadoorand_assert(arg.first == "arg2");
            abadoorand_assert(arg.second == "aaa = O0, cc = 000");
        }
    }
    abadoorand_assert(arg1Args.empty());
//    auto arg = multiArgs.find("arg1");
//    abadoorand_assert(arg != multiArgs.end());
//    abadoorand_assert(arg->second == "aaa = 123, bb = AZERTY");
//    arg = multiArgs.find("arg2");
//    abadoorand_assert(arg != multiArgs.end());
//    abadoorand_assert(arg->second == "aaa = O0, cc = 000");
//    arg = multiArgs.find("arg3");
//    abadoorand_assert(arg != multiArgs.end());
//    abadoorand_assert(arg->second == "");
//    arg = multiArgs.find("arg4");
//    abadoorand_assert(arg != multiArgs.end());
//    abadoorand_assert(arg->second == "bb = f, aaa=0");
    multiArgs.clear();

    // more delimiters
    rc = get_args(&multiArgs, "arg1 (aaa = 123, bb:AZERTY); arg2 {aaa:O0 cc := 000}; arg3[  bb  =  f,aaa=0]", ";", "([{", ")]}");
    abadoorand_assert(rc == 0);
    abadoorand_assert(multiArgs.size() == 3);
    arg = multiArgs.find("arg1");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa = 123, bb:AZERTY");
    arg = multiArgs.find("arg2");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa:O0 cc := 000");
    arg = multiArgs.find("arg3");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "bb  =  f,aaa=0");
    multiArgs.clear();

    // extra spaces, or no spaces
    rc = get_args(&multiArgs, "  arg1 (aaa = 123, bb:AZERTY)  ;arg2 { aaa:O0 cc := 000};  arg3    ", ";", "({", ")}");
    abadoorand_assert(rc == 0);
    abadoorand_assert(multiArgs.size() == 3);
    arg = multiArgs.find("arg1");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa = 123, bb:AZERTY");
    arg = multiArgs.find("arg2");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "aaa:O0 cc := 000");
    arg = multiArgs.find("arg3");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "");
    multiArgs.clear();

    // no arguments arguments
    rc = get_args(&multiArgs, "arg1; arg2,arg3", ";,", "");
    abadoorand_assert(rc == 0);
    abadoorand_assert(multiArgs.size() == 3);
    arg = multiArgs.find("arg1");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "");
    arg = multiArgs.find("arg2");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "");
    arg = multiArgs.find("arg3");
    abadoorand_assert(arg != multiArgs.end());
    abadoorand_assert(arg->second == "");
    multiArgs.clear();

    // nothing at all
    rc = get_args(&multiArgs, "", "", "");
    abadoorand_assert(rc == -1);
    abadoorand_assert(multiArgs.size() == 0);
    multiArgs.clear();

    // Let's try one of our test argument arguments
    rc = get_args(&args, "aaa = 123, bb = AZERTY", ",", "=", "");
    abadoorand_assert(rc == 0);
    abadoorand_assert(args.size() == 2);
    abadoorand_assert(args["aaa"] == "123");
    abadoorand_assert(args["bb"] == "AZERTY");
    args.clear();


    return 0;
}
void outputFunction(FILE *fp, FileInfo *data)
{
  int i;
  int args_ok = 1;
  char *jniFunction = 0;
  char *begPtr = 0;
  char *endPtr = 0;
  CurrentData = data;

  /* some functions will not get wrapped no matter what else */
  if (currentFunction->IsOperator || 
      currentFunction->ArrayFailure ||
      !currentFunction->IsPublic ||
      !currentFunction->Name) 
    {
    return;
    }

  /* NewInstance and SafeDownCast can not be wrapped because it is a
     (non-virtual) method which returns a pointer of the same type as
     the current pointer. Since all methods are virtual in Java, this
     looks like polymorphic return type.  */
  if (!strcmp("NewInstance",currentFunction->Name))
    {
    return ;
    }
  
  if (!strcmp("SafeDownCast",currentFunction->Name))
    {
    return ;
    }
  
  /* check to see if we can handle the args */
  for (i = 0; i < currentFunction->NumberOfArguments; i++)
    {
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x9) args_ok = 0;
    if ((currentFunction->ArgTypes[i] % 0x10) == 0x8) args_ok = 0;
    if (((currentFunction->ArgTypes[i] % 0x1000)/0x100 != 0x3)&&
        (currentFunction->ArgTypes[i] % 0x1000 != 0x109)&&
        ((currentFunction->ArgTypes[i] % 0x1000)/0x100)) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x313) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x314) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x315) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x316) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31A) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31B) args_ok = 0;
    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31C) args_ok = 0;
    }
  if ((currentFunction->ReturnType % 0x10) == 0x8) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x9) args_ok = 0;
  if (((currentFunction->ReturnType % 0x1000)/0x100 != 0x3)&&
      (currentFunction->ReturnType % 0x1000 != 0x109)&&
      ((currentFunction->ReturnType % 0x1000)/0x100)) args_ok = 0;


  /* eliminate unsigned short * usigned int * etc */
  if (currentFunction->ReturnType % 0x1000 == 0x314) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x315) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x316) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x31A) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x31B) args_ok = 0;
  if (currentFunction->ReturnType % 0x1000 == 0x31C) args_ok = 0;

  if (currentFunction->NumberOfArguments && 
      (currentFunction->ArgTypes[0] == 0x5000)
      &&(currentFunction->NumberOfArguments != 1)) args_ok = 0;

  /* make sure we have all the info we need for array arguments in */
  for (i = 0; i < currentFunction->NumberOfArguments; i++)
    {
    if (((currentFunction->ArgTypes[i] % 0x1000)/0x100 == 0x3)&&
        (currentFunction->ArgCounts[i] <= 0)&&
        (currentFunction->ArgTypes[i] % 0x1000 != 0x309)&&
        (currentFunction->ArgTypes[i] % 0x1000 != 0x303)) args_ok = 0;
    }

  /* if we need a return type hint make sure we have one */
  switch (currentFunction->ReturnType % 0x1000)
    {
    case 0x301: case 0x302: case 0x307:
    case 0x304: case 0x305: case 0x306:
    case 0x30A: case 0x30B: case 0x30C: case 0x30D: case 0x30E:
    case 0x313:
      args_ok = currentFunction->HaveHint;
      break;
    }
  
  /* make sure it isn't a Delete or New function */
  if (!strcmp("Delete",currentFunction->Name) ||
      !strcmp("New",currentFunction->Name))
    {
    args_ok = 0;
    }

  /* handle DataReader SetBinaryInputString as a special case */
  if (!strcmp("SetBinaryInputString",currentFunction->Name) &&
      (!strcmp("vtkDataReader",data->ClassName) ||
       !strcmp("vtkStructuredGridReader",data->ClassName) ||
       !strcmp("vtkRectilinearGridReader",data->ClassName) ||
       !strcmp("vtkUnstructuredGridReader",data->ClassName) ||
       !strcmp("vtkStructuredPointsReader",data->ClassName) ||
       !strcmp("vtkPolyDataReader",data->ClassName)))
      {
      if(currentFunction->IsLegacy)
        {
        fprintf(fp,"#if !defined(VTK_LEGACY_REMOVE)\n");
        }
      HandleDataReader(fp,data);
      if(currentFunction->IsLegacy)
        {
        fprintf(fp,"#endif\n");
        }
      wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
      numberOfWrappedFunctions++;
      }
  

  if (currentFunction->IsPublic && args_ok && 
      strcmp(data->ClassName,currentFunction->Name) &&
      strcmp(data->ClassName, currentFunction->Name + 1))
  {
    /* make sure we haven't already done one of these */
    if (!DoneOne())
    {
      fprintf(fp,"\n");

      /* Underscores are escaped in method names, see
           http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp133
         VTK class names contain no underscore and do not need to be escaped.  */
      jniFunction = currentFunction->Name;
      begPtr = currentFunction->Name;
      endPtr = strchr(begPtr, '_');
      if(endPtr)
        {
        jniFunction = (char *)malloc(2*strlen(currentFunction->Name) + 1);
        jniFunction[0] = '\0';
        while (endPtr)
          {
          strncat(jniFunction, begPtr, endPtr - begPtr + 1);
          strcat(jniFunction, "1");
          begPtr = endPtr + 1;
          endPtr = strchr(begPtr, '_');
          }
        strcat(jniFunction, begPtr);
        }
      
      if(currentFunction->IsLegacy)
        {
        fprintf(fp,"#if !defined(VTK_LEGACY_REMOVE)\n");
        }
      fprintf(fp,"extern \"C\" JNIEXPORT ");
      return_result(fp);
      fprintf(fp," JNICALL Java_vtk_%s_%s_1%i(JNIEnv *env, jobject obj",
              data->ClassName, jniFunction, numberOfWrappedFunctions);
      
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
          {
            fprintf(fp,",");
            output_proto_vars(fp, i);
          }
      fprintf(fp,")\n{\n");
      
      /* get the object pointer */
      fprintf(fp,"  %s *op;\n",data->ClassName);
      /* process the args */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
          {
            output_temp(fp, i, currentFunction->ArgTypes[i],
                    currentFunction->ArgClasses[i],
                    currentFunction->ArgCounts[i]);
          }
      output_temp(fp, MAX_ARGS,currentFunction->ReturnType,
                  currentFunction->ReturnClass,0);
      
      /* now get the required args from the stack */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
        {
        get_args(fp, i);
        }
      
      fprintf(fp,"\n  op = (%s *)vtkJavaGetPointerFromObject(env,obj);\n",
              data->ClassName);
      
      
      switch (currentFunction->ReturnType % 0x1000)
          {
            case 0x2:
            fprintf(fp,"  op->%s(",currentFunction->Name);
          break;
            case 0x109:
            fprintf(fp,"  temp%i = &(op)->%s(",MAX_ARGS, currentFunction->Name);
          break;
          default:
             fprintf(fp,"  temp%i = (op)->%s(",MAX_ARGS, currentFunction->Name);
          }
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
          {
          if (i)
            {
            fprintf(fp,",");
            }
          if (currentFunction->ArgTypes[i] % 0x1000 == 0x109)
            {
            fprintf(fp,"*(temp%i)",i);
            }
          else if (currentFunction->ArgTypes[i] == 0x5000)
            {
            fprintf(fp,"vtkJavaVoidFunc,(void *)temp%i",i);
            }
          else
            {
            fprintf(fp,"temp%i",i);
            }
          } /* for */
      fprintf(fp,");\n");
      if (currentFunction->NumberOfArguments == 1 && currentFunction->ArgTypes[0] == 0x5000)
        {
        fprintf(fp,"  op->%sArgDelete(vtkJavaVoidFuncArgDelete);\n",
                jniFunction);
        }
      
      /* now copy and release any arrays */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
        {
        copy_and_release_args(fp, i);
        }
      do_return(fp);
      fprintf(fp,"}\n");
      if(currentFunction->IsLegacy)
        {
        fprintf(fp,"#endif\n");
        }
      
      wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
      numberOfWrappedFunctions++;
      if (jniFunction != currentFunction->Name)
        {
        free(jniFunction);
        }
    } /* isDone() */
  } /* isAbstract */
}
Exemplo n.º 11
0
void outputFunction(FILE *fp, ClassInfo *data)
{
  int i;

  if (notWrappable(currentFunction))
    {
    return;
    }

  /* if the args are OK and it is not a constructor or destructor */
  if (managableArguments(currentFunction) &&
      strcmp(data->Name,currentFunction->Name) &&
      strcmp(data->Name,currentFunction->Name + 1))
    {
    if(currentFunction->IsLegacy)
      {
      fprintf(fp,"#if !defined(VTK_LEGACY_REMOVE)\n");
      }
    fprintf(fp,"  if (!strcmp(\"%s\",method) && msg.GetNumberOfArguments(0) == %i)\n",
            currentFunction->Name, currentFunction->NumberOfArguments+2);
    fprintf(fp, "    {\n");

    /* process the args */
    for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
      output_temp(fp, i, currentFunction->ArgTypes[i],
                  currentFunction->ArgClasses[i],
                  currentFunction->ArgCounts[i]);
      }
    output_temp(fp, MAX_ARGS,currentFunction->ReturnType,
                currentFunction->ReturnClass, 0);

    if(currentFunction->NumberOfArguments > 0)
      {
      const char* amps = "    if(";
      /* now get the required args from the stack */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
        {
        fprintf(fp, "%s", amps);
        amps = " &&\n      ";
        get_args(fp,i);
        }
      fprintf(fp, ")\n");
      }
    fprintf(fp, "      {\n");

    if ((currentFunction->ReturnType & VTK_PARSE_UNQUALIFIED_TYPE) ==
        VTK_PARSE_VOID)
      {
      fprintf(fp,"      op->%s(",currentFunction->Name);
      }
    else if ((currentFunction->ReturnType & VTK_PARSE_INDIRECT) ==
             VTK_PARSE_REF)
      {
      fprintf(fp,"      temp%i = &(op)->%s(",MAX_ARGS,currentFunction->Name);
      }
    else
      {
      fprintf(fp,"      temp%i = (op)->%s(",MAX_ARGS,currentFunction->Name);
      }

    for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
      if (i)
        {
        fprintf(fp,",");
        }
      if (((currentFunction->ArgTypes[i] & VTK_PARSE_INDIRECT)
           == VTK_PARSE_REF) &&
          ((currentFunction->ArgTypes[i] & VTK_PARSE_BASE_TYPE)
           == VTK_PARSE_VTK_OBJECT))
        {
        fprintf(fp,"*(temp%i)",i);
        }
      else if ((((currentFunction->ArgTypes[i] & VTK_PARSE_INDIRECT) == 0) ||
                ((currentFunction->ArgTypes[i] & VTK_PARSE_INDIRECT) ==
                 VTK_PARSE_REF)) &&
                ((currentFunction->ArgTypes[i] & VTK_PARSE_BASE_TYPE) ==
                 VTK_PARSE_STRING))
        {
        /* explicit construction avoids possible ambiguity */
        fprintf(fp,"vtkStdString(temp%i)",i);
        }
      else
        {
        fprintf(fp,"temp%i",i);
        }
      }
    fprintf(fp,");\n");
    return_result(fp);
    fprintf(fp,"      return 1;\n");
    fprintf(fp,"      }\n");
    fprintf(fp,"    }\n");
    if(currentFunction->IsLegacy)
      {
      fprintf(fp,"#endif\n");
      }

    wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
    numberOfWrappedFunctions++;
    }

#if 0
  if (!strcmp("vtkObject",data->Name))
    {
    fprintf(fp,"  if (!strcmp(\"AddProgressObserver\",method) && msg.NumberOfArguments == 3 &&\n");
    fprintf(fp,"      msg.ArgumentTypes[2] == vtkClietnServerStream::string_value)\n");
    fprintf(fp,"    {\n");
    fprintf(fp,"    vtkClientServerProgressObserver *apo = vtkClientServerProgressObserver::New();\n");
    fprintf(fp,"    vtkObject* obj = arlu->GetObjectFromMessage(msg, 0, 1);\n");
    fprintf(fp,"    apo->SetFilterID(arlu->GetIDFromObject(obj));\n");
    fprintf(fp,"    apo->SetClientServerUtil(arlu);\n");
    fprintf(fp,"    char *temp0 = vtkClientServerInterpreter::GetString(msg,2);\n");
    fprintf(fp,"    op->AddObserver(temp0,apo);\n");
    fprintf(fp,"    apo->Delete();\n");
    fprintf(fp,"    delete [] temp0;\n");
    fprintf(fp,"    return 1;\n");
    fprintf(fp,"    }\n");
    }
#endif
}
Exemplo n.º 12
0
Arquivo: cut.c Projeto: Abioy/FUZIX
int main(int argc, char *argv[])
{
    int i = 1;
    int numberFilenames = 0;
    name = argv[0];

    if (argc == 1)
	cuterror(USAGE);

    while (i < argc) {
	if (argv[i][0] == '-') {
	    switch (argv[i++][1]) {
	    case 'd':
		if (mode == OPTIONC || mode == OPTIONB)
		    warn(DELIMITER_NOT_APPLICABLE, "d");
		delim = argv[i++][0];
		break;

	    case 'f':
		sprintf(line, "%s", argv[i++]);
		if (mode == OPTIONC || mode == OPTIONB)
		    warn(OVERRIDING_PREVIOUS_MODE, "f");
		mode = OPTIONF;
		break;

	    case 'b':
		sprintf(line, "%s", argv[i++]);
		if (mode == OPTIONF || mode == OPTIONC)
		    warn(OVERRIDING_PREVIOUS_MODE, "b");
		mode = OPTIONB;
		break;

	    case 'c':
		sprintf(line, "%s", argv[i++]);
		if (mode == OPTIONF || mode == OPTIONB)
		    warn(OVERRIDING_PREVIOUS_MODE, "c");
		mode = OPTIONC;
		break;

	    case 'i':
		flag_i = SET;
		break;

	    case 's':
		flag_s = SET;
		break;

	    case '\0':		/* - means: read from stdin */
		numberFilenames++;
		break;

	    case 'n':		/* needed for Posix, but no effect here */
		if (mode != OPTIONB)
		    warn(OPTION_NOT_APPLICABLE, "n");
		break;

	    default:
		warn(UNKNOWN_OPTION, &(argv[i - 1][1]));
	    }
	} else {
	    i++;
	    numberFilenames++;
	}
    }

    /* Here follow the checks, if the selected options are reasonable. */

    if (mode == OPTIONB)	/* since in Minix char == byte */
	mode = OPTIONC;

    /* Flag -s is only allowed with -f, otherwise warn and reset flag_s */
    if (flag_s == SET && (mode == OPTIONB || mode == OPTIONC)) {
	warn(OPTION_NOT_APPLICABLE, "s");
	flag_s = NOTSET;
    }

    /* Flag -i is only allowed with -f, otherwise warn and reset flag_i */
    if (flag_i == SET && mode == OPTIONF) {
	warn(OPTION_NOT_APPLICABLE, "s");
	flag_i = NOTSET;
    }

    get_args();

    if (numberFilenames != 0) {
	i = 1;
	while (i < argc) {
	    if (argv[i][0] == '-') {
		switch (argv[i][1]) {
		case 'f':
		case 'c':
		case 'b':
		case 'd':
		    i += 2;
		    break;

		case 'n':
		case 'i':
		case 's':
		    i++;
		    break;

		case '\0':
		    fd = stdin;
		    i++;
		    cut();
		    break;

		default:
		    i++;
		}
	    } else {
		if ((fd = fopen(argv[i++], "r")) == NULL) {
		    warn(FILE_NOT_READABLE, argv[i - 1]);
		} else {
		    cut();
		    fclose(fd);
		}
	    }
	}
    } else {
	fd = stdin;
	cut();
    }

    return (exit_status);
}
int
main(int argc, char **argv) {
    time_t start = time(NULL);

    // If this binary is started with the single argument "--adbd",
    // instead of being the normal recovery binary, it turns into kind
    // of a stripped-down version of adbd that only supports the
    // 'sideload' command.  Note this must be a real argument, not
    // anything in the command file or bootloader control block; the
    // only way recovery should be run with this argument is when it
    // starts a copy of itself from the apply_from_adb() function.
    if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
        adb_main();
        return 0;
    }

    // Handle alternative invocations
    char* command = argv[0];
    char* stripped = strrchr(argv[0], '/');
    if (stripped)
        command = stripped + 1;

    if (strcmp(command, "recovery") != 0) {
        struct recovery_cmd cmd = get_command(command);
        if (cmd.name)
            return cmd.main_func(argc, argv);

#ifdef BOARD_RECOVERY_HANDLES_MOUNT
        if (!strcmp(command, "mount") && argc == 2)
        {
            load_volume_table();
            return ensure_path_mounted(argv[1]);
        }
#endif
        if (!strcmp(command, "setup_adbd")) {
            load_volume_table();
            setup_adbd();
            return 0;
        }
        if (strstr(argv[0], "start")) {
            property_set("ctl.start", argv[1]);
            return 0;
        }
        if (strstr(argv[0], "stop")) {
            property_set("ctl.stop", argv[1]);
            return 0;
        }
        return busybox_driver(argc, argv);
    }

    // devices can run specific tasks on recovery start
    __system("/sbin/postrecoveryboot.sh");

    // Clear umask for packages that copy files out to /tmp and then over
    // to /system without properly setting all permissions (eg. gapps).
    umask(0);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);

    printf("Starting recovery on %s", ctime(&start));

    load_volume_table();
    setup_data_media(1);
    vold_client_start(&v_callbacks, 0);
    vold_set_automount(1);
    setup_legacy_storage_paths();
    ensure_path_mounted(LAST_LOG_FILE);
    rotate_last_logs(10);
    get_args(&argc, &argv);

    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0, wipe_media = 0, show_text = 0, sideload = 0;
    bool just_exit = false;
    bool shutdown_after = false;

    printf("Checking arguments.\n");
    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': wipe_data = wipe_cache = 1; break;
        case 'm': wipe_media = 1; break;
        case 'c': wipe_cache = 1; break;
        case 't': show_text = 1; break;
        case 'x': just_exit = true; break;
        case 'a': sideload = 1; break;
        case 'p': shutdown_after = true; break;
        case 'g': {
            if (stage == NULL || *stage == '\0') {
                char buffer[20] = "1/";
                strncat(buffer, optarg, sizeof(buffer)-3);
                stage = strdup(buffer);
            }
            break;
        }
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    printf("stage is [%s]\n", stage);

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_MOD_VERSION_BUILD) "\n");
    ui_print("ClockworkMod " EXPAND(CWM_BASE_VERSION) "\n");
    LOGI("Device target: " EXPAND(TARGET_COMMON_NAME) "\n");
#ifdef PHILZ_TOUCH_RECOVERY
    print_libtouch_version(0);
#endif

    int st_cur, st_max;
    if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
        ui_SetStage(st_cur, st_max);
    }
    // ui_SetStage(5, 8); // debug

    if (show_text) ui_ShowText(true);

    struct selinux_opt seopts[] = {
      { SELABEL_OPT_PATH, "/file_contexts" }
    };

    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);

    if (!sehandle) {
        ui_print("Warning:  No file_contexts\n");
    }

    LOGI("device_recovery_start()\n");
    device_recovery_start();

    printf("Command:");
    for (arg = 0; arg < argc; arg++) {
        printf(" \"%s\"", argv[arg]);
    }
    printf("\n");

    if (update_package) {
        // For backwards compatibility on the cache partition only, if
        // we're given an old 'root' path "CACHE:foo", change it to
        // "/cache/foo".
        if (strncmp(update_package, "CACHE:", 6) == 0) {
            int len = strlen(update_package) + 10;
            char* modified_path = (char*)malloc(len);
            strlcpy(modified_path, "/cache/", len);
            strlcat(modified_path, update_package+6, len);
            printf("(replacing path \"%s\" with \"%s\")\n",
                   update_package, modified_path);
            update_package = modified_path;
        }
    }
    printf("\n");

    property_list(print_property, NULL);
    printf("\n");

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        status = install_package(update_package, &wipe_cache, TEMPORARY_INSTALL_FILE);
        if (status == INSTALL_SUCCESS && wipe_cache) {
            if (erase_volume("/cache")) {
                LOGE("Cache wipe (requested by package) failed.\n");
            }
        }
        if (status != INSTALL_SUCCESS) {
            ui_print("Installation aborted.\n");

            // If this is an eng or userdebug build, then automatically
            // turn the text display on if the script fails so the error
            // message is visible.
            char buffer[PROPERTY_VALUE_MAX+1];
            property_get("ro.build.fingerprint", buffer, "");
            if (strstr(buffer, ":userdebug/") || strstr(buffer, ":eng/")) {
                ui_ShowText(true);
            }
        }
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        if (erase_volume("/data")) status = INSTALL_ERROR;
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
    } else if (wipe_media) {
        if (is_data_media() && erase_volume("/data/media")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Media wipe failed.\n");
    } else if (sideload) {
        status = enter_sideload_mode(status);
    } else if (!just_exit) {
        // let's check recovery start up scripts (openrecoveryscript and ROM Manager extendedcommands)
        status = INSTALL_NONE; // No command specified, it is a normal recovery boot unless we find a boot script to run

        LOGI("Checking for extendedcommand & OpenRecoveryScript...\n");

        // we need show_text to show boot scripts log
        bool text_visible = ui_IsTextVisible();
        ui_SetShowText(true);
        if (0 == check_boot_script_file(EXTENDEDCOMMAND_SCRIPT)) {
            LOGI("Running extendedcommand...\n");
            status = INSTALL_ERROR;
            if (0 == run_and_remove_extendedcommand())
                status = INSTALL_SUCCESS;
        }

        if (0 == check_boot_script_file(ORS_BOOT_SCRIPT_FILE)) {
            LOGI("Running openrecoveryscript....\n");
            status = INSTALL_ERROR;
            if (0 == run_ors_boot_script())
                status = INSTALL_SUCCESS;
        }

        ui_SetShowText(text_visible);
    }

    if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
        copy_logs();
        // ui_set_background(BACKGROUND_ICON_ERROR); // will be set in prompt_and_wait() after recovery lock check
        handle_failure();
    }
    if (status != INSTALL_SUCCESS || ui_IsTextVisible()) {
        ui_SetShowText(true);
#ifdef PHILZ_TOUCH_RECOVERY
        check_recovery_lock();
#endif
        prompt_and_wait(status);
    }

    // We reach here when in main menu we choose reboot main system or on success install of boot scripts and recovery commands
    finish_recovery(send_intent);
    if (shutdown_after) {
        ui_print("Shutting down...\n");
        reboot_main_system(ANDROID_RB_POWEROFF, 0, 0);
    } else {
        ui_print("Rebooting...\n");
        reboot_main_system(ANDROID_RB_RESTART, 0, 0);
    }
    return EXIT_SUCCESS;
}
Exemplo n.º 14
0
int
icv_rot(size_t argc, const char *argv[])
{
    const size_t MAXPIXELS = 16768 * 16768; /* boo hiss */

    ssize_t x, y;
    size_t j;
    int ret = 0;
    off_t outbyte, outplace;
    FILE *ifp, *ofp;
    unsigned char *obuf;
    unsigned char *buffer;
    double angle = 0.0;
    ssize_t wrote = 0;

    ifp = stdin;
    ofp = stdout;
    bu_setprogname(argv[0]);

    if (!get_args(argc, argv, &ifp, &ofp, &angle)) {
	bu_exit(1, "Usage: %s [-rifb | -a angle] [-# bytes] [-s squaresize] [-w width] [-n height] [-o outputfile] inputfile [> outputfile]\n", argv[0]);
    }

    scanbytes = nxin * pixbytes;
    buflines = MAXPIXELS / nxin;
    if (buflines <= 0) {
	bu_exit(1, "ERROR: %s is not compiled to handle a scanline that long!\n", argv[0]);
    }
    if (buflines > nyin) buflines = nyin;
    buffer = (unsigned char *)bu_malloc(buflines * scanbytes, "buffer");
    obuf = (unsigned char *)bu_malloc((nyin > nxin) ? nyin*pixbytes : nxin*pixbytes, "obuf");

    /*
     * Break out to added arbitrary angle routine
     */
    if (angle > 0.0) {
	arbrot(angle, ifp, buffer);
	goto done;
    }

    /*
     * Clear our "file pointer."  We need to maintain this
     * In order to tell if seeking is required.  ftell() always
     * fails on pipes, so we can't use it.
     */
    outplace = 0;

    yin = 0;
    while (yin < nyin) {
	/* Fill buffer */
	fill_buffer(ifp, buffer);
	if (!buflines)
	    break;
	if (reverse)
	    reverse_buffer(buffer);
	if (plus90) {
	    for (x = 0; x < nxin; x++) {
		obp = obuf;
		bp = &buffer[ (lasty-firsty)*scanbytes + x*pixbytes ];
		for (y = lasty+1; y > yin; y--) {
		    /* firsty? */
		    for (j = 0; j < pixbytes; j++)
			*obp++ = *bp++;
		    bp -= scanbytes + pixbytes;
		}
		yout = x;
		xout = (nyin - 1) - lasty;
		outbyte = ((yout * nyin) + xout) * pixbytes;
		if (outplace != outbyte) {
		    if (bu_fseek(ofp, outbyte, SEEK_SET) < 0) {
			ret = 3;
			perror("fseek");
			bu_log("ERROR: %s can't seek on output (ofp=%p, outbyte=%zd)\n", argv[0], (void *)ofp, outbyte);
			goto done;
		    }
		    outplace = outbyte;
		}
		wrote = fwrite(obuf, pixbytes, buflines, ofp);
		if (wrote != buflines) {
		    ret = 4;
		    perror("fwrite");
		    bu_log("ERROR: %s can't out write image data (wrote %zd of %zd)\n", argv[0], wrote, buflines);
		    goto done;
		}
		outplace += buflines*pixbytes;
	    }
	} else if (minus90) {
	    for (x = nxin; x > 0; x--) {
		obp = obuf;
		bp = &buffer[ (x-1)*pixbytes ];
		for (y = firsty+1; (ssize_t)y < lasty; y++) {
		    for (j = 0; j < pixbytes; j++)
			*obp++ = *bp++;
		    bp += scanbytes - pixbytes;
		}
		yout = (nxin - 1) - x + 1;
		xout = yin;
		outbyte = ((yout * nyin) + xout) * pixbytes;
		if (outplace != outbyte) {
		    if (bu_fseek(ofp, outbyte, SEEK_SET) < 0) {
			ret = 3;
			perror("fseek");
			bu_log("ERROR: %s can't seek on output (ofp=%p, outbyte=%zd)\n", argv[0], (void *)ofp, outbyte);
			goto done;
		    }
		    outplace = outbyte;
		}
		wrote = fwrite(obuf, pixbytes, buflines, ofp);
		if (wrote != buflines) {
		    ret = 4;
		    perror("fwrite");
		    bu_log("ERROR: %s can't out write image data (wrote %zd of %zd)\n", argv[0], wrote, buflines);
		    goto done;
		}
		outplace += buflines*pixbytes;
	    }
	} else if (invert) {
	    for (y = lasty+1; (ssize_t)y > firsty; y--) {
		yout = (nyin - 1) - y + 1;
		outbyte = yout * scanbytes;
		if (outplace != outbyte) {
		    if (bu_fseek(ofp, outbyte, SEEK_SET) < 0) {
			ret = 3;
			perror("fseek");
			bu_log("ERROR: %s can't seek on output (ofp=%p, outbyte=%zd)\n", argv[0], (void *)ofp, outbyte);
			goto done;
		    }
		    outplace = outbyte;
		}
		wrote = fwrite(&buffer[(y-firsty-1)*scanbytes], 1, scanbytes, ofp);
		if (wrote != scanbytes) {
		    ret = 4;
		    perror("fwrite");
		    bu_log("ERROR: %s can't out write image data (wrote %zd of %zd)\n", argv[0], wrote, scanbytes);
		    goto done;
		}
		outplace += scanbytes;
	    }
	} else {
	    /* Reverse only */
	    for (y = 0; y < buflines; y++) {
		wrote = fwrite(&buffer[y*scanbytes], 1, scanbytes, ofp);
		if (wrote != scanbytes) {
		    ret = 4;
		    perror("fwrite");
		    bu_log("ERROR: %s can't out write image data (wrote %zd of %zd)\n", argv[0], wrote, scanbytes);
		    goto done;
		}
	    }
	}

	yin += buflines;
    }

done:
    fclose(ifp);
    bu_free(buffer, "buffer");
    bu_free(obuf, "obuf");

    return ret;
}
Exemplo n.º 15
0
int
main(int argc, char **argv)
{
    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
    fprintf(stderr, "Starting recovery on %s", ctime(&start));

    ui_init();
    ui_print("Android system recovery utility\n");
    get_args(&argc, &argv);

    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0;

    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': wipe_data = wipe_cache = 1; break;
        case 'c': wipe_cache = 1; break;
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    fprintf(stderr, "Command:");
    for (arg = 0; arg < argc; arg++) {
        fprintf(stderr, " \"%s\"", argv[arg]);
    }
    fprintf(stderr, "\n\n");

    property_list(print_property, NULL);
    fprintf(stderr, "\n");

#if TEST_AMEND
    test_amend();
#endif

    RecoveryCommandContext ctx = { NULL };
    if (register_update_commands(&ctx)) {
        LOGE("Can't install update commands\n");
    }

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        status = install_package(update_package);
        if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
    } else if (wipe_data || wipe_cache) {
        if (wipe_data && erase_root("DATA:")) status = INSTALL_ERROR;
        if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
    } else {
        status = INSTALL_ERROR;  // No command specified
    }

    if (status != INSTALL_SUCCESS) ui_set_background(BACKGROUND_ICON_ERROR);
    if (status != INSTALL_SUCCESS || ui_text_visible()) prompt_and_wait();

    // If there is a radio image pending, reboot now to install it.
    maybe_install_firmware_update(send_intent);

    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);
    ui_print("Rebooting...\n");
    sync();
    reboot(RB_AUTOBOOT);
    return EXIT_SUCCESS;
}
Exemplo n.º 16
0
int main(int argc, char **argv) {
	// Recovery needs to install world-readable files, so clear umask
	// set by init
	umask(0);

	Log_Offset = 0;

	// Set up temporary log file (/tmp/recovery.log)
	freopen(TMP_LOG_FILE, "a", stdout);
	setbuf(stdout, NULL);
	freopen(TMP_LOG_FILE, "a", stderr);
	setbuf(stderr, NULL);

	signal(SIGPIPE, SIG_IGN);

	// Handle ADB sideload
	if (argc == 3 && strcmp(argv[1], "--adbd") == 0) {
		property_set("ctl.stop", "adbd");
		adb_main(argv[2]);
		return 0;
	}

#ifdef RECOVERY_SDCARD_ON_DATA
	datamedia = true;
#endif

	char crash_prop_val[PROPERTY_VALUE_MAX];
	int crash_counter;
	property_get("twrp.crash_counter", crash_prop_val, "-1");
	crash_counter = atoi(crash_prop_val) + 1;
	snprintf(crash_prop_val, sizeof(crash_prop_val), "%d", crash_counter);
	property_set("twrp.crash_counter", crash_prop_val);
	property_set("ro.twrp.boot", "1");
	property_set("ro.twrp.version", TW_VERSION_STR);

	time_t StartupTime = time(NULL);
	printf("Starting TWRP %s on %s (pid %d)\n", TW_VERSION_STR, ctime(&StartupTime), getpid());

	// Load default values to set DataManager constants and handle ifdefs
	DataManager::SetDefaultValues();
	printf("Starting the UI...");
	gui_init();
	printf("=> Linking mtab\n");
	symlink("/proc/mounts", "/etc/mtab");
	if (TWFunc::Path_Exists("/etc/twrp.fstab")) {
		if (TWFunc::Path_Exists("/etc/recovery.fstab")) {
			printf("Renaming regular /etc/recovery.fstab -> /etc/recovery.fstab.bak\n");
			rename("/etc/recovery.fstab", "/etc/recovery.fstab.bak");
		}
		printf("Moving /etc/twrp.fstab -> /etc/recovery.fstab\n");
		rename("/etc/twrp.fstab", "/etc/recovery.fstab");
	}
	printf("=> Processing recovery.fstab\n");
	if (!PartitionManager.Process_Fstab("/etc/recovery.fstab", 1)) {
		LOGERR("Failing out of recovery due to problem with recovery.fstab.\n");
		return -1;
	}
	PartitionManager.Output_Partition_Logging();
	// Load up all the resources
	gui_loadResources();

#ifdef HAVE_SELINUX
	if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
		if (TWFunc::Path_Exists("/file_contexts")) {
			printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
			rename("/file_contexts", "/file_contexts.bak");
		}
		printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
		rename("/prebuilt_file_contexts", "/file_contexts");
	}
	struct selinux_opt selinux_options[] = {
		{ SELABEL_OPT_PATH, "/file_contexts" }
	};
	selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
	if (!selinux_handle)
		printf("No file contexts for SELinux\n");
	else
		printf("SELinux contexts loaded from /file_contexts\n");
	{ // Check to ensure SELinux can be supported by the kernel
		char *contexts = NULL;

		if (PartitionManager.Mount_By_Path("/cache", true) && TWFunc::Path_Exists("/cache/recovery")) {
			lgetfilecon("/cache/recovery", &contexts);
			if (!contexts) {
				lsetfilecon("/cache/recovery", "test");
				lgetfilecon("/cache/recovery", &contexts);
			}
		} else {
			LOGINFO("Could not check /cache/recovery SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n");
			lgetfilecon("/sbin/teamwin", &contexts);
		}
		if (!contexts) {
			gui_print_color("warning", "Kernel does not have support for reading SELinux contexts.\n");
		} else {
			free(contexts);
			gui_print("Full SELinux support is present.\n");
		}
	}
#else
	gui_print_color("warning", "No SELinux support (no libselinux).\n");
#endif

	PartitionManager.Mount_By_Path("/cache", true);

	string Zip_File, Reboot_Value;
	bool Cache_Wipe = false, Factory_Reset = false, Perform_Backup = false, Shutdown = false;

	{
		TWPartition* misc = PartitionManager.Find_Partition_By_Path("/misc");
		if (misc != NULL) {
			if (misc->Current_File_System == "emmc") {
				set_misc_device("emmc", misc->Actual_Block_Device.c_str());
			} else if (misc->Current_File_System == "mtd") {
				set_misc_device("mtd", misc->MTD_Name.c_str());
			} else {
				LOGERR("Unknown file system for /misc\n");
			}
		}
		get_args(&argc, &argv);

		int index, index2, len;
		char* argptr;
		char* ptr;
		printf("Startup Commands: ");
		for (index = 1; index < argc; index++) {
			argptr = argv[index];
			printf(" '%s'", argv[index]);
			len = strlen(argv[index]);
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == 'u') {
				ptr = argptr;
				index2 = 0;
				while (*ptr != '=' && *ptr != '\n')
					ptr++;
				// skip the = before grabbing Zip_File
				while (*ptr == '=')
					ptr++;
				if (*ptr) {
					Zip_File = ptr;
				} else
					LOGERR("argument error specifying zip file\n");
			} else if (*argptr == 'w') {
				if (len == 9)
					Factory_Reset = true;
				else if (len == 10)
					Cache_Wipe = true;
			} else if (*argptr == 'n') {
				Perform_Backup = true;
			} else if (*argptr == 'p') {
				Shutdown = true;
			} else if (*argptr == 's') {
				ptr = argptr;
				index2 = 0;
				while (*ptr != '=' && *ptr != '\n')
					ptr++;
				if (*ptr) {
					Reboot_Value = *ptr;
				}
			}
		}
		printf("\n");
	}

	if(crash_counter == 0) {
		property_list(Print_Prop, NULL);
		printf("\n");
	} else {
		printf("twrp.crash_counter=%d\n", crash_counter);
	}

	// Check for and run startup script if script exists
	TWFunc::check_and_run_script("/sbin/runatboot.sh", "boot");
	TWFunc::check_and_run_script("/sbin/postrecoveryboot.sh", "boot");

#ifdef TW_INCLUDE_INJECTTWRP
	// Back up TWRP Ramdisk if needed:
	TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
	LOGINFO("Backing up TWRP ramdisk...\n");
	if (Boot == NULL || Boot->Current_File_System != "emmc")
		TWFunc::Exec_Cmd("injecttwrp --backup /tmp/backup_recovery_ramdisk.img");
	else {
		string injectcmd = "injecttwrp --backup /tmp/backup_recovery_ramdisk.img bd=" + Boot->Actual_Block_Device;
		TWFunc::Exec_Cmd(injectcmd);
	}
	LOGINFO("Backup of TWRP ramdisk done.\n");
#endif

	bool Keep_Going = true;
	if (Perform_Backup) {
		DataManager::SetValue(TW_BACKUP_NAME, "(Auto Generate)");
		if (!OpenRecoveryScript::Insert_ORS_Command("backup BSDCAE\n"))
			Keep_Going = false;
	}
	if (Keep_Going && !Zip_File.empty()) {
		string ORSCommand = "install " + Zip_File;

		if (!OpenRecoveryScript::Insert_ORS_Command(ORSCommand))
			Keep_Going = false;
	}
	if (Keep_Going) {
		if (Factory_Reset) {
			if (!OpenRecoveryScript::Insert_ORS_Command("wipe data\n"))
				Keep_Going = false;
		} else if (Cache_Wipe) {
			if (!OpenRecoveryScript::Insert_ORS_Command("wipe cache\n"))
				Keep_Going = false;
		}
	}

	TWFunc::Update_Log_File();
	// Offer to decrypt if the device is encrypted
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0) {
		LOGINFO("Is encrypted, do decrypt page first\n");
		if (gui_startPage("decrypt", 1, 1) != 0) {
			LOGERR("Failed to start decrypt GUI page.\n");
		} else {
			// Check for and load custom theme if present
			gui_loadCustomResources();
		}
	} else if (datamedia) {
		if (tw_get_default_metadata(DataManager::GetSettingsStoragePath().c_str()) != 0) {
			LOGINFO("Failed to get default contexts and file mode for storage files.\n");
		} else {
			LOGINFO("Got default contexts and file mode for storage files.\n");
		}
	}

	// Read the settings file
#ifdef TW_HAS_MTP
	// We unmount partitions sometimes during early boot which may override
	// the default of MTP being enabled by auto toggling MTP off. This
	// will force it back to enabled then get overridden by the settings
	// file, assuming that an entry for tw_mtp_enabled is set.
	DataManager::SetValue("tw_mtp_enabled", 1);
#endif
	DataManager::ReadSettingsFile();

	// Fixup the RTC clock on devices which require it
	if(crash_counter == 0)
		TWFunc::Fixup_Time_On_Boot();

	// Run any outstanding OpenRecoveryScript
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(SCRIPT_FILE_CACHE))) {
		OpenRecoveryScript::Run_OpenRecoveryScript();
	}

#ifdef TW_HAS_MTP
	// Enable MTP?
	char mtp_crash_check[PROPERTY_VALUE_MAX];
	property_get("mtp.crash_check", mtp_crash_check, "0");
	if (strcmp(mtp_crash_check, "0") == 0) {
		property_set("mtp.crash_check", "1");
		if (DataManager::GetIntValue("tw_mtp_enabled") == 1 && ((DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0 && DataManager::GetIntValue(TW_IS_DECRYPTED) != 0) || DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0)) {
			LOGINFO("Enabling MTP during startup\n");
			if (!PartitionManager.Enable_MTP())
				PartitionManager.Disable_MTP();
			else
				gui_print("MTP Enabled\n");
		} else {
			PartitionManager.Disable_MTP();
		}
		property_set("mtp.crash_check", "0");
	} else {
		gui_print_color("warning", "MTP Crashed, not starting MTP on boot.\n");
		DataManager::SetValue("tw_mtp_enabled", 0);
		PartitionManager.Disable_MTP();
	}
#else
	PartitionManager.Disable_MTP();
#endif

#ifndef TW_OEM_BUILD
	// Check if system has never been changed
	TWPartition* sys = PartitionManager.Find_Partition_By_Path("/system");
	if (sys) {
		if ((DataManager::GetIntValue("tw_mount_system_ro") == 0 && sys->Check_Lifetime_Writes() == 0) || DataManager::GetIntValue("tw_mount_system_ro") == 2) {
			if (DataManager::GetIntValue("tw_never_show_system_ro_page") == 0) {
				DataManager::SetValue("tw_back", "main");
				if (gui_startPage("system_readonly", 1, 1) != 0) {
					LOGERR("Failed to start system_readonly GUI page.\n");
				}
			} else if (DataManager::GetIntValue("tw_mount_system_ro") == 0) {
				sys->Change_Mount_Read_Only(false);
			}
		} else if (DataManager::GetIntValue("tw_mount_system_ro") == 1) {
			// Do nothing, user selected to leave system read only
		} else {
			sys->Change_Mount_Read_Only(false);
		}
	}
#endif

	// Launch the main GUI
	gui_start();

#ifndef TW_OEM_BUILD
	// Disable flashing of stock recovery
	TWFunc::Disable_Stock_Recovery_Replace();
	// Check for su to see if the device is rooted or not
	if (PartitionManager.Mount_By_Path("/system", false) && DataManager::GetIntValue("tw_mount_system_ro") == 0) {
		if (TWFunc::Path_Exists("/supersu/su") && !TWFunc::Path_Exists("/system/bin/su") && !TWFunc::Path_Exists("/system/xbin/su") && !TWFunc::Path_Exists("/system/bin/.ext/.su")) {
			// Device doesn't have su installed
			DataManager::SetValue("tw_busy", 1);
			if (gui_startPage("installsu", 1, 1) != 0) {
				LOGERR("Failed to start SuperSU install page.\n");
			}
		}
		sync();
		PartitionManager.UnMount_By_Path("/system", false);
	}
#endif

	// Reboot
	TWFunc::Update_Intent_File(Reboot_Value);
	TWFunc::Update_Log_File();
	gui_print("Rebooting...\n");
	string Reboot_Arg;
	DataManager::GetValue("tw_reboot_arg", Reboot_Arg);
	if (Reboot_Arg == "recovery")
		TWFunc::tw_reboot(rb_recovery);
	else if (Reboot_Arg == "poweroff")
		TWFunc::tw_reboot(rb_poweroff);
	else if (Reboot_Arg == "bootloader")
		TWFunc::tw_reboot(rb_bootloader);
	else if (Reboot_Arg == "download")
		TWFunc::tw_reboot(rb_download);
	else
		TWFunc::tw_reboot(rb_system);

	return 0;
}
Exemplo n.º 17
0
int
main(int argc, char *argv[])
{
  char *domdot, *verstr, *vertmp;
  int ppid = 0;
  int error;
  char *progname = NULL;		/* "amd" */
  char hostname[MAXHOSTNAMELEN + 1] = "localhost"; /* Hostname */

  /*
   * Make sure some built-in assumptions are true before we start
   */
  assert(sizeof(nfscookie) >= sizeof(u_int));
  assert(sizeof(int) >= 4);

  /*
   * Set processing status.
   */
  amd_state = Start;

  /*
   * Determine program name
   */
  if (argv[0]) {
    progname = strrchr(argv[0], '/');
    if (progname && progname[1])
      progname++;
    else
      progname = argv[0];
  }
  if (!progname)
    progname = "amd";
  am_set_progname(progname);

  /*
   * Initialize process id.  This is kept
   * cached since it is used for generating
   * and using file handles.
   */
  am_set_mypid();

  /*
   * Get local machine name
   */
  if (gethostname(hostname, sizeof(hostname)) < 0) {
    plog(XLOG_FATAL, "gethostname: %m");
    going_down(1);
  }
  hostname[sizeof(hostname) - 1] = '\0';

  /*
   * Check it makes sense
   */
  if (!*hostname) {
    plog(XLOG_FATAL, "host name is not set");
    going_down(1);
  }

  /*
   * Initialize global options structure.
   */
  init_global_options();

  /*
   * Partially initialize hostd[].  This
   * is completed in get_args().
   */
  if ((domdot = strchr(hostname, '.'))) {
    /*
     * Hostname already contains domainname.
     * Split out hostname and domainname
     * components
     */
    *domdot++ = '\0';
    hostdomain = domdot;
  }
  xstrlcpy(hostd, hostname, sizeof(hostd));
  am_set_hostname(hostname);

  /*
   * Setup signal handlers
   */
  /* SIGINT: trap interrupts for shutdowns */
  setup_sighandler(SIGINT, sigterm);
  /* SIGTERM: trap terminate so we can shutdown cleanly (some chance) */
  setup_sighandler(SIGTERM, sigterm);
  /* SIGHUP: hangups tell us to reload the cache */
  setup_sighandler(SIGHUP, sighup);
  /*
   * SIGCHLD: trap Death-of-a-child.  These allow us to pick up the exit
   * status of backgrounded mounts.  See "sched.c".
   */
  setup_sighandler(SIGCHLD, sigchld);
#ifdef HAVE_SIGACTION
  /* construct global "masked_sigs" used in nfs_start.c */
  sigemptyset(&masked_sigs);
  sigaddset(&masked_sigs, SIGINT);
  sigaddset(&masked_sigs, SIGTERM);
  sigaddset(&masked_sigs, SIGHUP);
  sigaddset(&masked_sigs, SIGCHLD);
#endif /* HAVE_SIGACTION */

  /*
   * Fix-up any umask problems.  Most systems default
   * to 002 which is not too convenient for our purposes
   */
  orig_umask = umask(0);

  /*
   * Figure out primary network name
   */
  getwire(&PrimNetName, &PrimNetNum);

  /*
   * Determine command-line arguments
   */
  get_args(argc, argv);

  /*
   * Log version information.
   */
  vertmp = get_version_string();
  verstr = strtok(vertmp, "\n");
  plog(XLOG_INFO, "AM-UTILS VERSION INFORMATION:");
  while (verstr) {
    plog(XLOG_INFO, "%s", verstr);
    verstr = strtok(NULL, "\n");
  }
  XFREE(vertmp);

  /*
   * Get our own IP address so that we can mount the automounter.  We pass
   * localhost_address which could be used as the default localhost
   * name/address in amu_get_myaddress().
   */
  amu_get_myaddress(&myipaddr, gopt.localhost_address);
  plog(XLOG_INFO, "My ip addr is %s", inet_ntoa(myipaddr));

  /* avoid hanging on other NFS servers if started elsewhere */
  if (chdir("/") < 0)
    plog(XLOG_INFO, "cannot chdir to /: %m");

  /*
   * Now check we are root.
   */
  if (geteuid() != 0) {
    plog(XLOG_FATAL, "Must be root to mount filesystems (euid = %ld)", (long) geteuid());
    going_down(1);
  }

#ifdef HAVE_MAP_NIS
  /*
   * If the domain was specified then bind it here
   * to circumvent any default bindings that may
   * be done in the C library.
   */
  if (gopt.nis_domain && yp_bind(gopt.nis_domain)) {
    plog(XLOG_FATAL, "Can't bind to NIS domain \"%s\"", gopt.nis_domain);
    going_down(1);
  }
#endif /* HAVE_MAP_NIS */

  if (!amuDebug(D_DAEMON))
    ppid = daemon_mode();

  /*
   * Lock process text and data segment in memory.
   */
  if (gopt.flags & CFM_PROCESS_LOCK) {
    do_memory_locking();
  }

  do_mapc_reload = clocktime(NULL) + gopt.map_reload_interval;

  /*
   * Register automounter with system.
   */
  error = mount_automounter(ppid);
  if (error && ppid)
    kill(ppid, SIGALRM);

#ifdef HAVE_FS_AUTOFS
  /*
   * XXX this should be part of going_down(), but I can't move it there
   * because it would be calling non-library code from the library... ugh
   */
  if (amd_use_autofs)
    destroy_autofs_service();
#endif /* HAVE_FS_AUTOFS */

  going_down(error);

  abort();
  return 1; /* should never get here */
}
Exemplo n.º 18
0
void outputFunction(FILE *fp, ClassInfo *data)
{
  int i;
  int args_ok;
  unsigned int rType =
    (currentFunction->ReturnType & VTK_PARSE_UNQUALIFIED_TYPE);
  const char *jniFunction = 0;
  char *jniFunctionNew = 0;
  char *jniFunctionOld = 0;
  size_t j;
  CurrentData = data;

  args_ok = checkFunctionSignature(data);

  /* handle DataReader SetBinaryInputString as a special case */
  if (!strcmp("SetBinaryInputString",currentFunction->Name) &&
      (!strcmp("vtkDataReader",data->Name) ||
       !strcmp("vtkStructuredGridReader",data->Name) ||
       !strcmp("vtkRectilinearGridReader",data->Name) ||
       !strcmp("vtkUnstructuredGridReader",data->Name) ||
       !strcmp("vtkStructuredPointsReader",data->Name) ||
       !strcmp("vtkPolyDataReader",data->Name)))
  {
    if(currentFunction->IsLegacy)
    {
      fprintf(fp,"#if !defined(VTK_LEGACY_REMOVE)\n");
    }
    HandleDataReader(fp,data);
    if(currentFunction->IsLegacy)
    {
      fprintf(fp,"#endif\n");
    }
    wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
    numberOfWrappedFunctions++;
  }

  if (currentFunction->IsPublic && args_ok &&
      strcmp(data->Name,currentFunction->Name) &&
      strcmp(data->Name, currentFunction->Name + 1))
  {
    /* make sure we haven't already done one of these */
    if (!DoneOne())
    {
      fprintf(fp,"\n");

      /* Underscores are escaped in method names, see
           http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp133
         VTK class names contain no underscore and do not need to be escaped.  */
      jniFunction = currentFunction->Name;
      jniFunctionOld = 0;
      j = 0;
      while (jniFunction[j] != '\0')
      {
        /* replace "_" with "_1" */
        if (jniFunction[j] == '_')
        {
          j++;
          jniFunctionNew = (char *)malloc(strlen(jniFunction) + 2);
          strncpy(jniFunctionNew, jniFunction, j);
          jniFunctionNew[j] = '1';
          strcpy(&jniFunctionNew[j+1], &jniFunction[j]);
          free(jniFunctionOld);
          jniFunctionOld = jniFunctionNew;
          jniFunction = jniFunctionNew;
        }
        j++;
      }

      if(currentFunction->IsLegacy)
      {
        fprintf(fp,"#if !defined(VTK_LEGACY_REMOVE)\n");
      }
      fprintf(fp,"extern \"C\" JNIEXPORT ");
      return_result(fp);
      fprintf(fp," JNICALL Java_vtk_%s_%s_1%i(JNIEnv *env, jobject obj",
              data->Name, jniFunction, numberOfWrappedFunctions);

      for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
        fprintf(fp,",");
        output_proto_vars(fp, i);

        /* ignore args after function pointer */
        if (currentFunction->ArgTypes[i] == VTK_PARSE_FUNCTION)
        {
          break;
        }
      }
      fprintf(fp,")\n{\n");

      /* get the object pointer */
      fprintf(fp,"  %s *op;\n",data->Name);

      /* process the args */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
        output_temp(fp, i, currentFunction->ArgTypes[i],
                   currentFunction->ArgClasses[i],
                   currentFunction->ArgCounts[i]);

        /* ignore args after function pointer */
        if (currentFunction->ArgTypes[i] == VTK_PARSE_FUNCTION)
        {
          break;
        }
      }
      output_temp(fp, MAX_ARGS,currentFunction->ReturnType,
                  currentFunction->ReturnClass,0);

      /* now get the required args from the stack */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
        get_args(fp, i);

        /* ignore args after function pointer */
        if (currentFunction->ArgTypes[i] == VTK_PARSE_FUNCTION)
        {
          break;
        }
      }

      fprintf(fp,"\n  op = (%s *)vtkJavaGetPointerFromObject(env,obj);\n",
              data->Name);


      switch (rType)
      {
        case VTK_PARSE_VOID:
          fprintf(fp,"  op->%s(",currentFunction->Name);
          break;
        default:
          if ((rType & VTK_PARSE_INDIRECT) == VTK_PARSE_REF)
          {
            fprintf(fp,"  temp%i = &(op)->%s(",MAX_ARGS,currentFunction->Name);
          }
          else
          {
            fprintf(fp,"  temp%i = (op)->%s(",MAX_ARGS,currentFunction->Name);
          }
          break;
      }

      for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
        if (i)
        {
          fprintf(fp,",");
        }
        if (currentFunction->ArgTypes[i] == VTK_PARSE_FUNCTION)
        {
          fprintf(fp,"vtkJavaVoidFunc,(void *)temp%i",i);
          break;
        }
        else
        {
          fprintf(fp,"temp%i",i);
        }
      } /* for */

      fprintf(fp,");\n");

      if (currentFunction->NumberOfArguments == 2 &&
          currentFunction->ArgTypes[0] == VTK_PARSE_FUNCTION)
      {
        fprintf(fp,"  op->%sArgDelete(vtkJavaVoidFuncArgDelete);\n",
                jniFunction);
      }

      /* now copy and release any arrays */
      for (i = 0; i < currentFunction->NumberOfArguments; i++)
      {
        copy_and_release_args(fp, i);

        /* ignore args after function pointer */
        if (currentFunction->ArgTypes[i] == VTK_PARSE_FUNCTION)
        {
          break;
        }
      }
      do_return(fp);
      fprintf(fp,"}\n");
      if(currentFunction->IsLegacy)
      {
        fprintf(fp,"#endif\n");
      }

      wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
      numberOfWrappedFunctions++;
      if (jniFunctionNew)
      {
        free(jniFunctionNew);
        jniFunctionNew = 0;
      }
    } /* isDone() */
  } /* isAbstract */
}
Exemplo n.º 19
0
/*======== void parse_file () ==========
Inputs:   char * filename 
          struct matrix * transform, 
          struct matrix * pm,
          screen s
Returns: 

Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         l: add a line to the edge matrix - 
	    takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	 i: set the transform matrix to the identity matrix - 
	 s: create a scale matrix, 
	    then multiply the transform matrix by the scale matrix - 
	    takes 3 arguments (sx, sy, sz)
	 t: create a translation matrix, 
	    then multiply the transform matrix by the translation matrix - 
	    takes 3 arguments (tx, ty, tz)
	 x: create an x-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 y: create an y-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 z: create an z-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 a: apply the current transformation matrix to the 
	    edge matrix
	 v: draw the lines of the edge matrix to the screen
	    display the screen
	 g: draw the lines of the edge matrix to the screen
	    save the screen to a file -
	    takes 1 argument (file name)
	 q: end parsing

See the file script for an example of the file format


IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)

jdyrlandweaver
====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  FILE *f = fopen(filename,"r"); 

  //if there's no such file name, print message and exit
  if(f == NULL)
    {
      printf("You're giving me nothin', boy.");
      exit(1);
    }
  char *boof = (char*)malloc(50*sizeof(char)); //standard buffer to read from
  double *pts = (double*)malloc(6*sizeof(double)); //incase arguments have been indicated that are individual
                 //points
  color c; //felt i had to make a color
  c.red = MAX_COLOR;
  c.green = MAX_COLOR;
  c.blue = MAX_COLOR;
  
  
  while( fgets(boof,50,f) )
    {
      if( boof[0] == 'l') //add a line to edge matrix
	{ 
	  get_args(f,pts);
	  add_edge(pm,pts[0],pts[1],pts[2],pts[3],pts[4],pts[5]);
	}
      else if( boof[0] == 'i' ) //create an identity matrix
	{
	  ident(transform);
	}
      else if( boof[0] == 's' ) //scale matrix
	{
	  get_args(f,pts);
	 struct matrix *m = make_scale(pts[0],pts[1],pts[2]);
	 matrix_mult(m,transform);
	 free_matrix(m);
	 
	}
      else if( boof[0] == 't' ) //translate matrix
	{
	  get_args(f,pts);
	  struct matrix *m = make_translate(pts[0],pts[1],pts[2]);
	  matrix_mult(m,transform);
	  free_matrix(m);
	}
       else if( boof[0] == 'x' ) //rotation about x matrix
	{
	  get_args(f,pts);
	  struct matrix *m = make_rotX(pts[0]);
	  matrix_mult(m,transform);
	  free_matrix(m);
	} 
       else if( boof[0] == 'y' ) //rotation about y matrix
	{
	  get_args(f,pts);
	  struct matrix *m = make_rotY(pts[0]);
	  matrix_mult(m,transform);
	  free_matrix(m);
	} 
       else if( boof[0] == 'z' ) //rotation about z matrix
	{
	  get_args(f,pts);
	  struct matrix *m = make_rotZ(pts[0]);
	  matrix_mult(m,transform);
	  free_matrix(m);
	}
       else if( boof[0] == 'a' )
	 {
	   matrix_mult(transform,pm);
	 }
       else if( boof[0] == 'v')
	 {
	   clear_screen(s);
	   draw_lines(pm,s,c);
	   display(s);
	 }
       else if( boof[0] == 'g')
	 {
	   draw_lines(pm,s,c);
	   fgets(boof,50,f);
	   save_extension(s,boof);
	 }
       else if( boof[0] == 'q')
	 {
	   printf("Now exiting ...");
	   exit(1);
	 }
       else
	 {
	   printf("What the hell does %c mean?\n",boof[0]);
	   return;
	 }
    }
  }
Exemplo n.º 20
0
int main(int argc, char *argv[]) {
  int notdone=1;
  char buf[1024];
  int val[9], i, ch, code;
  time_t starttime, curtime;
  struct timeval tv;
  struct timezone tz;
  struct tm *ltime;
  int interval = 1;

  setup_vars();
  
  printf("Hello, World!\n");
  if (get_args(argc, argv) != 0) {
    show_usage();
    exit(1);
  }
  for(ch=0;ch<CHMAX;ch++) {
    clear_reading_storage(ch);
  }
  clear_inputs(interval);
  make_line();
  if ((fd = open(dsrc, O_RDWR|O_NONBLOCK)) < 0) {
    printf("couldn't open data source file\n");
    exit(1);
  }
  start_serial_io(fd, baud);
  my_fgets(buf, 1000, fd);
  notdone = 0;
  printf("syncing time...\n");
  while (notdone < 2) {
    starttime = time(NULL);
    ltime = localtime(&starttime);
    if ((ltime->tm_sec % interval) == 0) {
      notdone++;
    } else {
      /* sleep(1); */
      my_fgets(buf, 1000, fd);
    }
    curday = ltime->tm_mday;
    set_curdatestring(ltime);
  }
  if (log_file_name != NULL) {
    start_log_file();
  }
  printf("starting at %010d\n", (int) starttime);
  notdone = 1;
  while (notdone) {
    /* take care of time first */
    curtime = time(NULL);
    if (curtime >= (starttime + interval)) {
      if (logfp != NULL) {
        fprintf(logfp, "%010d (%s)", (int) starttime, safe_ctime(&starttime));
      } else {
        printf("%010d (%s)", (int) starttime, safe_ctime(&starttime));
      }
      for (ch=0;ch<CHMAX;ch++) {
        dump_reading(ch);
        clear_reading_storage(ch);
      }
      /* dump_inputs(); */
      if (logfp != NULL) {
        fprintf(logfp, "\n");
      } else {
        printf("\n");
      }
      starttime = curtime;
      ltime = localtime(&curtime); /* ltime is needed here and ctime messes it up */
      /* check for the day change here so that the last second of yesterday
         ends up in *yesterday's* log and this days data ends up in this
         days log */
      if (ltime->tm_mday != curday) {
        set_curdatestring(ltime);
        if (log_file_name != NULL) {
          fclose(logfp);
          start_log_file();
        }
        curday = ltime->tm_mday;
      } else {
        /* flush whenever a line is written */
        if (logfp != NULL) {
          fflush(logfp);
        } else {
          fflush(stdout);
        }
      }
    }
    if (my_fgets(buf, 1000, fd) == 1) {
      if (strlen(buf) > 4) {
        /* printf("%s", buf); */
        buf[strlen(buf) - 1] = 0;
        chop_input(buf, val, &code);
        /* test_code_change(~code, curtime); */
        for (ch=0;ch<CHMAX;ch++) {
          add_reading(ch, val[ch+1]);
        }
      }
    } else { /* don't consume 100% of the processor. */
      usleep(1000);
    }
    fflush(stdout);
  }
  exit(0);
}
Exemplo n.º 21
0
static int
edit_read_syntax_rules (WEdit * edit, FILE * f, char **args, int args_size)
{
    FILE *g = NULL;
    char *fg, *bg, *attrs;
    char last_fg[32] = "", last_bg[32] = "", last_attrs[64] = "";
    char whole_right[512];
    char whole_left[512];
    char *l = NULL;
    int save_line = 0, line = 0;
    context_rule_t *c = NULL;
    gboolean no_words = TRUE;
    int result = 0;

    args[0] = NULL;
    edit->is_case_insensitive = FALSE;

    strcpy (whole_left, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_01234567890");
    strcpy (whole_right, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_01234567890");

    edit->rules = g_ptr_array_new ();

    if (edit->defines == NULL)
        edit->defines = g_tree_new ((GCompareFunc) strcmp);

    while (TRUE)
    {
        char **a;
        size_t len;
        int argc;

        line++;
        l = NULL;

        len = read_one_line (&l, f);
        if (len != 0)
            xx_lowerize_line (edit, l, len);
        else
        {
            if (g == NULL)
                break;

            fclose (f);
            f = g;
            g = NULL;
            line = save_line + 1;
            MC_PTR_FREE (error_file_name);
            MC_PTR_FREE (l);
            len = read_one_line (&l, f);
            if (len == 0)
                break;
            xx_lowerize_line (edit, l, len);
        }

        argc = get_args (l, args, args_size);
        a = args + 1;
        if (args[0] == NULL)
        {
            /* do nothing */
        }
        else if (strcmp (args[0], "include") == 0)
        {
            if (g != NULL || argc != 2)
            {
                result = line;
                break;
            }
            g = f;
            f = open_include_file (args[1]);
            if (f == NULL)
            {
                MC_PTR_FREE (error_file_name);
                result = line;
                break;
            }
            save_line = line;
            line = 0;
        }
        else if (strcmp (args[0], "caseinsensitive") == 0)
        {
            edit->is_case_insensitive = TRUE;
        }
        else if (strcmp (args[0], "wholechars") == 0)
        {
            check_a;
            if (strcmp (*a, "left") == 0)
            {
                a++;
                g_strlcpy (whole_left, *a, sizeof (whole_left));
            }
            else if (strcmp (*a, "right") == 0)
            {
                a++;
                g_strlcpy (whole_right, *a, sizeof (whole_right));
            }
            else
            {
                g_strlcpy (whole_left, *a, sizeof (whole_left));
                g_strlcpy (whole_right, *a, sizeof (whole_right));
            }
            a++;
            check_not_a;
        }
        else if (strcmp (args[0], "context") == 0)
        {
            syntax_keyword_t *k;

            check_a;
            if (edit->rules->len == 0)
            {
                /* first context is the default */
                if (strcmp (*a, "default") != 0)
                    break_a;

                a++;
                c = g_new0 (context_rule_t, 1);
                g_ptr_array_add (edit->rules, c);
                c->left = g_strdup (" ");
                c->right = g_strdup (" ");
            }
            else
            {
                /* Start new context.  */
                c = g_new0 (context_rule_t, 1);
                g_ptr_array_add (edit->rules, c);
                if (strcmp (*a, "exclusive") == 0)
                {
                    a++;
                    c->between_delimiters = TRUE;
                }
                check_a;
                if (strcmp (*a, "whole") == 0)
                {
                    a++;
                    c->whole_word_chars_left = g_strdup (whole_left);
                    c->whole_word_chars_right = g_strdup (whole_right);
                }
                else if (strcmp (*a, "wholeleft") == 0)
                {
                    a++;
                    c->whole_word_chars_left = g_strdup (whole_left);
                }
                else if (strcmp (*a, "wholeright") == 0)
                {
                    a++;
                    c->whole_word_chars_right = g_strdup (whole_right);
                }
                check_a;
                if (strcmp (*a, "linestart") == 0)
                {
                    a++;
                    c->line_start_left = TRUE;
                }
                check_a;
                c->left = g_strdup (*a++);
                check_a;
                if (strcmp (*a, "linestart") == 0)
                {
                    a++;
                    c->line_start_right = TRUE;
                }
                check_a;
                c->right = g_strdup (*a++);
                c->first_left = *c->left;
                c->first_right = *c->right;
            }
            c->keyword = g_ptr_array_new ();
            k = g_new0 (syntax_keyword_t, 1);
            g_ptr_array_add (c->keyword, k);
            no_words = FALSE;
            subst_defines (edit->defines, a, &args[ARGS_LEN]);
            fg = *a;
            if (*a != NULL)
                a++;
            bg = *a;
            if (*a != NULL)
                a++;
            attrs = *a;
            if (*a != NULL)
                a++;
            g_strlcpy (last_fg, fg != NULL ? fg : "", sizeof (last_fg));
            g_strlcpy (last_bg, bg != NULL ? bg : "", sizeof (last_bg));
            g_strlcpy (last_attrs, attrs != NULL ? attrs : "", sizeof (last_attrs));
            k->color = this_try_alloc_color_pair (fg, bg, attrs);
            k->keyword = g_strdup (" ");
            check_not_a;
        }
        else if (strcmp (args[0], "spellcheck") == 0)
        {
            if (c == NULL)
            {
                result = line;
                break;
            }
            c->spelling = TRUE;
        }
        else if (strcmp (args[0], "keyword") == 0)
        {
            context_rule_t *last_rule;
            syntax_keyword_t *k;

            if (no_words)
                break_a;
            check_a;
            last_rule = CONTEXT_RULE (g_ptr_array_index (edit->rules, edit->rules->len - 1));
            k = g_new0 (syntax_keyword_t, 1);
            g_ptr_array_add (last_rule->keyword, k);
            if (strcmp (*a, "whole") == 0)
            {
                a++;
                k->whole_word_chars_left = g_strdup (whole_left);
                k->whole_word_chars_right = g_strdup (whole_right);
            }
            else if (strcmp (*a, "wholeleft") == 0)
            {
                a++;
                k->whole_word_chars_left = g_strdup (whole_left);
            }
            else if (strcmp (*a, "wholeright") == 0)
            {
                a++;
                k->whole_word_chars_right = g_strdup (whole_right);
            }
            check_a;
            if (strcmp (*a, "linestart") == 0)
            {
                a++;
                k->line_start = TRUE;
            }
            check_a;
            if (strcmp (*a, "whole") == 0)
                break_a;

            k->keyword = g_strdup (*a++);
            subst_defines (edit->defines, a, &args[ARGS_LEN]);
            fg = *a;
            if (*a != NULL)
                a++;
            bg = *a;
            if (*a != NULL)
                a++;
            attrs = *a;
            if (*a != NULL)
                a++;
            if (fg == NULL)
                fg = last_fg;
            if (bg == NULL)
                bg = last_bg;
            if (attrs == NULL)
                attrs = last_attrs;
            k->color = this_try_alloc_color_pair (fg, bg, attrs);
            check_not_a;
        }
        else if (*(args[0]) == '#')
        {
            /* do nothing for comment */
        }
        else if (strcmp (args[0], "file") == 0)
        {
            break;
        }
        else if (strcmp (args[0], "define") == 0)
        {
            char *key = *a++;
            char **argv;

            if (argc < 3)
                break_a;
            argv = g_tree_lookup (edit->defines, key);
            if (argv != NULL)
                mc_defines_destroy (NULL, argv, NULL);
            else
                key = g_strdup (key);

            argv = g_new (char *, argc - 1);
            g_tree_insert (edit->defines, key, argv);
            while (*a != NULL)
                *argv++ = g_strdup (*a++);
            *argv = NULL;
        }
        else
        {
Exemplo n.º 22
0
/******************************************************************************
METHOD:  l8cfmask

PURPOSE:  the main routine for fmask in C

RETURN VALUE:
Type = int
Value           Description
-----           -----------
ERROR           An error occurred during processing of the l8cfmask
SUCCESS         Processing was successful

PROJECT:  Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
3/15/2013   Song Guo         Original Development
5/14/2013   Song Guo         Added in Polar Stereographic support
7/17/2013   Song Guo         Added in Map info 
8/15/2013   Song Guo         Modified to use TOA reflectance file 
                             as input instead of metadata file
Oct/2014    Ron Dilley       Modified to utilize the ESPA internal raw binary
                             file format

NOTES: type ./l8cfmask --help for information to run the code
******************************************************************************/
int
main (int argc, char *argv[])
{
    char errstr[MAX_STR_LEN];     /* error string */
    char *cptr = NULL;            /* pointer to the file extension */
    char *xml_name = NULL;        /* input XML filename */
    char directory[MAX_STR_LEN];  /* input/output data directory */
    char extension[MAX_STR_LEN];  /* input TOA file extension */
    int ib;                       /* band counters */
    Input_t *input = NULL;        /* input data and meta data */
    char envi_file[MAX_STR_LEN];  /* output ENVI file name */
    char scene_name[MAX_STR_LEN]; /* input data scene name */
    unsigned char **pixel_mask;   /* pixel mask */
    unsigned char **conf_mask;    /* confidence mask */
    int status;               /* return value from function call */
    float clear_ptm;          /* percent of clear-sky pixels */
    float t_templ = 0.0;      /* percentile of low background temperature */
    float t_temph = 0.0;      /* percentile of high background temperature */
    Output_t *output = NULL;  /* output structure and metadata */
    bool verbose;             /* verbose flag for printing messages */
    bool use_l8_cirrus;       /* should we use L8 cirrus cloud bit results? */
    int cldpix = 2;           /* Default buffer for cloud pixel dilate */
    int sdpix = 2;            /* Default buffer for shadow pixel dilate */
    float cloud_prob;         /* Default cloud probability */
    float sun_azi_temp = 0.0; /* Keep the original sun azimuth angle */
    int max_cloud_pixels; /* Maximum cloud pixel number in cloud division */
    Espa_internal_meta_t xml_metadata; /* XML metadata structure */
    Envi_header_t envi_hdr;            /* output ENVI header information */

    time_t now;
    time (&now);
    printf ("CFmask start_time=%s\n", ctime (&now));

    /* Read the command-line arguments, including the name of the input
       Landsat TOA reflectance product and the DEM */
    status = get_args (argc, argv, &xml_name, &cloud_prob, &cldpix,
                       &sdpix, &max_cloud_pixels, &use_l8_cirrus, &verbose);
    if (status != SUCCESS)
    {
        sprintf (errstr, "calling get_args");
        CFMASK_ERROR (errstr, "main");
    }

    /* Validate the input metadata file */
    if (validate_xml_file (xml_name) != SUCCESS)
    {                           /* Error messages already written */
        CFMASK_ERROR (errstr, "main");
    }

    /* Initialize the metadata structure */
    init_metadata_struct (&xml_metadata);

    /* Parse the metadata file into our internal metadata structure; also
       allocates space as needed for various pointers in the global and band
       metadata */
    if (parse_metadata (xml_name, &xml_metadata) != SUCCESS)
    {                           /* Error messages already written */
        CFMASK_ERROR (errstr, "main");
    }

    /* Verify supported satellites */
    if (strcmp (xml_metadata.global.satellite, "LANDSAT_8") != 0)
    {
        sprintf (errstr, "Unsupported satellite sensor");
        CFMASK_ERROR (errstr, "main");
    }

    /* Split the filename to obtain the directory, scene name, and extension */
    split_filename (xml_name, directory, scene_name, extension);
    if (verbose)
        printf ("directory, scene_name, extension=%s,%s,%s\n",
                directory, scene_name, extension);

    /* Open input file, read metadata, and set up buffers */
    input = OpenInput (&xml_metadata);
    if (input == NULL)
    {
        sprintf (errstr, "opening the TOA and brightness temp files in: %s",
                 xml_name);
        CFMASK_ERROR (errstr, "main");
    }

    if (verbose)
    {
        /* Print some info to show how the input metadata works */
        printf ("DEBUG: Number of input TOA bands: %d\n", input->nband);
        printf ("DEBUG: Number of input thermal bands: %d\n", 1);
        printf ("DEBUG: Number of input TOA lines: %d\n", input->size.l);
        printf ("DEBUG: Number of input TOA samples: %d\n", input->size.s);
        printf ("DEBUG: ACQUISITION_DATE.DOY is %d\n",
                input->meta.acq_date.doy);
        printf ("DEBUG: Fill value is %d\n", input->meta.fill);
        for (ib = 0; ib < input->nband; ib++)
        {
            printf ("DEBUG: Band %d-->\n", ib);
            printf ("DEBUG:   band satu_value_ref: %d\n",
                    input->meta.satu_value_ref[ib]);
            printf ("DEBUG:   band satu_value_max: %d\n",
                    input->meta.satu_value_max[ib]);
            printf ("DEBUG:   band gains: %f, band biases: %f\n",
                    input->meta.gain[ib], input->meta.bias[ib]);
        }
        printf ("DEBUG: Thermal Band (Band 10) -->\n");
        printf ("DEBUG:   therm_satu_value_ref: %d\n",
                input->meta.therm_satu_value_ref);
        printf ("DEBUG:   therm_satu_value_max: %d\n",
                input->meta.therm_satu_value_max);
        printf ("DEBUG:   therm_gain: %f, therm_bias: %f\n",
                input->meta.gain_th, input->meta.bias_th);

        printf ("DEBUG: SUN AZIMUTH is %f\n", input->meta.sun_az);
        printf ("DEBUG: SUN ZENITH is %f\n", input->meta.sun_zen);
    }

    /* If the scene is an ascending polar scene (flipped upside down), then
       the solar azimuth needs to be adjusted by 180 degrees.  The scene in
       this case would be north down and the solar azimuth is based on north
       being up clock-wise direction. Flip the south to be up will not change
       the actual sun location, with the below relations, the solar azimuth
       angle will need add in 180.0 for correct sun location */
    if (input->meta.ul_corner.is_fill &&
        input->meta.lr_corner.is_fill &&
        (input->meta.ul_corner.lat - input->meta.lr_corner.lat) < MINSIGMA)
    {
        /* Keep the original solar azimuth angle */
        sun_azi_temp = input->meta.sun_az;
        input->meta.sun_az += 180.0;
        if ((input->meta.sun_az - 360.0) > MINSIGMA)
            input->meta.sun_az -= 360.0;
        if (verbose)
            printf ("  Polar or ascending scene."
                    "  Readjusting solar azimuth by 180 degrees.\n"
                    "  New value: %f degrees\n", input->meta.sun_az);
    }

    /* Dynamic allocate the 2d mask memory */
    pixel_mask = (unsigned char **) allocate_2d_array (input->size.l,
                                                       input->size.s,
                                                       sizeof (unsigned char));
    if (pixel_mask == NULL)
    {
        sprintf (errstr, "Allocating pixel mask memory");
        CFMASK_ERROR (errstr, "main");
    }

    conf_mask = (unsigned char **) allocate_2d_array (input->size.l,
                                                      input->size.s,
                                                      sizeof (unsigned char));
    if (conf_mask == NULL)
    {
        sprintf (errstr, "Allocating confidence mask memory");
        CFMASK_ERROR (errstr, "main");
    }

    /* Initialize the mask to clear data */
    int row, col;
    for (row = 0; row < input->size.l; row++)
        for (col = 0; col < input->size.s; col++)
        {
            pixel_mask[row][col] = MASK_CLEAR_LAND;
            conf_mask[row][col] = CLOUD_CONFIDENCE_NONE;
        }

    /* Build the potential cloud, shadow, snow, water mask */
    status = potential_cloud_shadow_snow_mask (input, cloud_prob, &clear_ptm,
                                               &t_templ, &t_temph, pixel_mask,
                                               conf_mask, use_l8_cirrus,
                                               verbose);
    if (status != SUCCESS)
    {
        sprintf (errstr, "processing potential_cloud_shadow_snow_mask");
        CFMASK_ERROR (errstr, "main");
    }

    printf ("Pcloud done, starting cloud/shadow match\n");

    /* Build the final cloud shadow based on geometry matching and
       combine the final cloud, shadow, snow, water masks into fmask
       the pixel_mask is a bit mask as input and a value mask as output */
    status = object_cloud_shadow_match (input, clear_ptm, t_templ, t_temph,
                                        cldpix, sdpix, max_cloud_pixels,
                                        pixel_mask, verbose);
    if (status != SUCCESS)
    {
        sprintf (errstr, "processing object_cloud_and_shadow_match");
        CFMASK_ERROR (errstr, "main");
    }

    /* Reassign solar azimuth angle for output purpose if south up north
       down scene is involved */
    if (input->meta.ul_corner.is_fill &&
        input->meta.lr_corner.is_fill &&
        (input->meta.ul_corner.lat - input->meta.lr_corner.lat) < MINSIGMA)
        input->meta.sun_az = sun_azi_temp;

    /* Open the output file */
    output = OpenOutput (&xml_metadata, input);
    if (output == NULL)
    {                           /* error message already printed */
        sprintf (errstr, "Opening output file");
        CFMASK_ERROR (errstr, "main");
    }

    if (!PutOutput (output, pixel_mask))
    {
        sprintf (errstr, "Writing output fmask files\n");
        CFMASK_ERROR (errstr, "main");
    }

    /* Close the output file */
    if (!CloseOutput (output))
    {
        sprintf (errstr, "closing output file");
        CFMASK_ERROR (errstr, "main");
    }

    /* Create the ENVI header file this band */
    if (create_envi_struct (&output->metadata.band[0], &xml_metadata.global,
                            &envi_hdr) != SUCCESS)
    {
        sprintf (errstr, "Creating ENVI header structure.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Write the ENVI header */
    strcpy (envi_file, output->metadata.band[0].file_name);
    cptr = strchr (envi_file, '.');
    if (cptr == NULL)
    {
        sprintf (errstr, "error in ENVI header filename");
        CFMASK_ERROR (errstr, "main");
    }

    strcpy (cptr, ".hdr");
    if (write_envi_hdr (envi_file, &envi_hdr) != SUCCESS)
    {
        sprintf (errstr, "Writing ENVI header file.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Append the cfmask band to the XML file */
    if (append_metadata (output->nband, output->metadata.band, xml_name)
        != SUCCESS)
    {
        sprintf (errstr, "Appending spectral index bands to XML file.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Free the structure */
    if (!FreeOutput (output))
    {
        sprintf (errstr, "freeing output file structure");
        CFMASK_ERROR (errstr, "main");
    }

    output = OpenOutputConfidence (&xml_metadata, input);
    if (output == NULL)
    {                           /* error message already printed */
        sprintf (errstr, "Opening output file");
        CFMASK_ERROR (errstr, "main");
    }

    if (!PutOutput (output, conf_mask))
    {
        sprintf (errstr, "Writing output fmask files\n");
        CFMASK_ERROR (errstr, "main");
    }

    /* Close the output file */
    if (!CloseOutput (output))
    {
        sprintf (errstr, "closing output file");
        CFMASK_ERROR (errstr, "main");
    }

    /* Create the ENVI header file this band */
    if (create_envi_struct (&output->metadata.band[0], &xml_metadata.global,
                            &envi_hdr) != SUCCESS)
    {
        sprintf (errstr, "Creating ENVI header structure.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Write the ENVI header */
    strcpy (envi_file, output->metadata.band[0].file_name);
    cptr = strchr (envi_file, '.');
    if (cptr == NULL)
    {
        sprintf (errstr, "error in ENVI header filename");
        CFMASK_ERROR (errstr, "main");
    }

    strcpy (cptr, ".hdr");
    if (write_envi_hdr (envi_file, &envi_hdr) != SUCCESS)
    {
        sprintf (errstr, "Writing ENVI header file.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Append the cfmask band to the XML file */
    if (append_metadata (output->nband, output->metadata.band, xml_name)
        != SUCCESS)
    {
        sprintf (errstr, "Appending spectral index bands to XML file.");
        CFMASK_ERROR (errstr, "main");
    }

    /* Free the structure */
    if (!FreeOutput (output))
    {
        sprintf (errstr, "freeing output file structure");
        CFMASK_ERROR (errstr, "main");
    }

    /* Free the metadata structure */
    free_metadata (&xml_metadata);

    /* Free the pixel mask */
    status = free_2d_array ((void **) pixel_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing pixel mask memory");
        CFMASK_ERROR (errstr, "main");
    }

    status = free_2d_array ((void **) conf_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing confidence mask memory");
        CFMASK_ERROR (errstr, "main");
    }

    /* Close the input file and free the structure */
    CloseInput (input);
    FreeInput (input);

    free (xml_name);

    printf ("Processing complete.\n");
    time (&now);
    printf ("CFmask end_time=%s\n", ctime (&now));

    return SUCCESS;
}
Exemplo n.º 23
0
void nsenter()
{
	int argc, c;
	char **argv;
	get_args(&argc, &argv);

	// check argv 0 to ensure that we are supposed to setns
	// we use strncmp to test for a value of "nsenter" but also allows alternate implmentations
	// after the setns code path to continue to use the argv 0 to determine actions to be run
	// resulting in the ability to specify "nsenter-mknod", "nsenter-exec", etc...
	if (strncmp(argv[0], kNsEnter, strlen(kNsEnter)) != 0) {
		return;
	}

	if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) == -1) {
                fprintf(stderr, "nsenter: failed to set child subreaper: %s", strerror(errno));
                exit(1);
        }

	static const struct option longopts[] = {
		{"nspid", required_argument, NULL, 'n'},
		{"console", required_argument, NULL, 't'},
		{NULL, 0, NULL, 0}
	};
    
	pid_t init_pid = -1;
	char *init_pid_str = NULL;
	char *console = NULL;
	while ((c = getopt_long_only(argc, argv, "n:c:", longopts, NULL)) != -1) {
		switch (c) {
		case 'n':
			init_pid_str = optarg;
			break;
		case 't':
			console = optarg;
			break;
		}
	}

	if (init_pid_str == NULL) {
		print_usage();
		exit(1);
	}

	init_pid = strtol(init_pid_str, NULL, 10);
	if ((init_pid == 0 && errno == EINVAL) || errno == ERANGE) {
		fprintf(stderr,
			"nsenter: Failed to parse PID from \"%s\" with output \"%d\" and error: \"%s\"\n",
			init_pid_str, init_pid, strerror(errno));
		print_usage();
		exit(1);
	}

	argc -= 3;
	argv += 3;

	if (setsid() == -1) {
		fprintf(stderr, "setsid failed. Error: %s\n", strerror(errno));
		exit(1);
	}
	// before we setns we need to dup the console
	int consolefd = -1;
	if (console != NULL) {
		consolefd = open(console, O_RDWR);
		if (consolefd < 0) {
			fprintf(stderr,
				"nsenter: failed to open console %s %s\n",
				console, strerror(errno));
			exit(1);
		}
	}
	// Setns on all supported namespaces.
	char ns_dir[PATH_MAX];
	memset(ns_dir, 0, PATH_MAX);
	snprintf(ns_dir, PATH_MAX - 1, "/proc/%d/ns/", init_pid);

	char *namespaces[] = { "ipc", "uts", "net", "pid", "mnt" };
	const int num = sizeof(namespaces) / sizeof(char *);
	int i;
	for (i = 0; i < num; i++) {
		char buf[PATH_MAX];
		memset(buf, 0, PATH_MAX);
		snprintf(buf, PATH_MAX - 1, "%s%s", ns_dir, namespaces[i]);
		int fd = open(buf, O_RDONLY);
		if (fd == -1) {
			// Ignore nonexistent namespaces.
			if (errno == ENOENT)
				continue;

			fprintf(stderr,
				"nsenter: Failed to open ns file \"%s\" for ns \"%s\" with error: \"%s\"\n",
				buf, namespaces[i], strerror(errno));
			exit(1);
		}
		// Set the namespace.
		if (setns(fd, 0) == -1) {
			fprintf(stderr,
				"nsenter: Failed to setns for \"%s\" with error: \"%s\"\n",
				namespaces[i], strerror(errno));
			exit(1);
		}
		close(fd);
	}

	// We must fork to actually enter the PID namespace.
	int child = fork();
	if (child == 0) {
		if (consolefd != -1) {
			if (dup2(consolefd, STDIN_FILENO) != 0) {
				fprintf(stderr, "nsenter: failed to dup 0 %s\n",
					strerror(errno));
				exit(1);
			}
			if (dup2(consolefd, STDOUT_FILENO) != STDOUT_FILENO) {
				fprintf(stderr, "nsenter: failed to dup 1 %s\n",
					strerror(errno));
				exit(1);
			}
			if (dup2(consolefd, STDERR_FILENO) != STDERR_FILENO) {
				fprintf(stderr, "nsenter: failed to dup 2 %s\n",
					strerror(errno));
				exit(1);
			}
		}
		// Finish executing, let the Go runtime take over.
		return;
	} else {
		// Parent, wait for the child.
		int status = 0;
		if (waitpid(child, &status, 0) == -1) {
			fprintf(stderr,
				"nsenter: Failed to waitpid with error: \"%s\"\n",
				strerror(errno));
			exit(1);
		}
		// Forward the child's exit code or re-send its death signal.
		if (WIFEXITED(status)) {
			exit(WEXITSTATUS(status));
		} else if (WIFSIGNALED(status)) {
			kill(getpid(), WTERMSIG(status));
		}

		exit(1);
	}

	return;
}
Exemplo n.º 24
0
Arquivo: r3.c Projeto: gotclout/randy
int main(int argc, char* argv[])
{
  //create a new command structure to imitate argc/argv
  CmdData* cmd = CmdData_Create();
  int        i = 1;

  cmd->argc   = argc - 1;                 //ignore program name
  cmd->strcmd = (char*) malloc(MAX_ARG); //allocate a string for using system
  memset(cmd->strcmd, 0, MAX_ARG);
  for( ; i < argc; ++i)              //copy argv
  {
    cmd->args[i - 1] = (char*) malloc(strlen(argv[i]));
    strcpy(cmd->args[i - 1], argv[i]);
    strcat(cmd->strcmd, argv[i]);
    if(i + 1 < argc) strcat(cmd->strcmd, " ");
  }

  //Example Could Have Used My system Implementation
  //Rather than popen
  /**
   * Test this after the rest is compiled and tested
   *
   * Be sure to modify your working system by removing main
   * including the sys.h file and removing the headers in the .c file
   *
  if(strstr(cmd->strcmd, "ping") != 0)
  {
    system(cmd->strcmd);
  }
  */


  do  //process accepted commands until user enters q
  {
    if(cmd->argc >= 3 && strcmp(cmd->args[0], "grep") == 0)
    {
      myGrep(cmd->args, cmd->argc);
    }
    else if(cmd->argc >= 1 && strcmp(cmd->args[0],"ps") == 0)
    {
      myPS(cmd->args,cmd->argc);
    }
    else if(cmd->argc >= 1 && strcmp(cmd->args[0], "ls") == 0)
    {
      myLS(cmd->args, cmd->argc);
    }
    else if(cmd->argc >= 3 && strcmp(cmd->args[0], "diff") == 0)
    {
      myDiff(cmd->args, cmd->argc);
    }
    else
    {
      fprintf(stderr, "Accepted Commands are grep, ps, ls, diff\n");
    }

    printf("Please enter a command or press q to exit\n");

    CmdData_Init(&cmd);
  }
  while( get_args(cmd) && strcmp(CmdData_at(cmd, 0),"q"));


  if(cmd) CmdData_Free(&cmd);

  return 0;
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
    void anim_dir2mat(fastf_t *, const fastf_t *, const fastf_t *), anim_y_p_r2mat(fastf_t *, double, double, double), anim_add_trans(fastf_t *, const fastf_t *, const fastf_t *), anim_mat_print(FILE *, const fastf_t *, int);
    int get_args(int argc, char **argv), track_prep(void), val, frame, go, i, count;
    fastf_t y_rot, distance, yaw, pitch, roll;
    vect_t p1, p2, p3, dir, dir2, wheel_now, wheel_prev;
    vect_t zero, position, vdelta, temp, to_track, to_front;
    mat_t mat_v, wmat, mat_x;
    FILE *stream;
    int last_frame;

    VSETALL(zero, 0.0);
    VSETALL(to_track, 0.0);
    VSETALL(centroid, 0.0);
    VSETALL(rcentroid, 0.0);
    init_dist = y_rot = radius= 0.0;
    first_frame = num_wheels = steer = axes = cent = links_placed=0;
    num_wheels = num_links = last_frame = 0;
    MAT_IDN(mat_v);
    MAT_IDN(mat_x);
    MAT_IDN(wmat);
    MAT_IDN(m_axes);
    MAT_IDN(m_rev_axes);

    if (!get_args(argc, argv)) {
	fprintf(stderr, "anim_hardtrack: argument error.");
	return(-1);
    }

    if (axes || cent ) {
	/* vehicle has own reference frame */
	anim_add_trans(m_axes, centroid, zero);
	anim_add_trans(m_rev_axes, zero, rcentroid);
    }

    /* get track information from specified file */

    if (!(stream = fopen(*(argv+bu_optind), "rb"))) {
	fprintf(stderr, "Anim_hardtrack: Could not open file %s.\n", *(argv+bu_optind));
	return(0);
    }
    num_wheels = -1;
    if (radius) {
	while (!feof(stream)) {
	    fscanf(stream, "%*f %*f %*f");
	    num_wheels++;
	}
    } else {
	while (!feof(stream)) {
	    fscanf(stream, "%*f %*f %*f %*f");
	    num_wheels++;
	}
    }
    rewind(stream);

    /*allocate memory for track information*/
    x = (struct all *) bu_calloc(num_wheels, sizeof(struct all), "struct all");
    /*read rest of track info */
    for (i=0;i<NW;i++) {
	fscanf(stream, "%lf %lf %lf", temp, temp+1, temp+2);
	if (radius)
	    x[i].w.rad = radius;
	else
	    fscanf(stream, "%lf", & x[i].w.rad);
	MAT4X3PNT(x[i].w.pos, m_rev_axes, temp);
	if (i==0)
	    track_y = x[0].w.pos[1];
	else
	    x[i].w.pos[1] = track_y;
    }
    (void) fclose(stream);

    (void) track_prep();

    if (get_circumf) {
	printf("%.10g\n", tracklen);
	return(0);
    }

    /* initialize to_track */
    VSET(to_track, 0.0, track_y, 0.0);
    VSET(to_front, 1.0, 0.0, 0.0);

    if ((!print_link)&&(!print_wheel)) {
	fprintf(stderr, "anim_hardtrack: no ouput requested. Use -l or -w.\n");
	bu_exit(0, NULL);
    }
    /* main loop */
    distance = 0.0;
    if (!steer)
	frame = first_frame;
    else
	frame = first_frame-1;
    for (val = 3; val > 2; frame++) {
	go = 1;
	/*p2 is current position. p3 is next;p1 is previous*/
	VMOVE(p1, p2);
	VMOVE(p2, p3);
	scanf("%*f");/*time stamp*/
	val = scanf("%lf %lf %lf", p3, p3+1, p3 + 2);
	if (!steer) {
	    scanf("%lf %lf %lf", &yaw, &pitch, &roll);
	    anim_dy_p_r2mat(mat_v, yaw, pitch, roll);
	    anim_add_trans(mat_v, p3, rcentroid);
	}
	else {
	    /* analyze positions for steering */
	    /*get useful direction unit vectors*/
	    if (frame == first_frame) {
		/* first frame*/
		VSUBUNIT(dir, p3, p2);
		VMOVE(dir2, dir);
	    }
	    else if (val < 3) {
		/*last frame*/
		VSUBUNIT(dir, p2, p1);
		VMOVE(dir2, dir);
	    }
	    else if (frame > first_frame) {
		/*normal*/
		VSUBUNIT(dir, p3, p1);
		VSUBUNIT(dir2, p2, p1);/*needed for vertical case*/
	    }
	    else go = 0;/*first time through loop;no p2*/

			/*create matrix which would move vehicle*/
	    anim_dir2mat(mat_v, dir, dir2);
	    anim_add_trans(mat_v, p2, rcentroid);
	}

	/*determine distance traveled*/
	VMOVE(wheel_prev, wheel_now);
	MAT4X3PNT(wheel_now, mat_v, to_track);
	if (frame > first_frame) {
	    /* increment distance by distance moved */
	    VSUB2(vdelta, wheel_now, wheel_prev);
	    MAT3X3VEC(temp, mat_v, to_front);/*new front of vehicle*/
	    distance += VDOT(temp, vdelta);/*portion of vdelta in line with track*/
	}

	if (go) {
	    if (print_mode==TRACK_ANIM) {
		printf("start %d;\nclean;\n", frame);
	    } else if (print_mode==TRACK_ARCED) {
		if (frame != arced_frame) continue;
		last_frame = 1;
	    }
	    if (print_link) {
		for (count=0;count<num_links;count++) {
		    (void) get_link(position, &y_rot, distance+tracklen*count/num_links+init_dist);
		    anim_y_p_r2mat(wmat, 0.0, y_rot+r[count].ang, 0.0);
		    anim_add_trans(wmat, position, r[count].pos);
		    if ((axes || cent) && links_placed) {
			/* link moved from vehicle coords */
			bn_mat_mul(mat_x, wmat, m_rev_axes);
			bn_mat_mul(wmat, m_axes, mat_x);
		    }
		    else if (axes || cent) {
			/* link moved to vehicle coords */
			MAT_MOVE(mat_x, wmat);
			bn_mat_mul(wmat, m_axes, mat_x);
		    }
		    if (print_mode==TRACK_ANIM) {
			printf("anim %s.%d matrix %s\n", *(argv+link_nindex), count, link_cmd);
			anim_mat_printf(stdout, wmat, "%.10g ", "\n", ";\n");
		    } else if (print_mode==TRACK_ARCED) {
			printf("arced %s.%d matrix %s ", *(argv+link_nindex), count, link_cmd);
			anim_mat_printf(stdout, wmat, "%.10g ", "", "\n");
		    }
		}
	    }
	    if (print_wheel) {
		for (count = 0;count<num_wheels;count++) {
		    anim_y_p_r2mat(wmat, 0.0, -distance/x[count].w.rad, 0.0);
		    VREVERSE(temp, x[count].w.pos);
		    anim_add_trans(wmat, x[count].w.pos, temp);
		    if (axes || cent) {
			bn_mat_mul(mat_x, wmat, m_rev_axes);
			bn_mat_mul(wmat, m_axes, mat_x);
		    }
		    if (print_mode==TRACK_ANIM) {
			printf("anim %s.%d matrix %s\n", *(argv+wheel_nindex), count, wheel_cmd);
			anim_mat_printf(stdout, wmat, "%.10g ", "\n", ";\n");
		    } else if (print_mode==TRACK_ARCED) {
			printf("arced %s.%d matrix %s ", *(argv+wheel_nindex), count, wheel_cmd);
			anim_mat_printf(stdout, wmat, "%.10g ", "", "\n");
		    }
		}
	    }
	    if (print_mode==TRACK_ANIM)
		printf("end;\n");
	}
	if (last_frame) break;
    }

    if (x) {
	bu_free(x, "struct all");
    }
    if (r) {
	bu_free(r, "struct rlink");
    }
    return( 0 );
}
Exemplo n.º 26
0
int main(int argc, char ** argv)
{ get_args(argc,argv);
    process_data();
    print_results();
}
Exemplo n.º 27
0
int
main(int argc, char *argv[])
{
		
		int port;
		char* file_img;
		int ofd, rfd;

		//Get the arguments
		get_args(&port, &file_img, argc, argv);
		
    int sd = UDP_Open(port); //Creates a new socket and binds to a port to it
    assert(sd > -1);

		//Open the file image, if not present call file_create routine
		ofd = open(file_img, O_RDWR);
		if(ofd == -1)
		{
#ifdef DEBUG
		printf("File image doesn't exist - Creating a new one\n");
#endif
			
			rfd =	create_img(file_img);
			if(rfd == -1)
			{
#ifdef DEBUG
		printf("Error Creating the file - Exiting\n");
#endif
				return -1;
			}
			ofd = rfd;
		}

#ifdef DEBUG
		printf("File descriptor open: %d\n", ofd);
#endif

		close(ofd);
		/*
		CR_t* cr;

		lseek(ofd, 0, SEEK_SET);
		int br = read(ofd, (void*)cr, 4);
		printf("BR: %d\n", br);	
		printf("Log end: %d\n", cr->log_end);
		printf("Imap_0 addr: %d\n", cr->imap_p[0]);
*/

		printf("                                SERVER:: waiting in loop\n");

    while (1) 
		{
			struct sockaddr_in s;
			char buffer[BUFFER_SIZE];
	
			int rc = UDP_Read(sd, &s, buffer, BUFFER_SIZE);
			
			if (rc > 0) 
			{
	    	printf("                                SERVER:: read %d bytes (message: '%s')\n", rc, buffer);
	    	char reply[BUFFER_SIZE];
	    	
				sprintf(reply, "reply");
				rc = UDP_Write(sd, &s, reply, BUFFER_SIZE);
			}
    }

    return 0;
}
Exemplo n.º 28
0
/******************************************************************************
METHOD:  cfmask

PURPOSE:  the main routine for fmask in C

RETURN VALUE:
Type = int
Value           Description
-----           -----------
ERROR           An error occurred during processing of the cfmask
SUCCESS         Processing was successful

PROJECT:  Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
3/15/2013   Song Guo         Original Development
5/14/2013   Song Guo         Added in Polar Stereographic support
7/17/2013   Song Guo         Added in Map info 
8/15/2013   Song Guo         Modified to use TOA reflectance file 
                             as input instead of metadata file

NOTES: type ./cfmask --help for information to run the code
******************************************************************************/
int main (int argc, char *argv[])
{
    char errstr[MAX_STR_LEN];           /* error string */
    char lndth_name[MAX_STR_LEN];       /* ledaps Brightness Temperature file */
    char fmask_name[MAX_STR_LEN];       /* output fmask binary file name */
    char fmask_header[MAX_STR_LEN];     /* output fmask binary file header */
    char fmask_hdf_name[MAX_STR_LEN];   /* output fmask HDF file name */
    char fmask_hdf_hdr[MAX_STR_LEN];    /* output fmask HDF file header */
    char *lndcal_name = NULL;           /* input lndcal data filename */
    char directory[MAX_STR_LEN];        /* input/output data directory */
    char extension[MAX_STR_LEN];        /* input TOA file extension */
    int ib;                             /* band counters */
    char sds_names[NBAND_REFL_MAX][MAX_STR_LEN]; /* array of image SDS names */
    Input_t *input = NULL;              /* input data and meta data */
    char  scene_name[MAX_STR_LEN];      /* input data scene name */
    char *hdf_grid_name = "Grid";  /* name of the grid for HDF-EOS */
    unsigned char **cloud_mask;    /* cloud pixel mask */
    unsigned char **shadow_mask;   /* shadow pixel mask */
    unsigned char **snow_mask;     /* snow pixel mask */
    unsigned char **water_mask;    /* water pixel mask */
    int status;                    /* return value from function call */
    FILE *fd = NULL;               /* file pointer */
    float ptm;                     /* percent of clear-sky pixels */
    float t_templ = 0.0;     /* percentile of low background temperature */
    float t_temph = 0.0;     /* percentile of high background temperature */
    int out_sds_types[NUM_OUT_SDS];     /* array of image SDS types */
    char *sds_name="fmask_band";        /* Fmask hdf SDS name */
    Output_t *output = NULL;            /* output structure and metadata */
    bool verbose;            /* verbose flag for printing messages */
    bool write_binary;       /* should we write raw binary output? */
    bool no_hdf_output;      /* should we don't write HDF4 output file? */
    int cldpix = 2;          /* Default buffer for cloud pixel dilate */
    int sdpix = 2;           /* Default buffer for shadow pixel dilate */
    float cloud_prob;        /* Default cloud probability */
    Space_def_t space_def;   /* spatial definition information */
    float sun_azi_temp = 0.0;/* Keep the original sun azimuth angle */
  
    time_t now;
    time(&now);
    printf("CFmask start_time=%s\n",ctime(&now));

    /* Read the command-line arguments, including the name of the input
       Landsat TOA reflectance product and the DEM */
    status = get_args (argc, argv, &lndcal_name, &cloud_prob, &cldpix,
                       &sdpix, &write_binary, &no_hdf_output, &verbose);
    if (status != SUCCESS)
    { 
        sprintf (errstr, "calling get_args");
        ERROR (errstr, "main");
    }

    split_filename(lndcal_name, directory, scene_name, extension);
    if (verbose)
        printf("directory, scene_name, extension=%s,%s,%s\n", 
            directory, scene_name, extension);
    sprintf(lndcal_name, "%slndcal.%s.hdf", directory, scene_name);
    sprintf(lndth_name, "%slndth.%s.hdf", directory, scene_name);
    sprintf(fmask_name, "%sfmask.%s.img", directory, scene_name);
    sprintf(fmask_header, "%sfmask.%s.img.hdr", directory, scene_name);
    sprintf(fmask_hdf_name, "%sfmask.%s.hdf", directory, scene_name);
    if (verbose)
    {
        printf("lndcal_name, lndth_name = %s, %s\n", lndcal_name, lndth_name); 
        printf("fmask_name, fmask_header, fmask_hdf_name = %s, %s, %s\n", 
                fmask_name, fmask_header, fmask_hdf_name); 
    }

    /* Open input file, read metadata, and set up buffers */
    input = OpenInput(lndth_name, lndcal_name);
    if (input == NULL)
    {
        sprintf (errstr, "opening the input files: %s & %s", lndth_name,
                 lndcal_name);
        ERROR (errstr, "main");
    }

    /* Get the projection and spatial information from the input TOA
       reflectance product */
    status = get_space_def_hdf(&space_def, lndcal_name, hdf_grid_name);
    if (status != SUCCESS)
    {
        sprintf(errstr, "Reading spatial metadata from the HDF file: %s", 
               lndcal_name);
        ERROR (errstr, "main");
    }
    input->meta.zone = space_def.zone;

    if (verbose)
    {
        /* Print some info to show how the input metadata works */
        printf ("DEBUG: Number of input TOA bands: %d\n", input->nband);
        printf ("DEBUG: Number of input thermal bands: %d\n", 1);
        printf ("DEBUG: Number of input lines: %d\n", input->size.l);
        printf ("DEBUG: Number of input samples: %d\n", input->size.s);
        printf ("DEBUG: Number of input TOA lines: %d\n", input->toa_size.l);
        printf ("DEBUG: Number of input TOA samples: %d\n", input->toa_size.s);
        printf ("DEBUG: Provider is %s\n", input->meta.provider);
        printf ("DEBUG: Satellite is %s\n", input->meta.sat);
        printf ("DEBUG: Instrument is %s\n", input->meta.inst);
        printf ("DEBUG: ACQUISITION_DATE.DOY is %d\n", input->meta.acq_date.doy);
        printf ("DEBUG: WRS system is %s\n", input->meta.wrs_sys);
        printf ("DEBUG: Path is %d\n", input->meta.path);
        printf ("DEBUG: Row is %d\n", input->meta.row);
        printf ("DEBUG: Fill value is %d\n", input->meta.fill);
        for (ib = 0; ib < input->nband; ib++)
        {
            printf ("DEBUG: Band %d-->\n", ib);
            printf ("DEBUG:   SDS name is %s\n", input->sds[ib].name);
            printf ("DEBUG:   SDS rank: %d\n", input->sds[ib].rank);
            printf ("DEBUG:   band satu_value_ref: %d\n", 
                   input->meta.satu_value_ref[ib]);
            printf ("DEBUG:   band satu_value_max: %d\n", 
                   input->meta.satu_value_max[ib]);
            printf ("DEBUG:   band gains: %f, band biases: %f\n", 
                    input->meta.gain[ib], input->meta.bias[ib]);      
        }
        printf ("DEBUG: Thermal Band -->\n");
        printf ("DEBUG:   SDS name is %s\n", input->therm_sds.name);
        printf ("DEBUG:   SDS rank: %d\n", input->therm_sds.rank);
        printf ("DEBUG:   therm_satu_value_ref: %d\n", 
                   input->meta.therm_satu_value_ref);
        printf ("DEBUG:   therm_satu_value_max: %d\n", 
                   input->meta.therm_satu_value_max);
        printf ("DEBUG:   therm_gain: %f, therm_bias: %f\n", 
                input->meta.gain_th, input->meta.bias_th);

        printf("DEBUG: ROW is %d\n", input->meta.row);
        printf("DEBUG: PATH is %d\n", input->meta.path);
        printf("DEBUG: SUN AZIMUTH is %f\n", input->meta.sun_az);
        printf("DEBUG: SUN ZENITH is %f\n", input->meta.sun_zen);
        printf("DEBUG: Projection Zone is %d\n", input->meta.zone);

        printf("DEBUG: unit_ref is %s\n", input->meta.unit_ref);
        printf("DEBUG: valid_range_ref is %f & %f\n", 
           input->meta.valid_range_ref[0], 
           input->meta.valid_range_ref[1]);
    }

    /* If the scene is an ascending polar scene (flipped upside down), then
       the solar azimuth needs to be adjusted by 180 degrees.  The scene in
       this case would be north down and the solar azimuth is based on north
       being up clock-wise direction. Flip the south to be up will not change 
       the actual sun location, with the below relations, the solar azimuth
       angle will need add in 180.0 for correct sun location */
    if (input->meta.ul_corner.is_fill &&
        input->meta.lr_corner.is_fill &&
        (input->meta.ul_corner.lat - input->meta.lr_corner.lat) < MINSIGMA)
    {
        /* Keep the original solar azimuth angle */
        sun_azi_temp = input->meta.sun_az;
        input->meta.sun_az += 180.0;
        if ((input->meta.sun_az - 360.0) > MINSIGMA)
            input->meta.sun_az -= 360.0;
        if (verbose)
            printf ("  Polar or ascending scene.  Readjusting solar azimuth by "
                "180 degrees.\n  New value: %f degrees\n", input->meta.sun_az);
    }

    /* Copy the SDS names and QA SDS names from the input structure for the
       output structure, since we are simply duplicating the input */
    for (ib = 0; ib < input->nband; ib++)
        strcpy (&sds_names[ib][0], input->sds[ib].name);

    /* Dynamic allocate the 2d mask memory */
    cloud_mask = (unsigned char **)allocate_2d_array(input->size.l, 
                 input->size.s, sizeof(unsigned char)); 
    shadow_mask = (unsigned char **)allocate_2d_array(input->size.l, 
                 input->size.s, sizeof(unsigned char)); 
    snow_mask = (unsigned char **)allocate_2d_array(input->size.l, 
                 input->size.s, sizeof(unsigned char)); 
    water_mask = (unsigned char **)allocate_2d_array(input->size.l, 
                 input->size.s, sizeof(unsigned char)); 
    if (cloud_mask == NULL  || shadow_mask == NULL || snow_mask == NULL
        || water_mask == NULL)
    {
        sprintf (errstr, "Allocating mask memory");
        ERROR (errstr, "main");
    }

    /* Build the potential cloud, shadow, snow, water mask */
    status = potential_cloud_shadow_snow_mask(input, cloud_prob, &ptm,
             &t_templ, &t_temph, cloud_mask, shadow_mask, snow_mask, 
             water_mask, verbose);
    if (status != SUCCESS)
    {
        sprintf (errstr, "processing potential_cloud_shadow_snow_mask");
        ERROR (errstr, "main");
    }

    printf("Pcloud done, starting cloud/shadow match\n");


    /* Build the final cloud shadow based on geometry matching and
       combine the final cloud, shadow, snow, water masks into fmask */
    status = object_cloud_shadow_match(input, ptm, t_templ, t_temph,
             cldpix, sdpix, cloud_mask, shadow_mask, snow_mask, water_mask,
             verbose);
    if (status != SUCCESS)
    {
        sprintf (errstr, "processing object_cloud_and_shadow_match");
        ERROR (errstr, "main");
    }    

    status = free_2d_array((void **)shadow_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing mask memory");
        ERROR (errstr, "main");
    }
    status = free_2d_array((void **)snow_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing mask memory");
        ERROR (errstr, "main");
    }
    status = free_2d_array((void **)water_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing mask memory");
        ERROR (errstr, "main");
    }

    /* Reassign solar azimuth angle for output purpose if south up north 
       down scene is involved */
    if (input->meta.ul_corner.is_fill &&
        input->meta.lr_corner.is_fill &&
        (input->meta.ul_corner.lat - input->meta.lr_corner.lat) < MINSIGMA)
        input->meta.sun_az = sun_azi_temp;
   
    if (write_binary)
    {
        /* Create an ENVI header file for the binary fmask */
        status = write_envi_hdr(fmask_header, BINARY_FILE, input, &space_def);
        if (status != SUCCESS)
        {
            sprintf(errstr, "Creating ENVI header for binary fmask");
            ERROR (errstr, "main");
        }

        /* Open the mask file for writing */
        fd = fopen(fmask_name, "w"); 
        if (fd == NULL)
        {
            sprintf(errstr, "Opening report file: %s", fmask_name);
            ERROR (errstr, "main");
        }

        /* Write out the mask file */
        status = fwrite(&cloud_mask[0][0], sizeof(unsigned char),
            input->size.l * input->size.s, fd);
        if (status != input->size.l * input->size.s)
        {
            sprintf(errstr, "Writing to %s", fmask_name);
            ERROR (errstr, "main");
        }

        /* Close the mask file */
        status = fclose(fd);
        if (status)
        {
            sprintf(errstr, "Closing file %s", fmask_name);
            ERROR (errstr, "main");
        }
    }

    if (!no_hdf_output)
    {
        /* Create and open fmask HDF output file */
        if (!CreateOutput(fmask_hdf_name))
        {
            sprintf(errstr, "Creating HDF fmask output file");
            ERROR (errstr, "main");
        }
        output = OpenOutput (fmask_hdf_name, sds_name, &input->size);
        if (output == NULL)
        {
            sprintf (errstr, "opening output file - %s", fmask_hdf_name);
            ERROR(errstr, "main");
        }

        if (!PutOutput(output, cloud_mask))
        {
            sprintf (errstr, "Writing output fmask in HDF files\n");
            ERROR (errstr, "main");
        }

        if (!PutMetadata(output, input))
        {
            sprintf (errstr, "Writing output fmask metadata in HDF files\n");
            ERROR (errstr, "main");
        }

        /* Close the output file and free the structure */
        if (!CloseOutput (output))
        {
            sprintf (errstr, "closing output file - %s", fmask_hdf_name);
            ERROR(errstr, "main");
        }
        if (!FreeOutput (output))
        {
            sprintf (errstr, "freeing output file - %s", fmask_hdf_name);
            ERROR(errstr, "main");
        }

        /* Write the spatial information, after the file has been closed */
        out_sds_types[0] = DFNT_UINT8;
        status = put_space_def_hdf (&space_def, fmask_hdf_name, NUM_OUT_SDS, 
            out_sds_names, out_sds_types, hdf_grid_name);
        if (status != SUCCESS)
        {
            sprintf("Putting spatial metadata to the HDF file: "
            "%s", lndcal_name);
            ERROR (errstr, "main");
        }

        /* Write CFmask HDF header to add in envi map info */
        sprintf (fmask_hdf_hdr, "%s.hdr", fmask_hdf_name);
        status = write_envi_hdr (fmask_hdf_hdr, HDF_FILE, input, &space_def);
        if (status != SUCCESS)
        {
            sprintf(errstr, "Error writing the ENVI header for CFmask HDF hdr");
            ERROR (errstr, "main");
        }
    }

    /* Free the final output cloud_mask */
    status = free_2d_array((void **)cloud_mask);
    if (status != SUCCESS)
    {
        sprintf (errstr, "Freeing mask memory");
        ERROR (errstr, "main");
    }

    /* Close the input file and free the structure */
    CloseInput (input);
    FreeInput (input);

    free(lndcal_name);
    printf ("Processing complete.\n");
    time(&now);
    printf("CFmask end_time=%s\n",ctime(&now));
    return (SUCCESS);
}
Exemplo n.º 29
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	fprintf( stderr, "lsmi-joystick" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME );

	if ( NULL == seq )
	{
		fprintf( stderr, "Error opening alsa sequencer!\n" );
		exit( 1 );
	}

	if ( ( port = open_output_port( seq ) ) < 0 )
	{
		fprintf( stderr, "Error opening MIDI output port!\n" );
		exit( 1 );
	}

	if ( sub_name )
	{
		snd_seq_addr_t addr;

		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}

	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	fprintf( stderr, "Initializing joystick...\n" );

	if ( -1 == ( jfd = open( joydevice, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		clean_up();
		exit(1);
	}

	set_traps();

	fprintf( stderr, "Waiting for events...\n" );

	for ( ;; )
	{
		struct js_event e;
		snd_seq_event_t ev;
		static int b1;
		static int b2;

		read (jfd, &e, sizeof(struct js_event));

		snd_seq_ev_clear( &ev );

		switch (e.type)
		{
			case JS_EVENT_BUTTON:
				switch (e.number)
				{
					case 0:
						if(e.value)
							b1 = 1;
						else
						{
							b1 = 0;
							snd_seq_ev_set_pitchbend( &ev, channel, 0 );

							send_event( &ev );
						}
						break;
					case 1:
						if (e.value)
							b2 = 1;
						else
						{
							b2 = 0;
							snd_seq_ev_set_controller( &ev, channel, 1, 0 );
							send_event( &ev );
							snd_seq_ev_set_controller( &ev, channel, 33, 0 );
							send_event( &ev );
						}
						break;
				}
				break;
			case JS_EVENT_AXIS:
				
				if ( e.number == 1 && ( b1 || nohold ) )
				{
					snd_seq_ev_set_pitchbend( &ev, channel, 0 - (int)((e.value) * ((float)8191/32767) ));

					send_event( &ev );
				}
				else
				if ( ( e.number == 1 && b2 ) ||
					 ( e.number == 0 && ( ( b1 && b2 ) || nohold ) )
				)
				{
					int fine = (int)((0 - e.value) + 32767) * ((float)16383/65534);
					int	course = fine >> 7;
					fine &= 0x7F;

					snd_seq_ev_set_controller( &ev, channel, 1, course );
					send_event( &ev );
					snd_seq_ev_set_controller( &ev, channel, 33, fine );
					send_event( &ev );
				}
				break;

			 default:
				break;
		}

	}
Exemplo n.º 30
0
/*
 * 函数命令行执行
 * @cmd 函数命令行, eg: timer_pwm_set(0, 567)
 */
void fcmd_exec(uint8_t *cmd)
{
    uint8_t *pcmd = cmd;
    _args_t args[PARAMS_NUM + 1]; 	//参数数组
    _args_t ret=0;					//函数返回值
    uint8_t i;
    int8_t cmdtbl_param_num;

    //跳过开头空格
    while (*pcmd == ' ')
        pcmd++;

    //分离参数
    memset(args, 0, PARAMS_NUM + 1);
    get_args(pcmd, (uint8_t *)"(,)\"", args);

    if (args[0] == -2)
    {
        PRINTF("err:fmt err\n");
        return ;
    }

    //匹配命令
    if (args[0] == -1)
    {
        //系统命令
        for (i = 0; i < SYSTEM_CMD; i++)
        {
            if (strncmp((char*)pcmd, CmdTbl[i].fname, strlen((char*)pcmd)) == 0)
                break;
        }

        if (i >= SYSTEM_CMD)
        {
            PRINTF("err:system cmd err\n");
            return ;
        }
    }
    else
    {
        //普通命令
        for (i = SYSTEM_CMD; i < CmdTblSize; i++)
        {
            uint8_t *pcmd_end;
            uint8_t pfname_len;
            uint8_t pcmd_len;
            uint8_t *pfname = get_fname((uint8_t*)CmdTbl[i].fname, &pfname_len);

            //malloc (int size), pcmd_end指向'c'
            pcmd_end = pcmd + strlen((char*)pcmd) - 1;
            while (*pcmd_end == ' ')//跳过空格
                --pcmd_end;
            pcmd_len = pcmd_end - pcmd + 1;

            //比较函数名
            if (strncmp((char*)pfname, (char*)pcmd, pcmd_len > pfname_len ? pcmd_len : pfname_len) == 0)
                break;
        }

        //没有匹配到命令
        if (i >= CmdTblSize)
        {
            PRINTF("err:not you wanted cmd\n");
            return;
        }
    }

    //得到函数表里的函数的参数个数
    if (args[0] != -1)
    {
        //普通命令
        cmdtbl_param_num = get_args_num((uint8_t*)CmdTbl[i].fname, (uint8_t*)"(,)");
		if (cmdtbl_param_num == -2)
		{
			;//可变参数情况
		}
        else if (cmdtbl_param_num != args[0])
        {
            PRINTF("err:param err\n");
            return ;
        }
    }
    else
    {
        //执行系统命令
        system_cmd_exe(i);
        return;
    }

    //传入相应参数,执行普通命令
    switch (args[0])
    {
    case 0://没有参数
        ret = (*(_args_t(*)())CmdTbl[i].pfunc)();
        break;

    case 1:
        ret = (*(_args_t(*)(_args_t))CmdTbl[i].pfunc)(args[1]);
        break;

    case 2:
        ret = (*(_args_t(*)(_args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2]);
        break;

    case 3:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3]);
        break;

    case 4:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4]);
        break;

    case 5:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5]);
        break;

    case 6:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5], args[6]);
        break;

    case 7:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
        break;

    case 8:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
        break;

    case 9:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
        break;

    case 10:
        ret = (*(_args_t(*)(_args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t, _args_t))CmdTbl[i].pfunc)(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10]);
        break;

    default:
        PRINTF("err:params num err\n");
        break;
    }

    if (sizeof(_args_t) == 1)
        PRINTF("=0x%02x,%d;\n", ret,ret);
    else if (sizeof(_args_t) == 2)
        PRINTF("=0x%04x,%d;\n", ret,ret);
    else if (sizeof(_args_t) == 4)
        PRINTF("=0x%08x,%d;\n", ret,ret);
}