Ejemplo n.º 1
0
/* ********************************************************************* */
void Init (double *us, double x1, double x2, double x3)
/*
 *
 *
 *
 *********************************************************************** */
{
  double dr, vol, r;

  g_gamma = g_inputParam[GAMMA];

/* --------------------------------------------------
    dr is the size of the initial energy deposition 
    region: 2 ghost zones.
   -------------------------------------------------- */

  #if DIMENSIONS == 1
   dr = 2.0*(g_domEnd[IDIR]-g_domBeg[IDIR])/(double)NX1;
  #else
   dr = 3.5*(g_domEnd[IDIR]-g_domBeg[IDIR])/(double)NX1;
  #endif

/* ---------------------------------------
     compute region volume 
   --------------------------------------- */

  #if (GEOMETRY == CARTESIAN) && (DIMENSIONS == 1)
   vol = 2.0*dr;
  #elif (GEOMETRY == CYLINDRICAL && DIMENSIONS == 1)|| \
        (GEOMETRY == CARTESIAN   && DIMENSIONS == 2)
   vol = CONST_PI*dr*dr;
  #elif (GEOMETRY == SPHERICAL   && DIMENSIONS == 1)|| \
        (GEOMETRY == CYLINDRICAL && DIMENSIONS == 2)|| \
        (GEOMETRY == CARTESIAN   && DIMENSIONS == 3)
   vol = 4.0/3.0*CONST_PI*dr*dr*dr;
  #else
   print1 ("! Init: geometrical configuration not allowed\n");
   QUIT_PLUTO(1);
  #endif

  r = EXPAND(x1*x1, + x2*x2, +x3*x3);
  r = sqrt(r);

  us[RHO] = g_inputParam[DNST0];
  us[VX1] = 0.0;
  us[VX2] = 0.0;
  us[VX3] = 0.0;

  if (r <= dr) {
    us[PRS] =  (g_gamma - 1.0)*g_inputParam[ENRG0]/vol;
  }else{
    us[PRS] = 1.e-5;
  }

  us[TRC]  = 0.0;

  #if PHYSICS == MHD || PHYSICS == RMHD

   us[BX1] = 0.0;
   us[BX2] = 0.0;
   us[BX3] = 0.0;

   #ifdef STAGGERED_MHD

    us[AX] = 0.0;
    us[AY] = 0.0;
    us[AZ] = 0.0;

   #endif

  #endif
}
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;
}
Ejemplo n.º 3
0
// If the package contains an update binary, extract it and run it.
static int
try_update_binary(const char *path, ZipArchive *zip) {
    const ZipEntry* binary_entry =
            mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
    if (binary_entry == NULL) {
        const ZipEntry* update_script_entry =
                mzFindZipEntry(zip, ASSUMED_UPDATE_SCRIPT_NAME);
        if (update_script_entry != NULL) {
            ui_print("Amend scripting (update-script) is no longer supported.\n");
            ui_print("Amend scripting was deprecated by Google in Android 1.5.\n");
            ui_print("It was necessary to remove it when upgrading to the ClockworkMod 3.0 Gingerbread based recovery.\n");
            ui_print("Please switch to Edify scripting (updater-script and update-binary) to create working update zip packages.\n");
            return INSTALL_UPDATE_BINARY_MISSING;
        }

        mzCloseZipArchive(zip);
        return INSTALL_UPDATE_BINARY_MISSING;
    }

    char* binary = "/tmp/update_binary";
    unlink(binary);
    int fd = creat(binary, 0755);
    if (fd < 0) {
        mzCloseZipArchive(zip);
        LOGE("Can't make %s\n", binary);
        return 1;
    }
    bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
    close(fd);

    if (!ok) {
        LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
        mzCloseZipArchive(zip);
        return 1;
    }

    int pipefd[2];
    pipe(pipefd);

    // When executing the update binary contained in the package, the
    // arguments passed are:
    //
    //   - the version number for this interface
    //
    //   - an fd to which the program can write in order to update the
    //     progress bar.  The program can write single-line commands:
    //
    //        progress <frac> <secs>
    //            fill up the next <frac> part of of the progress bar
    //            over <secs> seconds.  If <secs> is zero, use
    //            set_progress commands to manually control the
    //            progress of this segment of the bar
    //
    //        set_progress <frac>
    //            <frac> should be between 0.0 and 1.0; sets the
    //            progress bar within the segment defined by the most
    //            recent progress command.
    //
    //        firmware <"hboot"|"radio"> <filename>
    //            arrange to install the contents of <filename> in the
    //            given partition on reboot.
    //
    //            (API v2: <filename> may start with "PACKAGE:" to
    //            indicate taking a file from the OTA package.)
    //
    //            (API v3: this command no longer exists.)
    //
    //        ui_print <string>
    //            display <string> on the screen.
    //
    //   - the name of the package zip file.
    //

    char** args = malloc(sizeof(char*) * 5);
    args[0] = binary;
    args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk
    args[2] = malloc(10);
    sprintf(args[2], "%d", pipefd[1]);
    args[3] = (char*)path;
    args[4] = NULL;

    pid_t pid = fork();
    if (pid == 0) {
        setenv("UPDATE_PACKAGE", path, 1);
        close(pipefd[0]);
        execv(binary, args);
        fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
        _exit(-1);
    }
    close(pipefd[1]);

    char* firmware_type = NULL;
    char* firmware_filename = NULL;

    char buffer[1024];
    FILE* from_child = fdopen(pipefd[0], "r");
    while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
        char* command = strtok(buffer, " \n");
        if (command == NULL) {
            continue;
        } else if (strcmp(command, "progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            char* seconds_s = strtok(NULL, " \n");

            float fraction = strtof(fraction_s, NULL);
            int seconds = strtol(seconds_s, NULL, 10);

            ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION),
                             seconds);
        } else if (strcmp(command, "set_progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            float fraction = strtof(fraction_s, NULL);
            ui_set_progress(fraction);
        } else if (strcmp(command, "firmware") == 0) {
            char* type = strtok(NULL, " \n");
            char* filename = strtok(NULL, " \n");

            if (type != NULL && filename != NULL) {
                if (firmware_type != NULL) {
                    LOGE("ignoring attempt to do multiple firmware updates");
                } else {
                    firmware_type = strdup(type);
                    firmware_filename = strdup(filename);
                }
            }
        } else if (strcmp(command, "ui_print") == 0) {
            char* str = strtok(NULL, "\n");
            if (str) {
                ui_print("%s", str);
            } else {
                ui_print("\n");
            }
        } else {
            LOGE("unknown command [%s]\n", command);
        }
    }
    fclose(from_child);

    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
        mzCloseZipArchive(zip);
        return INSTALL_ERROR;
    }

    if (firmware_type != NULL) {
        int ret = handle_firmware_update(firmware_type, firmware_filename, zip);
        mzCloseZipArchive(zip);
        return ret;
    }
    return INSTALL_SUCCESS;
}
Ejemplo n.º 4
0
/*
 * push text into the generator input buffer
 */
static void
push(char *bfr, int size, MMIOT *f)
{
    while ( size-- > 0 )
	EXPAND(f->in) = *bfr++;
}
Ejemplo n.º 5
0
			NULL };

/*} else {
char* MENU_ITEMS[] = { "立即重启系统",
                       "刷入刷机包",
                       "清除数据/恢复出厂设置",
                       "清除缓存分区",
                       "备份和还原",
                       "挂载及 U 盘模式",
                       "高级功能",
		       "选择语言",

                       NULL };
	}
}*/
char* rootmenutitle[] = { EXPAND(RECOVERY_VERSION),

                      "Only for "EXPAND(RECOVERY_PRODUCT_MODEL),

                      "",
                      NULL };
void device_ui_init(UIParameters* ui_parameters) {
}

int device_recovery_start() {
    return 0;
}

