uint32 load(uint32 from_addr, uint32 to_addr) { uint8 tryCount; uint32 total_size, romaddr; if(from_addr == 0) return 0; INFO("ESPBOOT: new application at 0x%X\r\n", from_addr); if(check_image(from_addr, &total_size) > 0) { INFO("ESPBOOT: checksum ok, try 3 times to load new app\r\n"); tryCount = 3; while(tryCount --) { load_app(from_addr, to_addr, total_size); if((romaddr = check_image(to_addr, &total_size)) > 0) { return romaddr; } INFO("ESPBOOT: try load again [%d]\r\n", tryCount); } INFO("ESPBOOT: Can't load firmware\r\n"); return 0; } INFO("ESPBOOT: invalid firmware\r\n"); return 0; }
void call_user_start() { uint32 romaddr = 0, total_size = 0, boot_try = 3; INFO("ESPBOOT - New style Bootloader for ESP8266\r\n" "Version: v0.1 - Release: 2015-Nov-01\r\n" "Author: Tuan PM\r\n"); load_boot_cfg(&boot_cfg); if(boot_cfg.new_rom_addr > 0) { if((romaddr = load(boot_cfg.new_rom_addr, boot_cfg.app_rom_addr)) > 0) { boot_cfg.new_rom_addr = 0; save_boot_cfg(&boot_cfg); INFO("ESPBOOT: everyting is ok, goto new app\r\n"); boot_app(romaddr); } INFO("ESPBOOT: backup application at 0x%X\r\n", boot_cfg.backup_rom_addr); if((romaddr = load(boot_cfg.backup_rom_addr, boot_cfg.app_rom_addr)) > 0) { boot_cfg.new_rom_addr = 0; save_boot_cfg(&boot_cfg); INFO("ESPBOOT: everyting is ok, goto backup app\r\n"); boot_app(romaddr); } INFO("ESPBOOT: Goto old application\r\n"); boot_try = 3; while(boot_try-- > 0) { INFO("ESPBOOT: try boot application %d\r\n"); if((romaddr = check_image(boot_cfg.app_rom_addr, &total_size)) > 0) boot_app(romaddr); } ERROR("ESPBOOT: Serious exception !!!\r\n"); } while(boot_try-- > 0) { INFO("ESPBOOT: try boot application %d\r\n"); if((romaddr = check_image(boot_cfg.app_rom_addr, &total_size)) > 0) boot_app(romaddr); } INFO("ESPBOOT: backup application at 0x%X\r\n", boot_cfg.backup_rom_addr); if((romaddr = load(boot_cfg.backup_rom_addr, boot_cfg.app_rom_addr)) > 0) { INFO("ESPBOOT: everyting is ok, goto backup app\r\n"); boot_app(romaddr); } ERROR("Serious exception !!!"); }
// Mask REGISTER_MOD_PARSER(MASK, args) { std::vector<std::string> param = utils::parenthetical_split(args, ','); const size_t s = param.size(); if(s == 0 || (s == 1 && param[0].empty())){ ERR_DP << "no arguments passed to the ~MASK() function\n"; return NULL; } int x = 0, y = 0; if(s == 3) { x = lexical_cast_default<int>(param[1]); y = lexical_cast_default<int>(param[2]); } if(x < 0 || y < 0) { //required by blit_surface ERR_DP << "negative position arguments in ~MASK() function\n"; return NULL; } const image::locator img(param[0]); std::stringstream message; message << "~MASK():"; if(!check_image(img, message)) return NULL; surface surf = get_image(img); return new mask_modification(surf, x, y); }
void LBP_ADAPTER::extractLbpPatchFeature(const Rect* region, vector<float>* descriptors) { check_image(); if (!m_has_extracted) extractLbpFeature(); const int lbp_x = region->x / getCellSize(); const int lbp_y = region->y / getCellSize(); const int lbp_w = region->width / getCellSize(); const int lbp_h = region->height / getCellSize(); const int lbp_w_org = getLbpXDim(); const int lbp_h_org = getLbpYDim(); const int celldim = getLbpCellDim(); const int sz = lbp_w * lbp_h * celldim; descriptors->resize(sz, 0.0); for (int nd = 0; nd < celldim; ++nd) for (int ny = 0; ny < lbp_h; ++ny) { const float* p_org = m_lbp_features + (ny + lbp_y) * lbp_w_org + nd * lbp_w_org * lbp_h_org; vector<float>::iterator p_desc = descriptors->begin() + ny * lbp_w + nd * lbp_w * lbp_h; for (int nx = 0; nx < lbp_w; ++nx) { *(p_desc + nx) = *(p_org + lbp_x + nx); } } }
/* * ======== prepare_file ======== */ static int prepare_file(char * file_name, file_type type, elf_file_info *f_info) { struct stat st; int status = 0; char *access = ((type == INPUT_FILE) ? "r+b" : "w+b"); if ((f_info->fp = fopen(file_name, access)) == NULL) { printf("could not open: %s\n", file_name); status = 2; goto exit; } if (type == INPUT_FILE) { fstat(fileno(f_info->fp), &st); f_info->size = st.st_size; if (!f_info->size) { printf("size is invalid: %s\n", file_name); status = 3; goto exit; } printf("\nPreparing Input ELF file: %s of size: %d\n", file_name, f_info->size); f_info->data = malloc(f_info->size); if (!f_info->data) { printf("allocation failed for reading %s\n", file_name); status = 4; goto exit; } fread(f_info->data, 1, f_info->size, f_info->fp); status = check_image(f_info->data, f_info->size); if (status) { printf("Image check failed for %s\n", file_name); status = 5; goto exit; } status = read_headers(f_info); if (status) { printf("read_headers failed for %s\n", file_name); status = 6; goto exit; } printf("Preparation complete for %s\n", file_name); } else if (type == OUTPUT_FILE) { printf("\nPreparing Output ELF file: %s\n", file_name); status = allocate_headers(f_info); if (status) { printf("allocate_headers failed for %s\n", file_name); status = 7; goto exit; } printf("Preparation complete for %s\n", file_name); } exit: return status; }
/* Returns -1 if somethings fails otherwise 0 */ int main(int argc, char* argv[]) { if (!(argc == 3 || argc == 4)) { std::cerr << "[ ERROR ] Incorrect number of arguments" << std::endl << std::endl; std::cerr << "[ USAGE ] cuber <option> <arguments>" << std::endl; std::cerr << " -c, --check /path/to/image.img checks if image would pass signature verification" << std::endl; std::cerr << " -s, --sign /path/to/input/file.img /path/to/output/file.img creates a signature and outputs a signed image" << std::endl; return -1; } if ((strcmp(argv[1], "--check" ) == 0 || strcmp(argv[1], "-c") == 0) && argc == 3){ std::cout << "[ STATUS ] Checking image... " << argv[2] << std::endl; return check_image(argv[2]); } if ((strcmp(argv[1], "--sign") == 0 || strcmp(argv[1], "-s") == 0) && argc == 4) { if (strcmp(argv[1], argv[2]) == 0) { std::cerr << "[ ERROR ] Input and output paths must be different" << std::endl; return -1; } else { std::cout << "[ STATUS ] Signing image... " << argv[2] << std::endl; return sign_image(argv[2], argv[3]); } } else { std::cerr << "[ ERROR ] Invalid arguments" << std::endl << std::endl; std::cerr << "[ USAGE ] cuber <option> <arguments>" << std::endl; std::cerr << " -c, --check /path/to/image.img checks if image would pass signature verification" << std::endl; std::cerr << " -s, --sign /path/to/input/file.img /path/to/output/file.img creates a signature and outputs a signed image" << std::endl; return -1; } }
int do_tftpd(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) { gpio_init(); if(DETECT()) { printf(" \n## Enter Rescue Mode ##\n"); printf(" \n3: System Boot system code via TFTP.\n"); setenv("autostart", "no"); /* Wait forever for an image */ if (NetLoop(TFTPD) < 0) return 1; } else { if(check_image(0)) { printf(" \nEnter Recuse Mode for image error\n"); printf(" \n3: System Boot system code via TFTP.\n"); if (NetLoop(TFTPD) < 0) return 1; } /* show LED POWER after success image integrity check */ LEDON(); printf(" \n3: System Boot system code via Flash.\n"); do_bootm(cmdtp, 0, argc, argv); } return 0; }
void Handler::image_callback (zbar::Image &img) { bool unexpected = !expect_type; if(unexpected) error("unexpected image callback"); check_image(img); }
//_______________________________________________ double FM::LaplacianEnergy::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); cv::Mat processed; cv::Laplacian( image, processed, CV_8U ); cv::pow( processed, 2, processed ); return cv::sum( processed )[0]; }
const float* LBP_ADAPTER::getLbpFeature() const { check_image(); if (!m_has_extracted) { cerr << "Please call extractLbpFeature() first" << endl; exit(-1); } return m_lbp_features; }
static int new_imagebox( lua_State* L ) { // image as parameter uiImage *i = NULL; if( ! lua_isnoneornil( L, 1 ) ) { i = check_image( L, 1 ); } uiImageBox* b = uiNewImageBox( i ); object_create( L, b, uiImageBoxSignature, control_common, imagebox_functions, 0 ); return 1; }
//_______________________________________________ double FM::StandartDeviationCorrelation::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); double mean = cv::mean( image )[0], part1; for( int row = 0; row < image.rows; row++ ) { for( int column = 0; column < image.cols; column ++ ) { if( row + 1 < image.rows ) { part1 += std::abs( image.at<uchar>( row, column ) * image.at<uchar>( row + 1, column ) - mean ); } } } return part1; }
//_______________________________________________ double FM::PixelCount::measure_focus( cv::Mat image )const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); int sum = 0; for( int row = 0; row < image.rows; row++ ) { for( int column = 0; column < image.cols; column ++ ) { if( image.at<uchar>( row, column ) <= threshold ) { sum++; } } } return sum; }
//_______________________________________________ double FM::ImagePower::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); double sum; for( int x = 0; x < image.cols; x++ ) { for( int y = 0; y < image.rows; y++ ) { uchar pixelXY = image.at<uchar>( x, y ); if( ( int )pixelXY >= ( int ) threshold ) { sum += ( int )pixelXY * ( int ) pixelXY; } } } return sum; }
int LBP_ADAPTER::getLbpFeatureDim() const { check_image(); if (!m_lbp_model) { cerr << "Please call extractLbpFeature() first" << endl; return 0; } const int dim = getLbpXDim() * getLbpYDim() * getLbpCellDim(); return dim; }
//_______________________________________________ double FM::TenenbaumGradient::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); cv::Mat processedX, processedY, total; cv::Sobel( image, processedX, CV_16S, 1, 0 );//Calculates sobel for X cordinates cv::pow( processedX, 2, processedX );//Squares the result cv::Sobel( image, processedY, CV_16S, 0, 1 );//Calculates sobel for Y cordinates cv::pow( processedY, 2, processedY ); cv::add( processedX, processedY, total ); cv::Scalar totalSum = cv::sum( total ); return totalSum[0]; }
//_______________________________________________ double FM::NormalizedVariance::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); double mean = cv::mean( image )[0]; double sum = 0; for( int row = 0; row < image.rows; row++ ) { for( int column = 0; column < image.cols; column ++ ) { uchar pixel = image.at<uchar>( row, column ); sum += std::pow( ( pixel - mean ), 2 ); } } sum = sum / mean; return sum; }
static int l_uiImageBoxSetImage( lua_State* L ) { uiImageBox* i = (uiImageBox*) check_object( L, 1, uiImageBoxSignature ); if( lua_isnoneornil( L, 2 ) ) { uiImageBoxSetImage( i, 0 ); } else { uiImageBoxSetImage( i, check_image( L, 2 ) ); } lua_pushvalue( L, 1 ); return 1; }
//_______________________________________________ double FM::AutoCorrelation::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); double part1 = 0, part2 = 0; for( int row = 0; row < image.rows; row++ ) { for( int column = 0; column < image.cols; column ++ ) { if( row + 1 < image.rows ) { part1 += image.at<uchar>( row, column ) * image.at<uchar>( row + 1, column ); } if( row + 2 < image.rows ) { part2 += image.at<uchar>( row, column ) * image.at<uchar>( row + 2, column ); } } } return std::abs( part1 - part2 ); }
//_______________________________________________ double FM::ThresholdedHistogram::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); ImageHistogram * histogram = new ImageHistogram( bins, image ); int smallerBin = bins + 1, biggestBin = 0; for( int bin = 1; bin <= bins; bin++ ) { if( histogram->pixelsAboveThreshold( bin, threshold ) ) { smallerBin = bin < smallerBin ? bin : smallerBin; biggestBin = bin > biggestBin ? bin : biggestBin; } } int pixelPerBin = floor( 256 / bins ); int smallerPixelRange = ( -1 * ( pixelPerBin ) ) + smallerBin * pixelPerBin; int biggestPixelRange = pixelPerBin * biggestBin; return ( double )biggestPixelRange - smallerPixelRange; }
int acrn_parse_elf(char *arg) { size_t len = strnlen(arg, STR_LEN); size_t elfsz; if (len < STR_LEN) { strncpy(elf_path, arg, len + 1); assert(check_image(elf_path, 0, &elfsz) == 0); elf_file_name = elf_path; printf("SW_LOAD: get elf path %s\n", elf_path); return 0; } else return -1; }
int acrn_parse_ovmf(char *arg) { int error; size_t len = strnlen(arg, STR_LEN); if (len < STR_LEN) { strncpy(ovmf_path, arg, len + 1); error = check_image(ovmf_path, 2 * MB, &ovmf_size); assert(!error); ovmf_file_name = ovmf_path; printf("SW_LOAD: get ovmf path %s, size 0x%lx\n", ovmf_path, ovmf_size); return 0; } else return -1; }
void CMainDlg::OnBnClickedFlCompare() { CBusy busy; if(!m_BootConnected) return; EnableControlBtn(false); // check if code goes to valid memory only - issue warning only, but continue! (r30323) check_image(); LogResetReplaceLine(); verify_mem(1);// to do - what to do when erase operation halted ? ProgressChanged(100); LogResetReplaceLine(); EnableControlBtn(true); }
//_______________________________________________ double FM::BrennerGradient::measure_focus( cv::Mat image ) const { assert( check_image( image ) ); image.convertTo( image, CV_8UC1 ); double sum; for( int x = 0; x < image.cols; x++ ) { for( int y = 0; y < image.rows; y++ ) { uchar pixelXY = image.at<uchar>( y, x ); uchar pixelXY1; if( ( x + 2 ) < image.cols ) { pixelXY1 = image.at<uchar> ( y, x + 2 ); } else { pixelXY1 = ( uchar )0; } uchar alce = ( int ) pixelXY1 - ( int ) pixelXY; alce = alce * alce; if( ( int ) alce >= ( int ) threshold ) sum += ( int ) alce; } } return sum; }
/** Simplified find_image function */ __attribute__((section(".iram2.text"))) usercode* NOINLINE find_image(void) { uint32 buffer[BUFFER_SIZE/4]; uint8 sectcount; uint8 chksum = CHKSUM_INIT; uint32 remaining; uint32 readpos = SECTOR_SIZE * FIRMWARE_START_SECTOR; uint8 *writepos; section_header *section = (section_header*)buffer; usercode* entry = check_image(buffer, §count, &readpos); // copy all the sections while (sectcount > 0) { // read section header SPIRead(readpos, section, sizeof(section_header)); readpos += sizeof(section_header); // get section address and length writepos = section->address; remaining = section->length; while (remaining > 0) { // work out how much to read, up to 16 bytes at a time uint32 readlen = (remaining < BUFFER_SIZE) ? remaining : BUFFER_SIZE; // read the block SPIRead(readpos, buffer, readlen); readpos += readlen; // copy the block ets_memcpy(writepos, buffer, readlen); // increment next write position writepos += readlen; // decrement remaining count remaining -= readlen; } sectcount--; } return entry; }
void LBP_ADAPTER::extractLbpFeature(vector<float>* descriptors) { check_image(); if (m_has_extracted) return; set_gray_image_data(); set_lbp_model(); const int dim = getLbpFeatureDim(); // cerr << dim << endl; m_lbp_features = (float*) utils::mymalloc(dim * sizeof(float)); vl_lbp_process(m_lbp_model, m_lbp_features, m_gray_data, m_org_img.cols, m_org_img.rows, getCellSize()); if (descriptors) { descriptors->resize(dim, 0); copy(m_lbp_features, m_lbp_features + dim, descriptors->begin()); } m_has_extracted = true; }
// prevent this function being placed inline with main // to keep main's stack size as small as possible // don't mark as static or it'll be optimised out when // using the assembler stub uint32 NOINLINE find_image() { uint8 flag; uint32 runAddr; uint32 flashsize; int32 romToBoot; uint8 gpio_boot = FALSE; uint8 updateConfig = TRUE; uint8 buffer[SECTOR_SIZE]; rboot_config *romconf = (rboot_config*)buffer; rom_header *header = (rom_header*)buffer; // delay to slow boot (help see messages when debugging) //ets_delay_us(2000000); ets_printf("\r\nrBoot v1.2.1 - [email protected]\r\n"); // read rom header SPIRead(0, header, sizeof(rom_header)); // print and get flash size ets_printf("Flash Size: "); flag = header->flags2 >> 4; if (flag == 0) { ets_printf("4 Mbit\r\n"); flashsize = 0x80000; } else if (flag == 1) { ets_printf("2 Mbit\r\n"); flashsize = 0x40000; } else if (flag == 2) { ets_printf("8 Mbit\r\n"); flashsize = 0x100000; } else if (flag == 3) { ets_printf("16 Mbit\r\n"); #ifdef BOOT_BIG_FLASH flashsize = 0x200000; #else flashsize = 0x100000; // limit to 8Mbit #endif } else if (flag == 4) { ets_printf("32 Mbit\r\n"); #ifdef BOOT_BIG_FLASH flashsize = 0x400000; #else flashsize = 0x100000; // limit to 8Mbit #endif } else { ets_printf("unknown\r\n"); // assume at least 4mbit flashsize = 0x80000; } // print spi mode ets_printf("Flash Mode: "); if (header->flags1 == 0) { ets_printf("QIO\r\n"); } else if (header->flags1 == 1) { ets_printf("QOUT\r\n"); } else if (header->flags1 == 2) { ets_printf("DIO\r\n"); } else if (header->flags1 == 3) { ets_printf("DOUT\r\n"); } else { ets_printf("unknown\r\n"); } // print spi speed ets_printf("Flash Speed: "); flag = header->flags2 & 0x0f; if (flag == 0) ets_printf("40 MHz\r\n"); else if (flag == 1) ets_printf("26.7 MHz\r\n"); else if (flag == 2) ets_printf("20 MHz\r\n"); else if (flag == 0x0f) ets_printf("80 MHz\r\n"); else ets_printf("unknown\r\n"); // print enabled options #ifdef BOOT_BIG_FLASH ets_printf("rBoot Option: Big flash\r\n"); #endif #ifdef BOOT_CONFIG_CHKSUM ets_printf("rBoot Option: Config chksum\r\n"); #endif #ifdef BOOT_IROM_CHKSUM ets_printf("rBoot Option: irom chksum\r\n"); #endif ets_printf("\r\n"); // read boot config SPIRead(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); // fresh install or old version? if (romconf->magic != BOOT_CONFIG_MAGIC || romconf->version != BOOT_CONFIG_VERSION #ifdef BOOT_CONFIG_CHKSUM || romconf->chksum != calc_chksum((uint8*)romconf, (uint8*)&romconf->chksum) #endif ) { /* Modified by Cesanta */ ets_printf("Writing default boot config.\r\n"); ets_memset(romconf, 0x00, sizeof(rboot_config)); romconf->magic = BOOT_CONFIG_MAGIC; romconf->version = BOOT_CONFIG_VERSION; romconf->count = 2; romconf->mode = MODE_STANDARD; /* FWx_ADDR, FWx_FS_ADDR and FS_SIZE, FW_SIZE must be defined by -D */ romconf->roms[0] = FW1_ADDR; romconf->roms[1] = FW2_ADDR; romconf->fs_addresses[0] = FW1_FS_ADDR; romconf->fs_addresses[1] = FW2_FS_ADDR; romconf->fs_sizes[0] = romconf->fs_sizes[1] = FS_SIZE; romconf->roms_sizes[0] = romconf->roms_sizes[1] = FW_SIZE; #ifdef BOOT_CONFIG_CHKSUM romconf->chksum = calc_chksum((uint8*)romconf, (uint8*)&romconf->chksum); #endif // write new config sector SPIEraseSector(BOOT_CONFIG_SECTOR); SPIWrite(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); } // if gpio mode enabled check status of the gpio if ((romconf->mode & MODE_GPIO_ROM) && (get_gpio16() == 0)) { ets_printf("Booting GPIO-selected.\r\n"); romToBoot = romconf->previous_rom; /* * Modified by Cesanta * Make FD current */ updateConfig = TRUE; romconf->fw_updated = 0; romconf->is_first_boot = 0; gpio_boot = TRUE; } else if (romconf->current_rom >= romconf->count) { // if invalid rom selected try rom 0 ets_printf("Invalid rom selected, defaulting.\r\n"); romToBoot = 0; romconf->current_rom = 0; romconf->fw_updated = 0; romconf->is_first_boot = 0; updateConfig = TRUE; } else { /* Modified by Cesanta */ if (romconf->is_first_boot != 0) { ets_printf("First boot, attempt %d\n", romconf->boot_attempts); /* boot is unconfirmed */ if (romconf->boot_attempts == 0) { /* haven't try to load yes */ ets_printf("Boot is unconfirmed\r\n"); romconf->boot_attempts++; } else { ets_printf("Boot failed, fallback to fw #%d\r\n", romconf->previous_rom); romconf->current_rom = romconf->previous_rom; /* clear fw update flag, to avoid post-update acttions */ romconf->fw_updated = 0; romconf->boot_attempts = 0; } updateConfig = TRUE; } /* End of Cesanta modifications */ // try rom selected in the config romToBoot = romconf->current_rom; } // try to find a good rom do { runAddr = check_image(romconf->roms[romToBoot]); if (runAddr == 0) { ets_printf("Rom %d is bad.\r\n", romToBoot); if (gpio_boot) { // don't switch to backup for gpio-selected rom ets_printf("GPIO boot failed.\r\n"); return 0; } else { // for normal mode try each previous rom // until we find a good one or run out updateConfig = TRUE; romToBoot--; if (romToBoot < 0) romToBoot = romconf->count - 1; if (romToBoot == romconf->current_rom) { // tried them all and all are bad! ets_printf("No good rom available.\r\n"); return 0; } } } } while (runAddr == 0); // re-write config, if required if (updateConfig) { romconf->current_rom = romToBoot; #ifdef BOOT_CONFIG_CHKSUM romconf->chksum = calc_chksum((uint8*)romconf, (uint8*)&romconf->chksum); #endif SPIEraseSector(BOOT_CONFIG_SECTOR); SPIWrite(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); } ets_printf("Booting rom %d.\r\n", romToBoot); // copy the loader to top of iram ets_memcpy((void*)_text_addr, _text_data, _text_len); // return address to load from return runAddr; }
// prevent this function being placed inline with main // to keep main's stack size as small as possible static uint32 NOINLINE find_image() { uint8 flag; uint32 runAddr; uint32 flashsize; int32 romToBoot; uint8 gpio_boot = FALSE; uint8 updateConfig = TRUE; uint8 buffer[SECTOR_SIZE]; rboot_config *romconf = (rboot_config*)buffer; rom_header *header = (rom_header*)buffer; ets_delay_us(2000000); ets_printf("\r\nrBoot v1.0.0 - [email protected]\r\n"); // read rom header SPIRead(0, header, sizeof(rom_header)); // print and get flash size ets_printf("Flash Size: "); flag = header->flags2 >> 4; if (flag == 0) { ets_printf("4 Mbit\r\n"); flashsize = 0x80000; } else if (flag == 1) { ets_printf("2 Mbit\r\n"); flashsize = 0x40000; } else if (flag == 2) { ets_printf("8 Mbit\r\n"); flashsize = 0x100000; } else if (flag == 3) { ets_printf("16 Mbit\r\n"); flashsize = 0x200000; } else if (flag == 4) { ets_printf("32 Mbit\r\n"); flashsize = 0x400000; } else { ets_printf("unknown\r\n"); // assume at least 4mbit flashsize = 0x80000; } // print spi mode ets_printf("Flash Mode: "); if (header->flags1 == 0) { ets_printf("QIO\r\n"); } else if (header->flags1 == 1) { ets_printf("QOUT\r\n"); } else if (header->flags1 == 2) { ets_printf("DIO\r\n"); } else if (header->flags1 == 3) { ets_printf("DOUT\r\n"); } else { ets_printf("unknown\r\n"); } // print spi speed ets_printf("Flash Speed: "); flag = header->flags2 & 0x0f; if (flag == 0) ets_printf("40 MHz\r\n"); else if (flag == 1) ets_printf("26.7 MHz\r\n"); else if (flag == 2) ets_printf("20 MHz\r\n"); else if (flag == 0x0f) ets_printf("80 MHz\r\n"); else ets_printf("unknown\r\n"); // read boot config SPIRead(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); // fresh install or old version? if (romconf->magic != BOOT_CONFIG_MAGIC || romconf->version != BOOT_CONFIG_VERSION) { // create a default config for a standard 2 rom setup ets_printf("Writing default boot config.\r\n"); ets_memset(romconf, 0x00, sizeof(rboot_config)); romconf->magic = BOOT_CONFIG_MAGIC; romconf->version = BOOT_CONFIG_VERSION; romconf->mode = MODE_STANDARD; romconf->current_rom = 0; romconf->count = 2; romconf->current_rom = 0; romconf->roms[0] = SECTOR_SIZE * 2; romconf->roms[1] = (flashsize / 2) + (SECTOR_SIZE * 2); // write new config sector SPIEraseSector(BOOT_CONFIG_SECTOR); SPIWrite(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); } // if gpio mode enabled check status of the gpio if ((romconf->mode & MODE_GPIO_ROM) && (get_gpio16() == 0)) { ets_printf("Booting GPIO-selected.\r\n"); romToBoot = romconf->gpio_rom; gpio_boot = TRUE; } else if (romconf->current_rom >= romconf->count) { // if invalid rom selected try rom 0 ets_printf("Invalid rom selected, defaulting.\r\n"); romToBoot = 0; romconf->current_rom = 0; updateConfig = TRUE; } else { // try rom selected in the config romToBoot = romconf->current_rom; } // try to find a good rom do { runAddr = check_image(romconf->roms[romToBoot]); if (runAddr == 0) { ets_printf("Rom %d is bad.\r\n", romToBoot); if (gpio_boot) { // don't switch to backup for gpio-selected rom ets_printf("GPIO boot failed.\r\n"); return 0; } else { // for normal mode try each previous rom // until we find a good one or run out updateConfig = TRUE; romToBoot--; if (romToBoot < 0) romToBoot = romconf->count - 1; if (romToBoot == romconf->current_rom) { // tried them all and all are bad! ets_printf("No good rom available.\r\n"); return 0; } } } } while (runAddr == 0); // re-write config, if required if (updateConfig) { romconf->current_rom = romToBoot; SPIEraseSector(BOOT_CONFIG_SECTOR); SPIWrite(BOOT_CONFIG_SECTOR * SECTOR_SIZE, buffer, SECTOR_SIZE); } ets_printf("Booting rom %d.\r\n", romToBoot); // copy the loader to top of iram ets_memcpy((void*)_text_addr, _text_data, _text_len); // return address to load from return runAddr; }
static void ueblktap_setup(struct xs_handle *h, char *bepath) { struct backend_info *be; char *path = NULL, *p,*dev; int len, er, deverr; long int pdev = 0, handle; blkif_info_t *blk; const char* errmsg = NULL; be = be_lookup_be(bepath); if (be == NULL) { DPRINTF("ERROR: backend changed called for nonexistent " "backend! (%s)\n", bepath); goto fail; } deverr = xs_gather(h, bepath, "physical-device", "%li", &pdev, NULL); if (!deverr) { DPRINTF("pdev set to %ld\n",pdev); if (be->pdev && be->pdev != pdev) { DPRINTF("changing physical-device not supported"); goto fail; } be->pdev = pdev; } /* Check to see if device is to be opened read-only. */ deverr = xs_gather(h, bepath, "mode", NULL, &path, NULL); if (deverr) { DPRINTF("ERROR: could not find read/write mode\n"); goto fail; } else if (path[0] == 'r') be->readonly = 1; if (be->blkif == NULL) { /* Front end dir is a number, which is used as the handle. */ p = strrchr(be->frontpath, '/') + 1; handle = strtoul(p, NULL, 0); be->blkif = alloc_blkif(be->frontend_id); if (be->blkif == NULL) goto fail; be->blkif->be_id = get_be_id(bepath); /* Insert device specific info, */ blk = malloc(sizeof(blkif_info_t)); if (!blk) { DPRINTF("Out of memory - blkif_info_t\n"); goto fail; } er = xs_gather(h, bepath, "params", NULL, &blk->params, NULL); if (er) goto fail; be->blkif->info = blk; if (deverr) { /*Dev number was not available, try to set manually*/ pdev = convert_dev_name_to_num(blk->params); be->pdev = pdev; } if (check_image(h, be, &errmsg)) goto fail; er = blkif_init(be->blkif, handle, be->pdev, be->readonly); if (er != 0) { DPRINTF("Unable to open device %s\n",blk->params); goto fail; } DPRINTF("[BECHG]: ADDED A NEW BLKIF (%s)\n", bepath); } /* Supply the information about the device to xenstore */ er = xs_printf(h, be->backpath, "sectors", "%llu", be->blkif->ops->get_size(be->blkif)); if (er == 0) { DPRINTF("ERROR: Failed writing sectors"); goto fail; } er = xs_printf(h, be->backpath, "sector-size", "%lu", be->blkif->ops->get_secsize(be->blkif)); if (er == 0) { DPRINTF("ERROR: Failed writing sector-size"); goto fail; } er = xs_printf(h, be->backpath, "info", "%u", be->blkif->ops->get_info(be->blkif)); if (er == 0) { DPRINTF("ERROR: Failed writing info"); goto fail; } be->blkif->state = CONNECTED; xs_printf(h, be->backpath, "hotplug-status", "connected"); DPRINTF("[SETUP] Complete\n\n"); goto close; fail: if (be) { if (errmsg == NULL) errmsg = "Setting up the backend failed. See the log " "files in /var/log/xen/ for details."; xs_printf(h, be->backpath, "hotplug-error", errmsg); xs_printf(h, be->backpath, "hotplug-status", "error"); backend_remove(h, be); } close: if (path) free(path); return; }
/* Returns -1 if somethings fails otherwise 0 */ int sign_image(char* in, char* out){ /* An int is enough because the partitions shouldn't be bigger than 4GB */ int finalimagesize = 0; /* Load an image at given path */ FILE *imageinput; imageinput = fopen(in, "rb"); if (imageinput == NULL){ std::cerr << "[ ERROR ] Image does not exist at given location" << std::endl; return -1; } /* Check if file has contents */ unsigned imagefilesize = get_file_size(imageinput); if (imagefilesize == 0){ std::cerr << "[ ERROR ] Image has no size" << std::endl; return -1; } /* Extract image header first to determine if the final image is bigger than the orignal */ boot_img_hdr* hdr = NULL; hdr = (boot_img_hdr*)malloc(sizeof(boot_img_hdr)); fread(hdr, sizeof(boot_img_hdr), 1, imageinput); /* Reposition pointer at start */ fseek(imageinput, 0, SEEK_SET); /* Check if image is an Android bootimage */ if (memcmp((char*)hdr->magic, "ANDROID!", 8) != 0){ std::cerr << "[ ERROR ] File is not an Android boot image" << std::endl; return -1; } /* Load necessary variables from header and delete header */ unsigned kernel_actual; unsigned ramdisk_actual; unsigned imagesize_actual; unsigned dt_actual; unsigned page_size = hdr->page_size; unsigned page_mask = hdr->page_size - 1; kernel_actual = ROUND_TO_PAGE(hdr->kernel_size, page_mask); ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask); dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask); free(hdr); /* Calculate size of the "real" image */ imagesize_actual = (page_size + kernel_actual + ramdisk_actual + dt_actual); /* If the "real" image is bigger than the file, the file is probably corrupted */ if (imagefilesize < imagesize_actual){ std::cerr << "[ ERROR ] File is invalid (is it corrupted?)" << std::endl; return -1; } /* If the file is smaller than the "real" image + one page, a buffer with the size of the image would be too small we need allocate a new bigger one */ if (imagefilesize < imagesize_actual + page_size){ finalimagesize = imagefilesize + page_size; } else { finalimagesize = imagefilesize; } /* Load image in buffer and close file */ unsigned char* image = NULL; image = (unsigned char*)malloc(finalimagesize); fread(image, 1, imagefilesize, imageinput); fclose(imageinput); /* Create output file */ FILE *imageoutput; imageoutput = fopen(out, "wb"); if (imageoutput == NULL){ std::cerr << "[ ERROR ] Can't write output image to disk" << std::endl; return -1; } /* Hash the real image */ unsigned char hash[65]; unsigned char signature[SIGNATURE_SIZE]; memset(signature, 0, SIGNATURE_SIZE); sha256_buffer(image, imagesize_actual, hash); /* Create signature with given hash */ int sig = create_signature(hash, signature); /* If the signature is created successfully AND the signature passes the check, the signature will be written into the image buffer, which will written to the output file */ if (sig != -1){ std::cerr << std::endl << "[ STATUS ] Checking created signature... "; if (verify_image(image, signature, imagesize_actual) == 0){ memcpy(image + imagesize_actual, signature, SIGNATURE_SIZE); fwrite(image, finalimagesize, 1, imageoutput); } } /* Cleanup */ fclose(imageoutput); free(image); /* Final check of the output file */ std::cerr << std::endl << "[ STATUS ] Checking created image... "; check_image(out); return 0; }