// add here any key combo check to reboot device
int device_reboot_now(volatile char* key_pressed, int key_code) {
    return 0;
Ejemplo n.º 6
0
UInt32 HTTPPacket::build(Exception& ex,UInt8* data,UInt32 size) {
	if (_data)
		return 0;
	exception.set(Exception::NIL);

	/// read data
	ReadingStep			step(CMD);
	UInt8*				current(data);
	const UInt8*		end(current+size-4); // 4 == /r/n/r/n
	const char*			signifiant(NULL);
	const char*			key(NULL);

	// headers

	for (; current <= end;++current) {

		if (memcmp(current, EXPAND("\r\n")) == 0 || memcmp(current, EXPAND("\0\n")) == 0) {

			if (!ex && signifiant) {
				// KEY = VALUE
				UInt8* endValue(current);
				while (isblank(*--endValue));
				*(endValue+1) = 0;
				if (!key) { // version case!
					String::ToNumber(signifiant+5, version);
				} else {
					headers[key] = signifiant;
					parseHeader(ex,key,signifiant);
					key = NULL;
				}
			}
			step = LEFT;
			current += 2;
			signifiant = (const char*)current;

			if (memcmp(current, EXPAND("\r\n")) == 0) {
				current += 2;
				content = current;
				current += contentLength;
				if (ex || current > (end+4))
					break; // wait next
				_data = data;
				return _size = current - data;
			}

			++current; // here no continue, the "\r\n" check is not required again
		}

		if (ex)
			continue; // try to go to "\r\n\r\n"

		// http header, byte by byte
		UInt8 byte = *current;

		if ((step == LEFT || step == CMD || step == PATH) && (isspace(byte) || byte==0)) {
			if (step == CMD) {
				if(!signifiant) // Space before signifiant
					ex.set(Exception::PROTOCOL,"Unexpected space before command");

				// by default command == GET
				if (!signifiant || (command = HTTP::ParseCommand(ex, signifiant)) == HTTP::COMMAND_UNKNOWN) {
					exception = ex;
					continue;
				}
				signifiant = NULL;
				step = PATH;
			} else if (step == PATH) {
				// parse query
				*current = 0;
				size_t filePos = Util::UnpackUrl(signifiant, path,query);
				file.setPath(file.path(),path);
				if (filePos != string::npos)
					path.erase(filePos - 1);
				else
					file.makeFolder();
				signifiant = NULL;
				step = VERSION;
			} else
				++signifiant; // for trim begin of key or value
		} else if (step > VERSION && !key && (byte == ':' || byte == 0)) {
			// KEY
			key = signifiant;
			step = LEFT;
			UInt8* endValue(current);
			while (isblank(*--endValue));
			*(endValue+1) = 0;
			signifiant = (const char*)current + 1;
		} else if (step == CMD || step == PATH || step == VERSION) {
			if (!signifiant)
				signifiant = (const char*)current;
			if (step == CMD && (current-data)>7) // not a HTTP valid packet, consumes all
				exception = ex.set(Exception::PROTOCOL, "invalid HTTP packet");
		} else
			step = RIGHT;
	}


	if (ex)
		return current - data;

	return 0;  // wait next data
}
Ejemplo n.º 7
0
// If the package contains an update binary, extract it and run it.
static int
try_update_binary(const char *path, ZipArchive *zip, int* wipe_cache) {
    const ZipEntry* binary_entry =
        mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
    if (binary_entry == NULL) {
        mzCloseZipArchive(zip);
        return INSTALL_CORRUPT;
    }

    const char* binary = "/tmp/update_binary";
    unlink(binary);
    int fd = creat(binary, 0755);
    if (fd < 0) {
        mzCloseZipArchive(zip);
        LOGE("Can't make %s\n", binary);
        return INSTALL_ERROR;
    }
    bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
    close(fd);
    mzCloseZipArchive(zip);

    if (!ok) {
        LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
        return INSTALL_ERROR;
    }

    int pipefd[2];
    pipe(pipefd);

    // When executing the update binary contained in the package, the
    // arguments passed are:
    //
    //   - the version number for this interface
    //
    //   - an fd to which the program can write in order to update the
    //     progress bar.  The program can write single-line commands:
    //
    //        progress <frac> <secs>
    //            fill up the next <frac> part of of the progress bar
    //            over <secs> seconds.  If <secs> is zero, use
    //            set_progress commands to manually control the
    //            progress of this segment of the bar
    //
    //        set_progress <frac>
    //            <frac> should be between 0.0 and 1.0; sets the
    //            progress bar within the segment defined by the most
    //            recent progress command.
    //
    //        firmware <"hboot"|"radio"> <filename>
    //            arrange to install the contents of <filename> in the
    //            given partition on reboot.
    //
    //            (API v2: <filename> may start with "PACKAGE:" to
    //            indicate taking a file from the OTA package.)
    //
    //            (API v3: this command no longer exists.)
    //
    //        ui_print <string>
    //            display <string> on the screen.
    //
    //   - the name of the package zip file.
    //

    const char** args = (const char**)malloc(sizeof(char*) * 5);
    args[0] = binary;
    args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk
    char* temp = (char*)malloc(10);
    sprintf(temp, "%d", pipefd[1]);
    args[2] = temp;
    args[3] = (char*)path;
    args[4] = NULL;

    pid_t pid = fork();
    if (pid == 0) {
        umask(022);
        close(pipefd[0]);
        execv(binary, (char* const*)args);
        fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
        _exit(-1);
    }
    close(pipefd[1]);

    *wipe_cache = 0;

    char buffer[1024];
    FILE* from_child = fdopen(pipefd[0], "r");
    while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
        char* command = strtok(buffer, " \n");
        if (command == NULL) {
            continue;
        } else if (strcmp(command, "progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            char* seconds_s = strtok(NULL, " \n");

            float fraction = strtof(fraction_s, NULL);
            int seconds = strtol(seconds_s, NULL, 10);

            ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
        } else if (strcmp(command, "set_progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            float fraction = strtof(fraction_s, NULL);
            ui->SetProgress(fraction);
        } else if (strcmp(command, "ui_print") == 0) {
            char* str = strtok(NULL, "\n");
            if (str) {
                ui->Print("%s", str);
            } else {
                ui->Print("\n");
            }
            fflush(stdout);
        } else if (strcmp(command, "wipe_cache") == 0) {
            *wipe_cache = 1;
        } else if (strcmp(command, "clear_display") == 0) {
            ui->SetBackground(RecoveryUI::NONE);
        } else if (strcmp(command, "enable_reboot") == 0) {
            // packages can explicitly request that they want the user
            // to be able to reboot during installation (useful for
            // debugging packages that don't exit).
            ui->SetEnableReboot(true);
        } else {
            LOGE("unknown command [%s]\n", command);
        }
    }
    fclose(from_child);

    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
        return INSTALL_ERROR;
    }

    return INSTALL_SUCCESS;
}
Ejemplo n.º 8
0
/*
 * push a character into the generator input buffer
 */
static void 
pushc(char c, MMIOT *f)
{
    EXPAND(f->in) = c;
}
Ejemplo n.º 9
0
int
main (
int                         argc,
char *                      argv[])
{
  char                chartab[CHARMAX];
  char                chartmp[CHARMAX];
  char *              substab[SUBSMAX][2];        /* Substitution array */
  int                 subsnbr;
  int                 i;

  if ((argc >= 2) && (argv[1][0] == '?')) {       /* If need for help */
    printf ("Usage is:\ndummysizes [<input pattern header file> [<output header file>]]\n");
    return (((argv[1][0] == '?') && argv[1][1] == '\0') ? 0 : 1);
  }

  for (i = 0; i < C_FILENBR; i ++)                /* Set default stream pointers */
    C_fileTab[i].fileptr = (C_fileTab[i].modeptr[0] == 'r') ? stdin : stdout;
  for (i = 1; i < argc; i ++) {                   /* Loop for all option codes */
    if ((argv[i][0] != '+') &&                    /* If found a file name      */
        ((argv[i][0] != '-') || (argv[i][1] == '\0'))) {
      if (C_fileNum < C_FILEARGNBR)               /* A file name has been given */
        C_fileTab[C_fileNum ++].nameptr = argv[i];
      else {
        fprintf (stderr, "dummysizes: ERROR: main: too many file names given");
        exit    (1);
      }
    }
    else {                                        /* If found an option name */
      switch (argv[i][1]) {
        case 'H' :                                /* Give the usage message */
        case 'h' :
          printf ("Usage is:\ndummysizes [<input pattern header file> [<output header file>]]\n");
          exit       (0);
        case 'V' :
          fprintf (stderr, "dummysizes, version " SCOTCH_VERSION_STRING "\n");
          fprintf (stderr, "Copyright 2004,2007-2010 ENSEIRB, INRIA & CNRS, France\n");
          fprintf (stderr, "This software is libre/free software under CeCILL-C -- see the user's manual for more information\n");
          return  (0);
        default :
          fprintf (stderr, "dummysizes: ERROR: main: unprocessed option (\"%s\")", argv[i]);
          exit    (1);
      }
    }
  }

  for (i = 0; i < C_FILENBR; i ++) {              /* For all file names     */
    if ((C_fileTab[i].nameptr[0] != '-') ||       /* If not standard stream */
        (C_fileTab[i].nameptr[1] != '\0')) {
      if ((C_fileTab[i].fileptr = fopen (C_fileTab[i].nameptr, C_fileTab[i].modeptr)) == NULL) { /* Open the file */
          fprintf (stderr, "dummysizes: ERROR: main: cannot open file (%d)", i);
          exit    (1);
      }
    }
  }

#ifdef SCOTCH_PTSCOTCH
  substab[0][0] = "library_pt.h";
  substab[0][1] = "ptscotch.h  ";
  substab[1][0] = "library_pt_f.h";
  substab[1][1] = "ptscotchf.h   ";
#else /* SCOTCH_PTSCOTCH */
  substab[0][0] = "library.h";
  substab[0][1] = "scotch.h ";
  substab[1][0] = "library_f.h";
  substab[1][1] = "scotchf.h  ";
#endif /* SCOTCH_PTSCOTCH */
  substab[2][0] = "DUMMYIDX";
  substab[2][1] = EXPAND (IDX);
  substab[3][0] = "DUMMYINT";
  substab[3][1] = EXPAND (INT);
  substab[4][0] = "DUMMYMAXINT";
  substab[4][1] = EXPAND (INTVALMAX);
  substab[5][0] = "DUMMYNUMSTRING";
  substab[5][1] = "\"" GNUMSTRING "\"";
  substab[6][0] = "DUMMYVERSION";
  substab[6][1] = EXPAND (SCOTCH_VERSION);
  substab[7][0] = "DUMMYRELEASE";
  substab[7][1] = EXPAND (SCOTCH_RELEASE);
  substab[8][0] = "DUMMYPATCHLEVEL";
  substab[8][1] = EXPAND (SCOTCH_PATCHLEVEL);
  subsnbr = 9;
  subsFill (substab[subsnbr ++], "DUMMYSIZEARCH",          sizeof (Arch));
  subsFill (substab[subsnbr ++], "DUMMYSIZEGEOM",          sizeof (Geom));
  subsFill (substab[subsnbr ++], "DUMMYSIZEGRAPH",         sizeof (Graph));
  subsFill (substab[subsnbr ++], "DUMMYSIZEMESH",          sizeof (Mesh));
  subsFill (substab[subsnbr ++], "DUMMYSIZEMAP",           sizeof (LibMapping));
  subsFill (substab[subsnbr ++], "DUMMYSIZEORDER",         sizeof (LibOrder));
  subsFill (substab[subsnbr ++], "DUMMYSIZESTRAT",         sizeof (Strat *));
#ifdef SCOTCH_PTSCOTCH
  subsFill (substab[subsnbr ++], "DUMMYSIZEDGRAPHHALOREQ", sizeof (DgraphHaloRequest)); /* TRICK: before DUMMYSIZEDGRAPH */
  subsFill (substab[subsnbr ++], "DUMMYSIZEDGRAPH",        sizeof (Dgraph));
  subsFill (substab[subsnbr ++], "DUMMYSIZEDMAP",          sizeof (LibDmapping));
  subsFill (substab[subsnbr ++], "DUMMYSIZEDORDER",        sizeof (Dorder));
#else /* SCOTCH_PTSCOTCH */
  subsFill (substab[subsnbr ++], "DUMMYSIZEDGRAPHHALOREQ", 1); /* TRICK: before DUMMYSIZEDGRAPH */
  subsFill (substab[subsnbr ++], "DUMMYSIZEDGRAPH",        1);
  subsFill (substab[subsnbr ++], "DUMMYSIZEDMAP",          1);
  subsFill (substab[subsnbr ++], "DUMMYSIZEDORDER",        1);
#endif /* SCOTCH_PTSCOTCH */

  while (fgets (chartab, CHARMAX, C_filepntrhedinp) != NULL) { /* Infinite loop on file lines */
    int                 charnbr;
    int                 subsnum;

    if (((charnbr = strlen (chartab)) >= (CHARMAX - 1)) && /* If line read is at least as long as maximum size     */
        (chartab[CHARMAX - 1] != '\n')) {         /* And last character is not a newline, that is, some is missing */
      fprintf (stderr, "dummysizes: ERROR: line too long\n");
      exit    (1);
    }

    for (subsnum = 0; subsnum < subsnbr; subsnum ++) { /* Perform substitutions */
      char *              charptr;                /* Place where token found    */

      while ((charptr = strstr (chartab, substab[subsnum][0])) != NULL) { /* As long as substitution can be performed */
        int                 charnbr;
        int                 charnum;

        charnum = charptr - chartab;              /* Position where token found */
        charnbr = strlen (substab[subsnum][0]);   /* Length of token            */

        strcpy (chartmp, charptr + charnbr);      /* Save end of line */

        sprintf (charptr, "%s%s", substab[subsnum][1], chartmp); /* Replace end of line with substituted token */
      }
    }

    fputs (chartab, C_filepntrhedout);            /* Output possibly updated line */
  }

#ifdef SCOTCH_DEBUG_MAIN1
  for (i = 0; i < C_FILENBR; i ++) {              /* For all file names     */
    if ((C_fileTab[i].name[0] != '-') ||          /* If not standard stream */
        (C_fileTab[i].name[1] != '\0')) {
      fclose (C_fileTab[i].pntr);                 /* Close the stream */
    }
  }
#endif /* SCOTCH_DEBUG_MAIN1 */

  exit (0);
}
Ejemplo n.º 10
0
/* putc() into a cstring
 */
void
Csputc(int c, Cstring *iot)
{
    EXPAND(*iot) = c;
}
Ejemplo n.º 11
0
void SHA1_NEW( unsigned char * pData, int length, unsigned char * pDigest)
{
	if (length > 16)
		return;

    UINT4 Message_Block_Index    = 0;

	union
	{
		unsigned char Message_Block[64];
		UINT4 Message_Block_W[16];
	};

	Message_Block_W[0] = 0x00000000;
	Message_Block_W[1] = 0x00000000;
	Message_Block_W[2] = 0x00000000;
	Message_Block_W[3] = 0x00000000;
	Message_Block_W[4] = 0x00000000;

	UINT4 Intermediate_Hash[5] = { H0, H1, H2, H3, H4 };
	
 	memcpy(Message_Block, pData, length);
	Message_Block_Index += length;

	//padMessage
	Message_Block[length] = 0x80;
	
	UINT4 W_15 = length << 3;
	
    int           t;                 /* Loop counter                */
    UINT4      temp;              /* Temporary word value        */
    UINT4      W[80];             /* Word sequence               */
    UINT4      A, B, C, D, E;     /* Word buffers                */

    /*
     *  Initialize the first 16 words in the array W
     */

	#define INIT_OLD(x) \
        W[x] = (Message_Block[(x) * 4] << 24) | \
        	(Message_Block[(x) * 4 + 1] << 16) | \
        	(Message_Block[(x) * 4 +2] << 8) | \
        	(Message_Block[(x) * 4 +3])

	#define INIT(x) W[x] = Message_Block_W[x];
	
	#define INIT_NULL(x) W[x] = 0;

	
	Endian_Reverse32(Message_Block_W[0]);
	INIT(0);

	#define INIT_NULL_1_14 \
		INIT_NULL(1);  INIT_NULL_2_14;

	#define INIT_NULL_2_14 \
		INIT_NULL(2);  INIT_NULL_3_14;

	#define INIT_NULL_3_14 \
		INIT_NULL(3);  INIT_NULL_4_14;

	#define INIT_NULL_4_14 \
		INIT_NULL(4); INIT_NULL_5_14;

	#define INIT_NULL_5_14 \
		INIT_NULL(5);  INIT_NULL(6);  INIT_NULL(7); \
		INIT_NULL(8);  INIT_NULL(9);  INIT_NULL(10); INIT_NULL(11); \
		INIT_NULL(12); INIT_NULL(13); INIT_NULL(14);

	#define ROTATE1_NULL_1_14 \
		ROTATE1_NULL;  ROTATE1_NULL_2_14;

	#define ROTATE1_NULL_2_14 \
		ROTATE1_NULL;  ROTATE1_NULL_3_14;

	#define ROTATE1_NULL_3_14 \
		ROTATE1_NULL;  ROTATE1_NULL_4_14;

	#define ROTATE1_NULL_4_14 \
		ROTATE1_NULL; ROTATE1_NULL_5_14;

	#define ROTATE1_NULL_5_14 \
		ROTATE1_NULL; ROTATE1_NULL; ROTATE1_NULL; \
		ROTATE1_NULL; ROTATE1_NULL; ROTATE1_NULL; ROTATE1_NULL; \
		ROTATE1_NULL; ROTATE1_NULL; ROTATE1_NULL;


	#define EXPAND(t) \
		W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); \

	#define EXPAND_3(t) W[t] = SHA1CircularShift(1,W[t-3]);
	#define EXPAND_16(t) W[t] = SHA1CircularShift(1,W[t-16]);
	#define EXPAND_3_8(t) W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8]);


	if (length < 4) {
		INIT_NULL_1_14;
		W[15] = W_15;
		EXPAND_16(16);
		W[17] = 0;
		W[18] = W_15<<1;
	}
	else if (length < 8) {
		Endian_Reverse32(Message_Block_W[1]);
		INIT(1);
		INIT_NULL_2_14;
		W[15] = W_15;
		EXPAND_16(16);
		EXPAND_16(17);
		W[18] = W_15<<1;
	}
	else {
		Endian_Reverse32(Message_Block_W[1]);
		Endian_Reverse32(Message_Block_W[2]);
		Endian_Reverse32(Message_Block_W[3]);
		Endian_Reverse32(Message_Block_W[4]);
		INIT(1); INIT(2); INIT(3); INIT(4); 
		INIT_NULL_5_14;
		W[15] = W_15;
		EXPAND(16);
		EXPAND(17);
		EXPAND(18);
	}


	if (length < 12) {
		EXPAND_3(19);
	}
	else {
		EXPAND(19);
	}

	if (length < 16) {
		EXPAND_3(20);
	}
	else {
		EXPAND(20);
	}
	EXPAND_3(21); EXPAND_3(22);
	EXPAND(23);

	EXPAND(24); EXPAND(25); EXPAND_3_8(26);	EXPAND_3_8(27);
	EXPAND(28);	EXPAND(29);	EXPAND(30);	EXPAND(31);
	EXPAND(32);	EXPAND(33);	EXPAND(34);	EXPAND(35);
	EXPAND(36);	EXPAND(37);	EXPAND(38);	EXPAND(39);
	EXPAND(40);	EXPAND(41);	EXPAND(42);	EXPAND(43);
	EXPAND(44);	EXPAND(45);	EXPAND(46);	EXPAND(47);
	EXPAND(48);	EXPAND(49);	EXPAND(50);	EXPAND(51);
	EXPAND(52);	EXPAND(53);	EXPAND(54);	EXPAND(55);
	EXPAND(56);	EXPAND(57);	EXPAND(58);	EXPAND(59);
	EXPAND(60);	EXPAND(61);	EXPAND(62);	EXPAND(63);
	EXPAND(64);	EXPAND(65);	EXPAND(66);	EXPAND(67);
	EXPAND(68);	EXPAND(69);	EXPAND(70);	EXPAND(71);
	EXPAND(72);	EXPAND(73);	EXPAND(74);	EXPAND(75);
	EXPAND(76);	EXPAND(77);	EXPAND(78);	EXPAND(79);


	#define ROTATE1(t) \
			temp = SHA1CircularShift(5,A) + F_00_19(B,C,D) + E + W[t] + K0; \
			E = D; D = C; \
			C = SHA1CircularShift(30,B); \
			B = A; A = temp; \

	#define ROTATE1_NEW(a, b, c, d, e, x) \
			e += SHA1CircularShift(5,a) + F_00_19(b,c,d) + x + K0; \
			b = SHA1CircularShift(30,b);

	#define ROTATE1_W(w) \
			temp = SHA1CircularShift(5,A) + F_00_19(B,C,D) + E + w + K0; \
			E = D; D = C; \
			C = SHA1CircularShift(30,B); \
			B = A; A = temp;

	#define ROTATE1_NULL \
			temp = SHA1CircularShift(5,A) + F_00_19(B,C,D) + E + K0; \
			E = D; D = C; \
			C = SHA1CircularShift(30,B); \
			B = A; A = temp; \
			
	#define ROTATE2_NEW(a, b, c, d, e, x) \
			e += SHA1CircularShift(5,a) + F_20_39(b,c,d) + x + K1; \
			b = SHA1CircularShift(30,b);
	
	#define ROTATE2(t) \
		temp = SHA1CircularShift(5,A) + F_20_39(B,C,D) + E + W[t] + K1; \
        E = D; D = C; \
        C = SHA1CircularShift(30,B); \
        B = A; A = temp;

	#define ROTATE2_W(w) \
		temp = SHA1CircularShift(5,A) + F_20_39(B,C,D) + E + w + K1; \
        E = D; D = C; \
        C = SHA1CircularShift(30,B); \
        B = A; A = temp;

	#define ROTATE3(t) \
		temp = SHA1CircularShift(5,A) + F_40_59(B,C,D) + E + W[t] + K2; \
        E = D; D = C; \
        C = SHA1CircularShift(30,B); \
        B = A; A = temp;

	#define ROTATE4(t) \
		temp = SHA1CircularShift(5,A) + F_60_79(B,C,D) + E + W[t] + K3; \
		E = D; D = C; \
		C = SHA1CircularShift(30,B); \
		B = A; A = temp;

	A = H0;
    B = H1;
    C = H2;
    D = H3;
    E = H4;

	
	E = H2;
	//D = 2079550178;
	//C = 1506887872;
	B = 2679412915 + W[0];
	if (length < 4) {
		A = SHA1CircularShift(5,B) + 1722862861;
	}
	else {
		A = SHA1CircularShift(5,B) + 1722862861 + W[1];
	}

	if (length < 8) {
		temp = SHA1CircularShift(5,A) + ((((1506887872) ^ (2079550178)) & (B)) ^ (2079550178)) + H2 + K0;
	}
	else {
		temp = SHA1CircularShift(5,A) + (((572662306) & (B)) ^ (2079550178)) + H2 + K0 + W[2];
	}
	C = SHA1CircularShift(30,B);  //SHA1CircularShift(30,(2679412915 + W[0]));
	B = A;
	A = temp;
	
	if (length < 12) {
		temp = SHA1CircularShift(5,A) + ((((C) ^ (1506887872)) & (B)) ^ (1506887872)) + 2079550178 + K0;
	}
	else {
		temp = SHA1CircularShift(5,A) + ((((C) ^ (1506887872)) & (B)) ^ (1506887872)) + 2079550178 + K0 + W[3];
	}
	E = 1506887872;
	D = C;
	C = SHA1CircularShift(30,B);
	B = A;
	A = temp;

	if (length < 16) {
		temp = SHA1CircularShift(5,A) + F_00_19(B,C,D) + 1506887872 + K0;
	}
	else {
		temp = SHA1CircularShift(5,A) + F_00_19(B,C,D) + 1506887872 + K0 + W[4];
	}
	E = D;
	D = C;
	C = SHA1CircularShift(30,B);
	B = A;
	A = temp;

	ROTATE1_NULL_5_14;

	ROTATE1_NEW( A, B, C, D, E, W_15 );
    ROTATE1_NEW( E, A, B, C, D, W[16] );
    ROTATE1_NEW( D, E, A, B, C, W[17] );
    ROTATE1_NEW( C, D, E, A, B, W[18] );
    ROTATE1_NEW( B, C, D, E, A, W[19] );
	
    for(t = 20; t < 40; t++)
    {
		if (t == 21 && length < 8) {
			ROTATE2_W((length<<5)); // *32
		}
		else {
			ROTATE2(t);
		}
    }

    for(t = 40; t < 60; t++)
    {
  		ROTATE3(t);
    }

    for(t = 60; t < 80; t++)
    {
		ROTATE4(t);
    }

    Intermediate_Hash[0] += A;
    Intermediate_Hash[1] += B;
    Intermediate_Hash[2] += C;
    Intermediate_Hash[3] += D;
    Intermediate_Hash[4] += E;

	Endian_Reverse32(Intermediate_Hash[0]);
	Endian_Reverse32(Intermediate_Hash[1]);
	Endian_Reverse32(Intermediate_Hash[2]);
	Endian_Reverse32(Intermediate_Hash[3]);
	Endian_Reverse32(Intermediate_Hash[4]);

	memcpy(pDigest, Intermediate_Hash, 20);
}
Ejemplo n.º 12
0
UInt32 RTSPPacket::build(Exception& ex,UInt8* data,UInt32 size) {
	if (_data)
		return 0;
	exception.set(Exception::NIL);

	/// read data
	ReadingStep			step(CMD);
	UInt8*				current(data);
	const UInt8*		end(current+size);
	const char*			signifiant(NULL);
	const char*			key(NULL);

	// headers

	for (; current <= end;++current) {

		if (memcmp(current, EXPAND("\r\n")) == 0 || memcmp(current, EXPAND("\0\n")) == 0) {

			if (!ex && signifiant) {
				// KEY = VALUE
				UInt8* endValue(current);
				while (isblank(*--endValue));
				*(endValue+1) = 0;
				if (!key) { // version case!
					String::ToNumber(signifiant+5, version);
				} else {
					headers[key] = signifiant;
					parseHeader(ex,key,signifiant);
					key = NULL;
				}
			}
			step = LEFT;
			current += 2;
			signifiant = (const char*)current;
			++current; // here no continue, the "\r\n" check is not required again
		}

		if (ex)
			continue; // try to go to "\r\n\r\n"

		// http header, byte by byte
		UInt8 byte = *current;

		if ((step == LEFT || step == CMD || step == PATH) && (isspace(byte) || byte==0)) {
			if (step == CMD) {
				if ((command = RTSP::ParseCommand(ex, signifiant)) == RTSP::COMMAND_UNKNOWN) {
					exception = ex;
					continue;
				}
				if(command == RTSP::COMMAND_DESCRIBE) // Only for DESCRIBE : content = application/sdp
					responseType = HTTP::CONTENT_APPLICATON;
				signifiant = NULL;
				step = PATH;
			} else if (step == PATH) {
				// parse query
				*current = 0;
				size_t filePos = Util::UnpackUrl(signifiant, path,query);
				url.assign(signifiant);

				// Get trackID
				if(filePos != string::npos && path.size() > 9 && String::ICompare(path.substr(filePos),"trackID=",8)==0) {
					trackID = String::ToNumber<UInt8>(ex, 0, path.substr(filePos+8));
					path.erase(filePos - 1); // remove trackID part
					filePos = path.find_last_of('/');
					if (filePos != string::npos)
						filePos++;
				}

				// Record file directory and path
				file.setPath(path);
				if (filePos != string::npos)
					path.erase(filePos - 1);
				else
					file.makeFolder();
				signifiant = NULL;
				step = VERSION;
			} else
				++signifiant; // for trim begin of key or value
		} else if (step > PATH && !key && (byte == ':' || byte == 0)) {
			// KEY
			key = signifiant;
			step = LEFT;
			UInt8* endValue(current);
			while (isblank(*--endValue));
			*(endValue+1) = 0;
			signifiant = (const char*)current + 1;
		} else if (step == CMD || step == PATH || step == VERSION) {
			if (!signifiant)
				signifiant = (const char*)current;
			if (step == CMD && (current-data)>13) // not a RTSP valid command, consumes all
				exception = ex.set(Exception::PROTOCOL, "invalid RTSP command");
		} else
			step = RIGHT;
	}

	_data = data;
	return _size = current - data;
}
Ejemplo n.º 13
0
unsigned long mm_getFreePages(int gfp_mask, unsigned long order) {
	unsigned long flags;
	unsigned long ret_address;
	unsigned long page_order ;

	stat_allocs++;
	ret_address = 0;
	page_order = order;
	if (order >= NR_MEM_LISTS)
		return ret_address;

	spin_lock_irqsave(&free_area_lock, flags);
	do {
		struct free_mem_area_struct * area = free_mem_area+order;
		unsigned long new_order = order;
		do { struct page *prev = memory_head(area), *ret = prev->next;
			while (memory_head(area) != ret) {
				if ( CAN_DMA(ret)) {
					unsigned long map_nr;
					(prev->next = ret->next)->prev = prev;
					map_nr = ret - g_mem_map;
					MARK_USED(map_nr, new_order, area);
					area->stat_count--;
					g_nr_free_pages -= 1 << order;
					EXPAND(ret, map_nr, order, new_order, area);
					DEBUG(" Page alloc return address: %x mask:%x order:%d \n",ADDRESS(map_nr),gfp_mask,order);
					if (gfp_mask & MEM_CLEAR) ut_memset(ADDRESS(map_nr),0,PAGE_SIZE<<order);
					if (!(gfp_mask & MEM_FOR_CACHE)) memleakHook_alloc(ADDRESS(map_nr),PAGE_SIZE<<order,0,0);
					ret_address = ADDRESS(map_nr);
					goto last;
				}
				prev = ret;
				ret = ret->next;
			}
			new_order++; area++;
		} while (new_order < NR_MEM_LISTS);
	} while (0);


last:
	if (ret_address > 0) {
		unsigned long i = (1 << page_order);
		struct page *page = virt_to_page(ret_address);

		while (i--) {
#ifdef MEMORY_DEBUG
			if (PageReferenced(page)){
				ut_log("Page Backtrace in Alloc page :\n");
				ut_printBackTrace(page->bt_addr_list,MAX_BACKTRACE_LENGTH);
			}
#endif
			assert(!PageReferenced(page));
			PageSetReferenced(page);
#ifdef MEMORY_DEBUG
			ut_storeBackTrace(page->bt_addr_list,MAX_BACKTRACE_LENGTH);
#endif
			page++;
		}
	}
	spin_unlock_irqrestore(&free_area_lock, flags);

	if (ret_address ==0) return ret_address;
	if ((ret_address >= (KADDRSPACE_START+g_phy_mem_size)) || (ret_address < KADDRSPACE_START)){
		ut_log(" ERROR:  frames execeeding the max frames :%x\n",ret_address);
		BUG();
	}

	return ret_address;
}
static int Run_Update_Binary(const char *path, ZipArchive *Zip, int* wipe_cache) {
	const ZipEntry* binary_location = mzFindZipEntry(Zip, ASSUMED_UPDATE_BINARY_NAME);
	string Temp_Binary = "/tmp/updater";
	int binary_fd, ret_val, pipe_fd[2], status, zip_verify;
	char buffer[1024];
	const char** args = (const char**)malloc(sizeof(char*) * 5);
	FILE* child_data;

	if (binary_location == NULL) {
		mzCloseZipArchive(Zip);
		return INSTALL_CORRUPT;
	}

	// Delete any existing updater
	if (TWFunc::Path_Exists(Temp_Binary) && unlink(Temp_Binary.c_str()) != 0) {
		LOGINFO("Unable to unlink '%s'\n", Temp_Binary.c_str());
	}

	binary_fd = creat(Temp_Binary.c_str(), 0755);
	if (binary_fd < 0) {
		mzCloseZipArchive(Zip);
		LOGERR("Could not create file for updater extract in '%s'\n", Temp_Binary.c_str());
		return INSTALL_ERROR;
	}

	ret_val = mzExtractZipEntryToFile(Zip, binary_location, binary_fd);
	close(binary_fd);

	if (!ret_val) {
		mzCloseZipArchive(Zip);
		LOGERR("Could not extract '%s'\n", ASSUMED_UPDATE_BINARY_NAME);
		return INSTALL_ERROR;
	}

	// If exists, extract file_contexts from the zip file
	const ZipEntry* selinx_contexts = mzFindZipEntry(Zip, "file_contexts");
	if (selinx_contexts == NULL) {
		mzCloseZipArchive(Zip);
		LOGINFO("Zip does not contain SELinux file_contexts file in its root.\n");
	} else {
		string output_filename = "/file_contexts";
		LOGINFO("Zip contains SELinux file_contexts file in its root. Extracting to %s\n", output_filename.c_str());
		// Delete any file_contexts
		if (TWFunc::Path_Exists(output_filename) && unlink(output_filename.c_str()) != 0) {
			LOGINFO("Unable to unlink '%s'\n", output_filename.c_str());
		}

		int file_contexts_fd = creat(output_filename.c_str(), 0644);
		if (file_contexts_fd < 0) {
			mzCloseZipArchive(Zip);
			LOGERR("Could not extract file_contexts to '%s'\n", output_filename.c_str());
			return INSTALL_ERROR;
		}

		ret_val = mzExtractZipEntryToFile(Zip, selinx_contexts, file_contexts_fd);
		close(file_contexts_fd);

		if (!ret_val) {
			mzCloseZipArchive(Zip);
			LOGERR("Could not extract '%s'\n", ASSUMED_UPDATE_BINARY_NAME);
			return INSTALL_ERROR;
		}
	}
	mzCloseZipArchive(Zip);

#ifndef TW_NO_LEGACY_PROPS
	/* Set legacy properties */
	if (switch_to_legacy_properties() != 0) {
		LOGERR("Legacy property environment did not initialize successfully. Properties may not be detected.\n");
	} else {
		LOGINFO("Legacy property environment initialized.\n");
	}
#endif

	pipe(pipe_fd);

	args[0] = Temp_Binary.c_str();
	args[1] = EXPAND(RECOVERY_API_VERSION);
	char* temp = (char*)malloc(10);
	sprintf(temp, "%d", pipe_fd[1]);
	args[2] = temp;
	args[3] = (char*)path;
	args[4] = NULL;

	pid_t pid = fork();
	if (pid == 0) {
		close(pipe_fd[0]);
		execve(Temp_Binary.c_str(), (char* const*)args, environ);
		printf("E:Can't execute '%s'\n", Temp_Binary.c_str());
		_exit(-1);
	}
	close(pipe_fd[1]);

	*wipe_cache = 0;

	DataManager::GetValue(TW_SIGNED_ZIP_VERIFY_VAR, zip_verify);
	child_data = fdopen(pipe_fd[0], "r");
	while (fgets(buffer, sizeof(buffer), child_data) != NULL) {
		char* command = strtok(buffer, " \n");
		if (command == NULL) {
			continue;
		} else if (strcmp(command, "progress") == 0) {
			char* fraction_char = strtok(NULL, " \n");
			char* seconds_char = strtok(NULL, " \n");

			float fraction_float = strtof(fraction_char, NULL);
			int seconds_float = strtol(seconds_char, NULL, 10);

			if (zip_verify)
				DataManager::ShowProgress(fraction_float * (1 - VERIFICATION_PROGRESS_FRACTION), seconds_float);
			else
				DataManager::ShowProgress(fraction_float, seconds_float);
		} else if (strcmp(command, "set_progress") == 0) {
			char* fraction_char = strtok(NULL, " \n");
			float fraction_float = strtof(fraction_char, NULL);
			DataManager::SetProgress(fraction_float);
		} else if (strcmp(command, "ui_print") == 0) {
			char* display_value = strtok(NULL, "\n");
			if (display_value) {
				gui_print("%s", display_value);
			} else {
				gui_print("\n");
			}
		} else if (strcmp(command, "wipe_cache") == 0) {
			*wipe_cache = 1;
		} else if (strcmp(command, "clear_display") == 0) {
			// Do nothing, not supported by TWRP
		} else {
			LOGERR("unknown command [%s]\n", command);
		}
	}
	fclose(child_data);

	waitpid(pid, &status, 0);

#ifndef TW_NO_LEGACY_PROPS
	/* Unset legacy properties */
	if (legacy_props_path_modified) {
		if (switch_to_new_properties() != 0) {
			LOGERR("Legacy property environment did not disable successfully. Legacy properties may still be in use.\n");
		} else {
			LOGINFO("Legacy property environment disabled.\n");
		}
	}
#endif

	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		LOGERR("Error executing updater binary in zip '%s'\n", path);
		return INSTALL_ERROR;
	}

	return INSTALL_SUCCESS;
}
void write_recovery_version() {
    //No need to write it in multiple locations. 
    //write_string_to_file("/sdcard/0/clockworkmod/.recovery_version",EXPAND(RECOVERY_VERSION));
    write_string_to_file("/sdcard/clockworkmod/.recovery_version",EXPAND(RECOVERY_VERSION));
}
Ejemplo n.º 16
0
        if ((u & DoubleU64FracMask) == 0) {
            return (u & DoubleU64SignMask) ? ScalarType::INF_MINUS : ScalarType::INF_PLUS;
        } 
        return (u & DoubleU64SignMask) ?  ScalarType::NAN_MINUS : ScalarType::NAN_PLUS;
    } else if (me == 0) {
        return ScalarType::DEN;
    }

    return ScalarType::VALID;
}

struct NumberTypeSignature {
    const char* name;
    int len; // including null termination
} g_signatures[] = {
    EXPAND("valid"),
    EXPAND("#DEN"),
    EXPAND("1.#INF00"),
    EXPAND("-1.#INF00"),
    EXPAND("1.#NAN00"),
    EXPAND("-1.#NAN00"),
};

static_assert(dimof(g_signatures) == ScalarType::MAX, "g_signatures array out of sync with enum");

char *flt(char *str, double num, int size, int precision, char fmt, int flags)
{
    char tmp[CVTBUFSIZE];
    char c, sign;
    int n, i;
Ejemplo n.º 17
0
static void sha256_sha224_transform(word32 * state, word32 * data)
{
    word32 A, B, C, D, E, F, G, H;    /* Local vars */
    unsigned i;
    const word32 *k;
    word32 *d;

    /* Set up first buffer and local data buffer */
    A = state[0];
    B = state[1];
    C = state[2];
    D = state[3];
    E = state[4];
    F = state[5];
    G = state[6];
    H = state[7];

    /* Heavy mangling */
    /* First 16 subrounds that act on the original data */

    for (i = 0, k = K, d = data; i < 16; i += 8, k += 8, d += 8) {
        ROUND(A, B, C, D, E, F, G, H, k[0], d[0]);
        ROUND(H, A, B, C, D, E, F, G, k[1], d[1]);
        ROUND(G, H, A, B, C, D, E, F, k[2], d[2]);
        ROUND(F, G, H, A, B, C, D, E, k[3], d[3]);
        ROUND(E, F, G, H, A, B, C, D, k[4], d[4]);
        ROUND(D, E, F, G, H, A, B, C, k[5], d[5]);
        ROUND(C, D, E, F, G, H, A, B, k[6], d[6]);
        ROUND(B, C, D, E, F, G, H, A, k[7], d[7]);
    }

    for (; i < 64; i += 16, k += 16) {
        ROUND(A, B, C, D, E, F, G, H, k[0], EXPAND(data, 0));
        ROUND(H, A, B, C, D, E, F, G, k[1], EXPAND(data, 1));
        ROUND(G, H, A, B, C, D, E, F, k[2], EXPAND(data, 2));
        ROUND(F, G, H, A, B, C, D, E, k[3], EXPAND(data, 3));
        ROUND(E, F, G, H, A, B, C, D, k[4], EXPAND(data, 4));
        ROUND(D, E, F, G, H, A, B, C, k[5], EXPAND(data, 5));
        ROUND(C, D, E, F, G, H, A, B, k[6], EXPAND(data, 6));
        ROUND(B, C, D, E, F, G, H, A, k[7], EXPAND(data, 7));
        ROUND(A, B, C, D, E, F, G, H, k[8], EXPAND(data, 8));
        ROUND(H, A, B, C, D, E, F, G, k[9], EXPAND(data, 9));
        ROUND(G, H, A, B, C, D, E, F, k[10], EXPAND(data, 10));
        ROUND(F, G, H, A, B, C, D, E, k[11], EXPAND(data, 11));
        ROUND(E, F, G, H, A, B, C, D, k[12], EXPAND(data, 12));
        ROUND(D, E, F, G, H, A, B, C, k[13], EXPAND(data, 13));
        ROUND(C, D, E, F, G, H, A, B, k[14], EXPAND(data, 14));
        ROUND(B, C, D, E, F, G, H, A, k[15], EXPAND(data, 15));
    }

    /* Update state */
    state[0] += A;
    state[1] += B;
    state[2] += C;
    state[3] += D;
    state[4] += E;
    state[5] += F;
    state[6] += G;
    state[7] += H;
}
Ejemplo n.º 18
0
void MetaInfoModel::editItem(const QModelIndex &index, QWidget *parent)
{
	bool ok = false;
	int val = -1;
	QStringList generes(QString("(%1)").arg(tr("Unspecified")));
	QString temp;

	QInputDialog input(parent);
	input.setOkButtonText(tr("OK"));
	input.setCancelButtonText(tr("Cancel"));
	input.setTextEchoMode(QLineEdit::Normal);

	switch(index.row() + m_offset)
	{
	case 5:
		input.setWindowTitle(tr("Edit Title"));
		input.setLabelText(EXPAND(tr("Please enter the title for this file:")));
		input.setTextValue(m_metaInfo->title());
		if(input.exec() != 0)
		{
			temp = input.textValue().simplified();
			if(temp.isEmpty())
			{
				QMessageBox::warning(parent, tr("Edit Title"), tr("The title must not be empty. Generating title from file name!"));
				temp = QFileInfo(m_fullInfo->filePath()).completeBaseName().replace("_", " ").simplified();
				int index = temp.lastIndexOf(" - ");
				if(index >= 0) temp = temp.mid(index + 3).trimmed();
			}
			beginResetModel();
			m_metaInfo->setTitle(temp.isEmpty() ? QString() : temp);
			endResetModel();
		}
		break;
	case 6:
		input.setWindowTitle(tr("Edit Artist"));
		input.setLabelText(EXPAND(tr("Please enter the artist for this file:")));
		input.setTextValue(m_metaInfo->artist());
		if(input.exec() != 0)
		{
			temp = input.textValue().simplified();
			beginResetModel();
			m_metaInfo->setArtist(temp.isEmpty() ? QString() : temp);
			endResetModel();
		}
		break;
	case 7:
		input.setWindowTitle(tr("Edit Album"));
		input.setLabelText(EXPAND(tr("Please enter the album for this file:")));
		input.setTextValue(m_metaInfo->album());
		if(input.exec() != 0)
		{
			temp = input.textValue().simplified();
			beginResetModel();
			m_metaInfo->setAlbum(temp.isEmpty() ? QString() : temp);
			endResetModel();
		}
		break;
	case 8:
		input.setWindowTitle(tr("Edit Genre"));
		input.setLabelText(EXPAND(tr("Please enter the genre for this file:")));
		for(int i = 0; g_lamexp_generes[i]; i++) generes << g_lamexp_generes[i];
		input.setComboBoxItems(generes);
		input.setTextValue(m_metaInfo->genre());
		if(input.exec() != 0)
		{
			temp = input.textValue().simplified();
			beginResetModel();
			m_metaInfo->setGenre((temp.isEmpty() || !temp.compare(generes.at(0), Qt::CaseInsensitive)) ? QString() : temp);
			endResetModel();
		}
		break;
	case 9:
		input.setWindowTitle(tr("Edit Year"));
		input.setLabelText(EXPAND(tr("Please enter the year for this file:")));
		input.setIntRange(0, 2100);
		input.setIntValue((m_metaInfo->year() ? m_metaInfo->year() : 1900));
		input.setIntStep(1);
		if(input.exec() != 0)
		{
			val = input.intValue();
			beginResetModel();
			m_metaInfo->setYear(val);
			endResetModel();
		}
		break;
	case 10:
		if(!m_offset)
		{
			input.setWindowTitle(tr("Edit Position"));
			input.setLabelText(EXPAND(tr("Please enter the position (track no.) for this file:")));
			input.setIntRange(0, 99);
			input.setIntValue((m_metaInfo->position() ? m_metaInfo->position() : 1));
			input.setIntStep(1);
			if(input.exec() != 0)
			{
				val = input.intValue();
				beginResetModel();
				m_metaInfo->setPosition(val);
				endResetModel();
			}
		}
		else
		{
			QStringList options;
			options << tr("Unspecified (copy from source file)") << tr("Generate from list position");
			input.setWindowTitle(tr("Edit Position"));
			input.setLabelText(EXPAND(tr("Please enter the position (track no.) for this file:")));
			input.setComboBoxItems(options);
			input.setTextValue(options.value((m_metaInfo->position() == UINT_MAX) ? 1 : 0));
			if(input.exec() != 0)
			{
				temp = input.textValue().simplified();
				beginResetModel();
				m_metaInfo->setPosition((options.indexOf(temp) == 1) ? UINT_MAX : 0);
				endResetModel();
			}
		}
		break;
	case 11:
		input.setWindowTitle(tr("Edit Comment"));
		input.setLabelText(EXPAND(tr("Please enter the comment for this file:")));
		input.setTextValue((m_metaInfo->comment().isEmpty() ? tr("Encoded with LameXP") : m_metaInfo->comment()));
		if(input.exec() != 0)
		{
			temp = input.textValue().simplified();
			beginResetModel();
			m_metaInfo->setComment(temp.isEmpty() ? QString() : temp);
			endResetModel();
		}
		break;
	default:
		QMessageBox::warning(parent, tr("Not editable"), tr("Sorry, this property of the source file cannot be edited!"));
		break;
	}
}
Ejemplo n.º 19
0
MooseApp::~MooseApp()
{
  // Warn if the compiler *does not* have support for the C++11
  // features we plan to initially require support for in MOOSE.  The
  // user can completely opt out of seeing this warning by setting the
  // environment variable MOOSE_CXX11_IGNORE
  char * moose_cxx11_ignore = std::getenv("MOOSE_CXX11_IGNORE");
  if (!moose_cxx11_ignore)
  {
    // Array of feature descriptions
    const char * feature_descriptions[] = {
      "alias declarations",
      "auto keyword",
      "constexpr keyword",
      "decltype keyword",
      "deleted functions",
      "lambdas",
      "move keyword",
      "override keyword",
      "range-based for",
      "rvalue references",
      "std::shared_ptr",
      "std::unique_ptr",
      "variadic templates",
    };

    // Array of true/false values
    const int tf_array[] = {
      setBool(EXPAND(LIBMESH_HAVE_CXX11_ALIAS_DECLARATIONS)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_AUTO)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_CONSTEXPR)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_DECLTYPE)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_DELETED_FUNCTIONS)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_LAMBDA)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_MOVE)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_OVERRIDE)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_RANGEFOR)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_RVALUE_REFERENCES)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_SHARED_PTR)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_UNIQUE_PTR)),
      setBool(EXPAND(LIBMESH_HAVE_CXX11_VARIADIC_TEMPLATES))
    };

    int n_entries = sizeof(tf_array)/sizeof(int);
    int success = std::accumulate(tf_array, tf_array+n_entries, 0);

    // Print prominent warning to screen if compiler does not support
    // one of the features we require.
    if (success < n_entries)
    {
      // Get compiler name and version
#ifdef __clang__
      std::string
        compiler_name = "Clang",
        compiler_version = QUOTE(__clang_major__) "." QUOTE(__clang_minor__) "." QUOTE(__clang_patchlevel__);
#elif __INTEL_COMPILER
      std::string
        compiler_name = "Intel",
        compiler_version = QUOTE(__INTEL_COMPILER_BUILD_DATE);
#elif __GNUG__
      std::string
        compiler_name = "GCC",
        compiler_version = QUOTE(__GNUC__) "." QUOTE(__GNUC_MINOR__) "." QUOTE(__GNUC_PATCHLEVEL__);
#else
      std::string
        compiler_name = "Unknown compiler",
        compiler_version = "Unknown version";
#endif

      std::stringstream oss;
      oss << "--------------------------------------------------------------------------------\n";
      oss << "Warning!\n";
      oss << "MOOSE will soon start using the following C++11 features, but\n";
      oss << "your compiler, " << compiler_name << ' ' << compiler_version << ", does not support the ones marked 'no' below:\n";
      for (int i=0; i<n_entries; ++i)
        printYesNo(oss, feature_descriptions[i], tf_array[i]);
      oss << '\n';
      oss << "These features will require the following minimum compiler versions:\n";
      oss << "* GCC >= 4.8.4\n";
      oss << "* Clang >= 3.4.0\n";
      oss << "* Intel >= 20130607\n";
      oss << "\n";
      oss << "Please upgrade your compiler as soon as possible, or send mail to\n";
      oss << "[email protected] for assistance.\n";
      oss << "--------------------------------------------------------------------------------\n";

      Moose::out << '\n' << oss.str();
    }
  }

  _action_warehouse.clear();
  _executioner.reset();

  delete _input_parameter_warehouse;

#ifdef LIBMESH_HAVE_DLOPEN
  // Close any open dynamic libraries
  for (std::map<std::pair<std::string, std::string>, void *>::iterator it = _lib_handles.begin(); it != _lib_handles.end(); ++it)
    dlclose(it->second);
#endif
}
Ejemplo n.º 20
0
enum nss_status
_nss_files_setnetgrent (const char *group, struct __netgrent *result)
{
  FILE *fp;
  enum nss_status status;

  if (group[0] == '\0')
    return NSS_STATUS_UNAVAIL;

  /* Find the netgroups file and open it.  */
  fp = fopen (DATAFILE, "r");
  if (fp == NULL)
    status = errno == EAGAIN ? NSS_STATUS_TRYAGAIN : NSS_STATUS_UNAVAIL;
  else
    {
      /* Read the file line by line and try to find the description
	 GROUP.  We must take care for long lines.  */
      char *line = NULL;
      size_t line_len = 0;
      const ssize_t group_len = strlen (group);

      status = NSS_STATUS_NOTFOUND;
      result->cursor = result->data;

      while (!feof (fp))
	{
	  ssize_t curlen = getline (&line, &line_len, fp);
	  int found;

	  if (curlen < 0)
	    {
	      status = NSS_STATUS_NOTFOUND;
	      break;
	    }

	  found = (curlen > group_len && strncmp (line, group, group_len) == 0
		   && isspace (line[group_len]));

	  /* Read the whole line (including continuation) and store it
	     if FOUND in nonzero.  Otherwise we don't need it.  */
	  if (found)
	    {
	      /* Store the data from the first line.  */
	      EXPAND (curlen - group_len);
	      memcpy (result->cursor, &line[group_len + 1],
		      curlen - group_len);
	      result->cursor += (curlen - group_len) - 1;
	    }

	  while (line[curlen - 1] == '\n' && line[curlen - 2] == '\\')
	    {
	      /* Yes, we have a continuation line.  */
	      if (found)
		/* Remove these characters from the stored line.  */
		result->cursor -= 2;

	      /* Get next line.  */
	      curlen = getline (&line, &line_len, fp);
	      if (curlen <= 0)
		break;

	      if (found)
		{
		  /* Make sure we have enough room.  */
		  EXPAND (1 + curlen + 1);

		  /* Add separator in case next line starts immediately.  */
		  *result->cursor++ = ' ';

		  /* Copy new line.  */
		  memcpy (result->cursor, line, curlen + 1);
		  result->cursor += curlen;
		}
	    }

	  if (found)
	    {
	      /* Now we have read the line.  */
	      status = NSS_STATUS_SUCCESS;
	      result->cursor = result->data;
	      result->first = 1;
	      break;
	    }
	}

    the_end:
      /* We don't need the file and the line buffer anymore.  */
      free (line);
      fclose (fp);
    }

  return status;
}
Ejemplo n.º 21
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);

    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 (!strcmp(command, "start")) {
            property_set("ctl.start", argv[1]);
            return 0;
        }
        if (!strcmp(command, "stop")) {
            property_set("ctl.stop", argv[1]);
            return 0;
        }
        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\n", ctime(&start));

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_VERSION)"\n");
	ui_print("Builder: "EXPAND(RECOVERY_BUILDER)"\n");
	ui_print("Date: "EXPAND(RECOVERY_BUILD_TIME)"\n");
	ui_print("weibo:@nx-baby\n");
	__system("/sbin/postrecoveryboot.sh");

//#ifdef BOARD_RECOVERY_SWIPE
//#ifndef BOARD_TOUCH_RECOVERY
    //display directions for swipe controls
    ui_print("Swipe up/down to change selections.\n");
    ui_print("Swipe to the right for enter.\n");
    ui_print("Swipe to the left for back.\n");
//#endif
//#endif

    load_volume_table();
    process_volumes();
    vold_init();
    setup_legacy_storage_paths();
#ifdef QCOM_HARDWARE
    parse_t_daemon_data_files();
	apply_time_zone();
#endif
    LOGI("Processing arguments.\n");
    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;
    int sideload = 0;
    int headless = 0;
    int shutdown_after = 0;

    LOGI("Checking arguments.\n");
    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 's': send_intent = optarg; break;
        case 'u':
            if (update_package == NULL)
                update_package = optarg;
            break;
        case 'w':
#ifndef BOARD_RECOVERY_ALWAYS_WIPES
        wipe_data = wipe_cache = 1;
#endif
        break;
        case 'h':
            ui_set_background(BACKGROUND_ICON_CID);
            ui_show_text(0);
            headless = 1;
            break;
        case 'c': wipe_cache = 1; break;
        case 't': ui_show_text(1); break;
        case 'l': sideload = 1; break;
        case 'p': shutdown_after = 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) {
            copy_logs();
            ui_print("Installation aborted.\n");
        } else if (!strcmp(TARGET_DEVICE, "A0001")) { //hack for a0001 ota
            if (strstr(update_package, "/.OTA/"))
                send_intent = "0";
        }
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        preserve_data_media(0);
        if (erase_volume("/data")) status = INSTALL_ERROR;
        preserve_data_media(1);
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) {
            copy_logs();
            ui_print("Data wipe failed.\n");
        }
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) {
            copy_logs();
            ui_print("Cache wipe failed.\n");
        }
    } 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;
        is_user_initiated_recovery = 1;
        if (!headless) {
            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");
        }
    }

    if (sideload) {
        signature_check_enabled = 0;
        if (!headless)
            ui_set_show_text(1);
        if (0 == apply_from_adb()) {
            status = INSTALL_SUCCESS;
            ui_set_show_text(0);
        }
    }

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

    // We reach here when in main menu we choose reboot main system or for some wipe commands on start
    // 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);
    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;
}
Ejemplo n.º 22
0
int FileListModel::importFromCsv(QWidget *parent, const QString &inFile)
{
	QFile file(inFile);
	if(!file.open(QIODevice::ReadOnly))
	{
		return CsvError_FileOpen;
	}

	QTextCodec *codec = NULL;
	QByteArray bomCheck = file.peek(16);

	if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xef\xbb\xbf"))
	{
		codec = QTextCodec::codecForName("UTF-8");
	}
	else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xff\xfe"))
	{
		codec = QTextCodec::codecForName("UTF-16LE");
	}
	else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xfe\xff"))
	{
		codec = QTextCodec::codecForName("UTF-16BE");
	}
	else
	{
		const QString systemDefault = tr("(System Default)");

		QStringList codecList;
		codecList.append(systemDefault);
		codecList.append(lamexp_available_codepages());

		QInputDialog *input = new QInputDialog(parent);
		input->setLabelText(EXPAND(tr("Select ANSI Codepage for CSV file:")));
		input->setOkButtonText(tr("OK"));
		input->setCancelButtonText(tr("Cancel"));
		input->setTextEchoMode(QLineEdit::Normal);
		input->setComboBoxItems(codecList);
	
		if(input->exec() < 1)
		{
			LAMEXP_DELETE(input);
			return CsvError_Aborted;
		}
	
		if(input->textValue().compare(systemDefault, Qt::CaseInsensitive))
		{
			qDebug("User-selected codec is: %s", input->textValue().toLatin1().constData());
			codec = QTextCodec::codecForName(input->textValue().toLatin1().constData());
		}
		else
		{
			qDebug("Going to use the system's default codec!");
			codec = QTextCodec::codecForName("System");
		}

		LAMEXP_DELETE(input);
	}

	bomCheck.clear();

	//----------------------//

	QTextStream stream(&file);
	stream.setAutoDetectUnicode(false);
	stream.setCodec(codec);

	QString headerLine = stream.readLine().simplified();

	while(headerLine.isEmpty())
	{
		if(stream.atEnd())
		{
			qWarning("The file appears to be empty!");
			return CsvError_FileRead;
		}
		qWarning("Skipping a blank line at beginning of CSV file!");
		headerLine = stream.readLine().simplified();
	}

	QStringList header = headerLine.split(";", QString::KeepEmptyParts);

	const int nCols = header.count();
	const int nFiles = m_fileList.count();

	if(nCols < 1)
	{
		qWarning("Header appears to be empty!");
		return CsvError_FileRead;
	}

	bool *ignore = new bool[nCols];
	memset(ignore, 0, sizeof(bool) * nCols);

	for(int i = 0; i < nCols; i++)
	{
		if((header[i] = header[i].trimmed()).isEmpty())
		{
			ignore[i] = true;
		}
	}

	//----------------------//

	for(int i = 0; i < nFiles; i++)
	{
		if(stream.atEnd())
		{
			LAMEXP_DELETE_ARRAY(ignore);
			return CsvError_Incomplete;
		}
		
		QString line = stream.readLine().simplified();
		
		if(line.isEmpty())
		{
			qWarning("Skipping a blank line in CSV file!");
			continue;
		}
		
		QStringList data = line.split(";", QString::KeepEmptyParts);

		if(data.count() < header.count())
		{
			qWarning("Skipping an incomplete line in CSV file!");
			continue;
		}

		const QString key = m_fileList[i];

		for(int j = 0; j < nCols; j++)
		{
			if(ignore[j])
			{
				continue;
			}
			else if(CHECK_HDR(header.at(j), "POSITION"))
			{
				bool ok = false;
				unsigned int temp = data.at(j).trimmed().toUInt(&ok);
				if(ok) m_fileStore[key].metaInfo().setPosition(temp);
			}
			else if(CHECK_HDR(header.at(j), "TITLE"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setTitle(temp);
			}
			else if(CHECK_HDR(header.at(j), "ARTIST"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setArtist(temp);
			}
			else if(CHECK_HDR(header.at(j), "ALBUM"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setAlbum(temp);
			}
			else if(CHECK_HDR(header.at(j), "GENRE"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setGenre(temp);
			}
			else if(CHECK_HDR(header.at(j), "YEAR"))
			{
				bool ok = false;
				unsigned int temp = data.at(j).trimmed().toUInt(&ok);
				if(ok) m_fileStore[key].metaInfo().setYear(temp);
			}
			else if(CHECK_HDR(header.at(j), "COMMENT"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setComment(temp);
			}
			else
			{
				qWarning("Unkonw field '%s' will be ignored!", QUTF8(header.at(j)));
				ignore[j] = true;
				
				if(!checkArray(ignore, false, nCols))
				{
					qWarning("No known fields left, aborting!");
					return CsvError_NoTags;
				}
			}
		}
	}

	//----------------------//

	LAMEXP_DELETE_ARRAY(ignore);
	return CsvError_OK;
}
Ejemplo n.º 23
0
/*
 * add a new (image or link) footnote to the footnote table
 */
static Line*
addfootnote(Line *p, MMIOT* f)
{
    int j, i;
    int c;
    Line *np = p->next;

    Footnote *foot = &EXPAND(*f->footnotes);
    
    CREATE(foot->tag);
    CREATE(foot->link);
    CREATE(foot->title);
    foot->flags = foot->height = foot->width = 0;

    for (j=i=p->dle+1; T(p->text)[j] != ']'; j++)
	EXPAND(foot->tag) = T(p->text)[j];

    EXPAND(foot->tag) = 0;
    S(foot->tag)--;
    j = nextnonblank(p, j+2);

    if ( (f->flags & MKD_EXTRA_FOOTNOTE) && (T(foot->tag)[0] == '^') ) {
	while ( j < S(p->text) )
	    EXPAND(foot->title) = T(p->text)[j++];
	goto skip_to_end;
    }

    while ( (j < S(p->text)) && !isspace(T(p->text)[j]) )
	EXPAND(foot->link) = T(p->text)[j++];
    EXPAND(foot->link) = 0;
    S(foot->link)--;
    j = nextnonblank(p,j);

    if ( T(p->text)[j] == '=' ) {
	sscanf(T(p->text)+j, "=%dx%d", &foot->width, &foot->height);
	while ( (j < S(p->text)) && !isspace(T(p->text)[j]) )
	    ++j;
	j = nextnonblank(p,j);
    }


    if ( (j >= S(p->text)) && np && np->dle && tgood(T(np->text)[np->dle]) ) {
	___mkd_freeLine(p);
	p = np;
	np = p->next;
	j = p->dle;
    }

    if ( (c = tgood(T(p->text)[j])) ) {
	/* Try to take the rest of the line as a comment; read to
	 * EOL, then shrink the string back to before the final
	 * quote.
	 */
	++j;	/* skip leading quote */

	while ( j < S(p->text) )
	    EXPAND(foot->title) = T(p->text)[j++];

	while ( S(foot->title) && T(foot->title)[S(foot->title)-1] != c )
	    --S(foot->title);
	if ( S(foot->title) )	/* skip trailing quote */
	    --S(foot->title);
	EXPAND(foot->title) = 0;
	--S(foot->title);
    }

skip_to_end:
    ___mkd_freeLine(p);
    return np;
}
Ejemplo n.º 24
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);

    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 (!strcmp(command, "start")) {
            property_set("ctl.start", argv[1]);
            return 0;
        }
        if (!strcmp(command, "stop")) {
            property_set("ctl.stop", argv[1]);
            return 0;
        }
        /* Make sure stdout is not fully buffered, we don't want to
         * have issues when calling busybox commands */
        setlinebuf(stdout);
        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\n", ctime(&start));

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_VERSION)"\n");

#ifdef BOARD_RECOVERY_SWIPE
#ifndef BOARD_TOUCH_RECOVERY
    //display directions for swipe controls
    ui_print("Swipe up/down to change selections.\n");
    ui_print("Swipe to the right for enter.\n");
    ui_print("Swipe to the left for back.\n");
#endif
#endif

    load_volume_table();
    process_volumes();
    vold_client_start(&v_callbacks, 0);
    vold_set_automount(1);
    setup_legacy_storage_paths();
    LOGI("Processing arguments.\n");
    ensure_path_mounted(LAST_LOG_FILE);
    rotate_last_logs(10);
    get_args(&argc, &argv);

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

    try_autodeploy(AUTODEPLOY_PACKAGE_FILE);
    try_autodeploy(AUTODEPLOY_PACKAGE_FILE_MULTI);

    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 'd': user_data_update_package = optarg; break;
        case 'w':
#ifndef BOARD_RECOVERY_ALWAYS_WIPES
        wipe_data = wipe_cache = 1;
#endif
        break;
        case 'h':
            ui_set_background(BACKGROUND_ICON_CID);
            ui_show_text(0);
            headless = 1;
            break;
        case 'c': wipe_cache = 1; break;
        case 't': ui_show_text(1); break;
        case 'l': sideload = 1; break;
        case 'v': update_ubuntu_package = UBUNTU_UPDATE_SCRIPT; 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) {
            copy_logs();
            ui_print("Installation aborted.\n");
        }
    } else if (update_ubuntu_package != NULL) {
        LOGI("Performing Ubuntu update");
        ui_set_background(BACKGROUND_ICON_INSTALLING);
        ui_show_indeterminate_progress();
        ui_print("Installing Ubuntu update.\n");
        char tmp[PATH_MAX];
        sprintf(tmp, "%s %s", UBUNTU_UPDATE_SCRIPT, UBUNTU_COMMAND_FILE );
        __system(tmp);
        LOGI("Ubuntu update complete");
        ui_print("Ubuntu update complete.\n");
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        ignore_data_media_workaround(1);
        if (erase_volume("/data")) status = INSTALL_ERROR;
        ignore_data_media_workaround(0);
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) {
            copy_logs();
            ui_print("Data wipe failed.\n");
        }
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) {
            copy_logs();
            ui_print("Cache wipe failed.\n");
        }
    } 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;
        if (!headless) {
            ui_set_show_text(1);
            ui_set_background(BACKGROUND_ICON_UBUNTU);
        }

        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");
        }
    }

    if (sideload) {
        signature_check_enabled = 0;
        if (!headless)
            ui_set_show_text(1);
        if (0 == apply_from_adb()) {
            status = INSTALL_SUCCESS;
            ui_set_show_text(0);
        }
    }

    if (headless) {
        headless_wait();
    }

    if (user_data_update_package != NULL) {
        status = install_package(user_data_update_package);
        if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
    }

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

    // We reach here when in main menu we choose reboot main system or for some wipe commands on start
    // 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");
    reboot_main_system(ANDROID_RB_RESTART, 0, 0);

    return EXIT_SUCCESS;
}
Ejemplo n.º 25
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], "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], "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);
        }
        if (strstr(argv[0], "setprop"))
            return setprop_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;

    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 '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    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 {
        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");
        }
    }

    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();
    }

    // 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;
}
Ejemplo n.º 26
0
int
main(int argc, char **argv) {
        if (strstr(argv[0], "recovery") == NULL)
        {
            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);
            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);
        }
    
    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);
    fprintf(stderr, "Starting recovery on %s", ctime(&start));
    
    ui_init();
    ui_print(EXPAND(RECOVERY_VERSION)"\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;
        }
    }

    //device_recovery_start();

    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");

    int status = INSTALL_SUCCESS;

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

    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_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 if (wipe_cache) {
        if (wipe_cache && erase_root("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 || ui_text_visible()) prompt_and_wait();

    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);
    ui_print("Rebooting...\n");
    sync();
    reboot(RB_AUTOBOOT);
    return EXIT_SUCCESS;
}
Ejemplo n.º 27
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);
    }

#ifdef RECOVERY_CHARGEMODE
    handle_chargemode();
#endif

    //__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\n", ctime(&start));

#ifdef RECOVERY_CHARGEMODE
    int flag;
    flag = get_chargemode();

    if(flag == 1){
//        __system("mount /dev/block/mmcblk0p12 /system");
//        __system("sleep 1");
        __system("charge");
    }else {
#endif

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_WELCOME)"\n");
    ui_print(EXPAND(RECOVERY_VERSION_INFO)"\n");
    ui_print(EXPAND(RECOVERY_BUILD_DATE)"\n");
	__system("/sbin/postrecoveryboot.sh");

#ifdef BOARD_RECOVERY_SWIPE
#ifndef BOARD_TOUCH_RECOVERY
    //display directions for swipe controls
    ui_print("上/下滑动选择.\n");
//    ui_print("Swipe to the right for enter.\n");
//    ui_print("Swipe to the left for back.\n");
#endif
#endif

    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;
//    int headless = 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 'h':
            ui_set_background(BACKGROUND_ICON_CID);
            ui_show_text(0);
            headless = 1;
            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();

    enable_key_backlight();

    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("安装终止.\n");
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        ignore_data_media_workaround(1);
        if (erase_volume("/data")) status = INSTALL_ERROR;
        ignore_data_media_workaround(0);
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("清除数据失败.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("清除缓存失败.\n");
    } else if (sideload) {
        signature_check_enabled = 0;
//        if (!headless)
          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;
//        if (!headless) {
          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 (headless) {
      headless_wait();
    } */
    if (status != INSTALL_SUCCESS && !is_user_initiated_recovery) {
        ui_set_show_text(1);
        ui_set_background(BACKGROUND_ICON_ERROR);
    }
//    else if (status != INSTALL_SUCCESS || ui_text_visible()) {
    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("正在重启...\n");
        android_reboot(ANDROID_RB_RESTART, 0, 0);
    }
    else {
        ui_print("正在关机...\n");
        android_reboot(ANDROID_RB_POWEROFF, 0, 0);
    }
    return EXIT_SUCCESS;
}

#ifdef RECOVERY_CHARGEMODE
	return 0;
}
Ejemplo n.º 28
0
// If the package contains an update binary, extract it and run it.
static int
try_update_binary(const char *path, ZipArchive *zip) {
	struct statfs st;
	char* binary = (char*)malloc(20);

	if (statfs(INCLUDED_BINARY_NAME, &st) != 0) {
		// No update-binary included in recovery, extract it from the zip
		strcpy(binary, "/tmp/update_binary");
		const ZipEntry* binary_entry =
				mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
		if (binary_entry == NULL) {
			mzCloseZipArchive(zip);
			return INSTALL_CORRUPT;
		}

		unlink(binary);
		int fd = creat(binary, 0755);
		if (fd < 0) {
			mzCloseZipArchive(zip);
			LOGE("Can't make %s\n", binary);
			return 1;
		}
		bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
		close(fd);
		mzCloseZipArchive(zip);

		if (!ok) {
			LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
			return 1;
		}
	} else {
		// Use the update-binary that is included in the recovery
		strcpy(binary, INCLUDED_BINARY_NAME);
		LOGI("Using update-binary included in recovery: '%s'.\n", binary);
	}

    int pipefd[2];
    pipe(pipefd);

    // When executing the update binary contained in the package, the
    // arguments passed are:
    //
    //   - the version number for this interface
    //
    //   - an fd to which the program can write in order to update the
    //     progress bar.  The program can write single-line commands:
    //
    //        progress <frac> <secs>
    //            fill up the next <frac> part of of the progress bar
    //            over <secs> seconds.  If <secs> is zero, use
    //            set_progress commands to manually control the
    //            progress of this segment of the bar
    //
    //        set_progress <frac>
    //            <frac> should be between 0.0 and 1.0; sets the
    //            progress bar within the segment defined by the most
    //            recent progress command.
    //
    //        firmware <"hboot"|"radio"> <filename>
    //            arrange to install the contents of <filename> in the
    //            given partition on reboot.
    //
    //            (API v2: <filename> may start with "PACKAGE:" to
    //            indicate taking a file from the OTA package.)
    //
    //            (API v3: this command no longer exists.)
    //
    //        ui_print <string>
    //            display <string> on the screen.
    //
    //   - the name of the package zip file.
    //

    char** args = malloc(sizeof(char*) * 5);
    args[0] = binary;
    args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk
    args[2] = malloc(10);
    sprintf(args[2], "%d", pipefd[1]);
    args[3] = (char*)path;
    args[4] = NULL;

    pid_t pid = fork();
    if (pid == 0) {
        close(pipefd[0]);
        execv(binary, args);
        fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
        _exit(-1);
    }
    close(pipefd[1]);

    char buffer[1024];
    FILE* from_child = fdopen(pipefd[0], "r");
    while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
        char* command = strtok(buffer, " \n");
        if (command == NULL) {
            continue;
        } else if (strcmp(command, "progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            char* seconds_s = strtok(NULL, " \n");

            float fraction = strtof(fraction_s, NULL);
            int seconds = strtol(seconds_s, NULL, 10);

            ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION),
                             seconds);
        } else if (strcmp(command, "set_progress") == 0) {
            char* fraction_s = strtok(NULL, " \n");
            float fraction = strtof(fraction_s, NULL);
            ui_set_progress(fraction);
        } else if (strcmp(command, "ui_print") == 0) {
            char* str = strtok(NULL, "\n");
            if (str) {
                ui_print("%s", str);
            } else {
                ui_print("\n");
            }
        } else {
            LOGE("unknown command [%s]\n", command);
        }
    }
    fclose(from_child);

    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
        return INSTALL_ERROR;
    }

    return INSTALL_SUCCESS;
}
void write_recovery_version() {
    if ( is_data_media() ) {
        write_string_to_file("/sdcard/0/clockworkmod/.recovery_version",EXPAND(RECOVERY_VERSION) "\n" EXPAND(TARGET_DEVICE));
    }
    write_string_to_file("/sdcard/clockworkmod/.recovery_version",EXPAND(RECOVERY_VERSION) "\n" EXPAND(TARGET_DEVICE));
}
Ejemplo n.º 30
0
bool TWPartition::Process_Fstab_Line(string Line, bool Display_Error) {
	char full_line[MAX_FSTAB_LINE_LENGTH], item[MAX_FSTAB_LINE_LENGTH];
	int line_len = Line.size(), index = 0, item_index = 0;
	char* ptr;
	string Flags;

	strncpy(full_line, Line.c_str(), line_len);

	for (index = 0; index < line_len; index++) {
		if (full_line[index] <= 32)
			full_line[index] = '\0';
	}
	Mount_Point = full_line;
	LOGI("Processing '%s'\n", Mount_Point.c_str());
	Backup_Path = Mount_Point;
	index = Mount_Point.size();
	while (index < line_len) {
		while (index < line_len && full_line[index] == '\0')
			index++;
		if (index >= line_len)
			continue;
		ptr = full_line + index;
		if (item_index == 0) {
			// File System
			Fstab_File_System = ptr;
			Current_File_System = ptr;
			item_index++;
		} else if (item_index == 1) {
			// Primary Block Device
			if (Fstab_File_System == "mtd" || Fstab_File_System == "yaffs2") {
				MTD_Name = ptr;
				Find_MTD_Block_Device(MTD_Name);
			} else if (Fstab_File_System == "bml") {
				if (Mount_Point == "/boot")
					MTD_Name = "boot";
				else if (Mount_Point == "/recovery")
					MTD_Name = "recovery";
				Primary_Block_Device = ptr;
				if (*ptr != '/')
					LOGE("Until we get better BML support, you will have to find and provide the full block device path to the BML devices e.g. /dev/block/bml9 instead of the partition name\n");
			} else if (*ptr != '/') {
				if (Display_Error)
					LOGE("Invalid block device on '%s', '%s', %i\n", Line.c_str(), ptr, index);
				else
					LOGI("Invalid block device on '%s', '%s', %i\n", Line.c_str(), ptr, index);
				return 0;
			} else {
				Primary_Block_Device = ptr;
				Find_Real_Block_Device(Primary_Block_Device, Display_Error);
			}
			item_index++;
		} else if (item_index > 1) {
			if (*ptr == '/') {
				// Alternate Block Device
				Alternate_Block_Device = ptr;
				Find_Real_Block_Device(Alternate_Block_Device, Display_Error);
			} else if (strlen(ptr) > 7 && strncmp(ptr, "length=", 7) == 0) {
				// Partition length
				ptr += 7;
				Length = atoi(ptr);
			} else if (strlen(ptr) > 6 && strncmp(ptr, "flags=", 6) == 0) {
				// Custom flags, save for later so that new values aren't overwritten by defaults
				ptr += 6;
				Flags = ptr;
			} else if (strlen(ptr) == 4 && (strncmp(ptr, "NULL", 4) == 0 || strncmp(ptr, "null", 4) == 0 || strncmp(ptr, "null", 4) == 0)) {
				// Do nothing
			} else {
				// Unhandled data
				LOGI("Unhandled fstab information: '%s', %i, line: '%s'\n", ptr, index, Line.c_str());
			}
		}
		while (index < line_len && full_line[index] != '\0')
			index++;
	}

	if (!Is_File_System(Fstab_File_System) && !Is_Image(Fstab_File_System)) {
		if (Display_Error)
			LOGE("Unknown File System: '%s'\n", Fstab_File_System.c_str());
		else
			LOGI("Unknown File System: '%s'\n", Fstab_File_System.c_str());
		return 0;
	} else if (Is_File_System(Fstab_File_System)) {
		Find_Actual_Block_Device();
		Setup_File_System(Display_Error);
		if (Mount_Point == "/system") {
			Display_Name = "System";
			Wipe_Available_in_GUI = true;
		} else if (Mount_Point == "/data") {
			Display_Name = "Data";
			Wipe_Available_in_GUI = true;
			Wipe_During_Factory_Reset = true;
#ifdef RECOVERY_SDCARD_ON_DATA
			Has_Data_Media = true;
			Is_Storage = true;
			Storage_Path = "/data/media";
			if (strcmp(EXPAND(TW_EXTERNAL_STORAGE_PATH), "/sdcard") == 0) {
				Make_Dir("/emmc", Display_Error);
				Symlink_Path = "/data/media";
				Symlink_Mount_Point = "/emmc";
			} else {
				Make_Dir("/sdcard", Display_Error);
				Symlink_Path = "/data/media";
				Symlink_Mount_Point = "/sdcard";
			}
#endif
#ifdef TW_INCLUDE_CRYPTO
			Can_Be_Encrypted = true;
			char crypto_blkdev[255];
			property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
			if (strcmp(crypto_blkdev, "error") != 0) {
				DataManager::SetValue(TW_DATA_BLK_DEVICE, Primary_Block_Device);
				DataManager::SetValue(TW_IS_DECRYPTED, 1);
				Is_Encrypted = true;
				Is_Decrypted = true;
				Decrypted_Block_Device = crypto_blkdev;
				LOGI("Data already decrypted, new block device: '%s'\n", crypto_blkdev);
			} else if (!Mount(false)) {
				Is_Encrypted = true;
				Is_Decrypted = false;
				DataManager::SetValue(TW_IS_ENCRYPTED, 1);
				DataManager::SetValue(TW_CRYPTO_PASSWORD, "");
				DataManager::SetValue("tw_crypto_display", "");
			}
	#ifdef RECOVERY_SDCARD_ON_DATA
			if (!Is_Encrypted || (Is_Encrypted && Is_Decrypted))
				Recreate_Media_Folder();
	#endif
#else
	#ifdef RECOVERY_SDCARD_ON_DATA
			Recreate_Media_Folder();
	#endif
#endif
		} else if (Mount_Point == "/cache") {
			Display_Name = "Cache";
			Wipe_Available_in_GUI = true;
			Wipe_During_Factory_Reset = true;
			if (Mount(false) && !TWFunc::Path_Exists("/cache/recovery/.")) {
				string Recreate_Command = "cd /cache && mkdir recovery";
				LOGI("Recreating /cache/recovery folder.\n");
				system(Recreate_Command.c_str());
			}
		} else if (Mount_Point == "/datadata") {
			Wipe_During_Factory_Reset = true;
			Display_Name = "DataData";
			Is_SubPartition = true;
			SubPartition_Of = "/data";
			DataManager::SetValue(TW_HAS_DATADATA, 1);
		} else if (Mount_Point == "/sd-ext") {
			Wipe_During_Factory_Reset = true;
			Display_Name = "SD-Ext";
			Wipe_Available_in_GUI = true;
			Removable = true;
		} else if (Mount_Point == "/boot") {
			Display_Name = "Boot";
			DataManager::SetValue("tw_boot_is_mountable", 1);
		}
#ifdef TW_EXTERNAL_STORAGE_PATH
		if (Mount_Point == EXPAND(TW_EXTERNAL_STORAGE_PATH)) {
			Is_Storage = true;
			Storage_Path = EXPAND(TW_EXTERNAL_STORAGE_PATH);
			Removable = true;
		}
#else
		if (Mount_Point == "/sdcard") {
			Is_Storage = true;
			Storage_Path = "/sdcard";
			Removable = true;
#ifndef RECOVERY_SDCARD_ON_DATA
			Setup_AndSec();
			Mount_Storage_Retry();
#endif
		}
#endif
#ifdef TW_INTERNAL_STORAGE_PATH
		if (Mount_Point == EXPAND(TW_INTERNAL_STORAGE_PATH)) {
			Is_Storage = true;
			Storage_Path = EXPAND(TW_INTERNAL_STORAGE_PATH);
#ifndef RECOVERY_SDCARD_ON_DATA
			Setup_AndSec();
			Mount_Storage_Retry();
#endif
		}
#else
		if (Mount_Point == "/emmc") {
			Is_Storage = true;
			Storage_Path = "/emmc";
#ifndef RECOVERY_SDCARD_ON_DATA
			Setup_AndSec();
			Mount_Storage_Retry();
#endif
		}
#endif
	} else if (Is_Image(Fstab_File_System)) {
		Find_Actual_Block_Device();
		Setup_Image(Display_Error);
	}

	// Process any custom flags
	if (Flags.size() > 0)
		Process_Flags(Flags, Display_Error);

	return true;
}