static struct brw_wm_instruction *translate_insn( struct brw_wm_compile *c, const struct prog_instruction *inst ) { struct brw_wm_instruction *out = get_instruction(c); GLuint writemask = inst->DstReg.WriteMask; GLuint nr_args = brw_wm_nr_args(inst->Opcode); GLuint i, j; /* Copy some data out of the instruction */ out->opcode = inst->Opcode; out->saturate = (inst->SaturateMode != SATURATE_OFF); out->tex_unit = inst->TexSrcUnit; out->tex_idx = inst->TexSrcTarget; /* Args: */ for (i = 0; i < nr_args; i++) { for (j = 0; j < 4; j++) { out->src[i][j] = get_new_ref(c, inst->SrcReg[i], j, out); } } /* Dst: */ if (brw_wm_is_scalar_result(out->opcode)) pass0_set_dst_scalar(c, out, inst, writemask); else pass0_set_dst(c, out, inst, writemask); return out; }
int get_single_instruction(BYTE* bytes, char* str, size_t bufsize){ INSTRUCTION inst; int len = 0; len = get_instruction(&inst, bytes, MODE_32); get_instruction_string(&inst, FORMAT_ATT, 0, str, bufsize); return len; }
static void translate_insn(struct brw_wm_compile *c, const struct prog_instruction *inst) { struct brw_wm_instruction *out = get_instruction(c); GLuint writemask = inst->DstReg.WriteMask; GLuint nr_args = brw_wm_nr_args(inst->Opcode); GLuint i, j; /* Copy some data out of the instruction */ out->opcode = inst->Opcode; out->saturate = (inst->SaturateMode != SATURATE_OFF); out->tex_unit = inst->TexSrcUnit; out->tex_idx = inst->TexSrcTarget; out->tex_shadow = inst->TexShadow; out->eot = inst->Aux & INST_AUX_EOT; out->target = INST_AUX_GET_TARGET(inst->Aux); /* Args: */ for (i = 0; i < nr_args; i++) { for (j = 0; j < 4; j++) { out->src[i][j] = get_new_ref(c, inst->SrcReg[i], j, out); } } /* Dst: */ pass0_set_dst(c, out, inst, writemask); }
bool token::is_instruction(opcodes opcode) const { if (is_instruction()) { return get_instruction().opcode == opcode; } return false; }
void _scitFix_E8_E9(BYTE *functionCode, DWORD functionCodeLength, DWORD currentApiAddress, LPVOID newApiAddress) { INSTRUCTION inst; int insLen = 0; int insPtr = 0; DWORD addr; if (!functionCode || functionCodeLength <= 0 || !currentApiAddress || !newApiAddress) { return; } do { if (functionCode[insPtr] == 0xE8 || functionCode[insPtr] == 0xE9) { /* JMP/CALL - recalculate address */ memcpy(&addr, &functionCode[insPtr + 1], 4); /* calc real original address */ addr = (DWORD)currentApiAddress + insPtr + addr + 5; if ((DWORD)newApiAddress + insPtr >= addr) addr = 0 - ((DWORD)newApiAddress + insPtr) - addr - 5; else addr = 0 - ((DWORD)newApiAddress + insPtr) + addr - 5; memcpy(&functionCode[insPtr + 1], &addr, 4); } insLen = get_instruction(&inst, functionCode + insPtr, MODE_32); if (insLen <= 0) { break; } insPtr += insLen; } while (insPtr < functionCodeLength && insLen); }
uint32_t dasm_print_instruction(uint32_t eip, uint8_t *data, uint32_t size, char *str) { INSTRUCTION inst; // step 2: fetch instruction- uint32_t instrsize = get_instruction(&inst, data, MODE_32); if( instrsize == 0 ) { // printf("invalid instruction\n"); return 0; } str[81] = '\0'; memset(str, 0x20, 81); int i; for (i=0;i<instrsize;i++) { snprintf(str+i*2, 36-2*i, "%02X", data[i]); } memset(str+strlen(str), 0x20, 81-strlen(str)); // step 3: print it get_instruction_string(&inst, FORMAT_INTEL, 0, str+32, 31); return instrsize; }
/** --------------------------------------------------------------------------- \brief calculate instruction length of Addr \param \return \code \endcode -----------------------------------------------------------------------------*/ int GetInstructionLength(BYTE* Addr) { #ifdef _USE_LIBDASM_LIB INSTRUCTION instr = {0}; int Len = get_instruction(&instr, Addr, MODE_32); // check illegal opcode if (0 == Len) { _ASSERTE(!"get_instruction"); return -1; } #ifdef _DEBUG char string[256] = {0}; get_instruction_string(&instr, FORMAT_INTEL, 0, string, sizeof(string)); _tprintf(TEXT("%s\n"), string); #endif return Len; #else DISASSEMBLER Disassembler; INSTRUCTION * Instruction = NULL; if (TRUE != InitDisassembler(&Disassembler, ARCH_X86)) { _ASSERTE(!"InitDisassembler"); return -1; } ULONG Flags = DISASM_DISASSEMBLE | DISASM_DECODE | DISASM_STOPONERROR | DISASM_STOPONANOMALY | DISASM_STOPONRETURN; Instruction = GetInstruction(&Disassembler, (ULONG)Addr, (PBYTE)Addr, Flags); if (!Instruction) { _ASSERTE(!"GetInstruction"); CloseDisassembler(&Disassembler); return -1; } #ifdef _DEBUG DumpInstruction(Instruction, TRUE, TRUE); #endif int Len = Instruction->Length; CloseDisassembler(&Disassembler); return Len; #endif//_USE_LIBDASM_LIB }
void update_regPC() { uint32 instr; char txt[128]; get_instruction( PC->addr, &instr); sprintf(txt, "%.16lX: 0x%.8lX", PC->addr, instr ); gtk_entry_set_text(GTK_ENTRY (enRegPC), txt ); }
int is_valid_bugaddr(unsigned long addr) { unsigned int opcode; if (!get_instruction(&opcode, (unsigned short *)addr)) return 0; return opcode == BFIN_BUG_OPCODE; }
void runPlugin(static HANDLE hProcess, PUNRESOLVED_IMPORT unresolvedImport, unsigned int eip){ DWORD_PTR invalidApiAddress = 0; INSTRUCTION inst; int max_instruction_size = sizeof(UINT8)*15; LPVOID instruction_buffer = (LPVOID)malloc(max_instruction_size); int instruction_size; char buffer[200]; while (unresolvedImport->ImportTableAddressPointer != 0){ //last element is a nulled struct printf("Unresolved : 0x%08x\n", unresolvedImport->InvalidApiAddress); invalidApiAddress = unresolvedImport->InvalidApiAddress; readMemoryFromProcess(hProcess, invalidApiAddress, max_instruction_size, instruction_buffer); instruction_size = get_instruction(&inst, (BYTE *)instruction_buffer, MODE_32); get_instruction_string(&inst, FORMAT_ATT, 0, buffer, sizeof(buffer)); printf("INS: %s\n",buffer); if(inst.type == INSTRUCTION_TYPE_PUSH){ //pushl $0x770fdfa4 char *pch = strstr (buffer,"0x"); //printf("ADDRESS: %s\n",pch); unsigned int correct_address = (unsigned int)strtoul(pch,NULL,16); printf("ADDRESS: %08x\n",correct_address); bool res = writeMemoryToProcess(hProcess, (DWORD_PTR)(unresolvedImport->ImportTableAddressPointer), sizeof(correct_address), &correct_address); printf("writeMemoryToProcess result %d\n" , res); }else{ if(inst.type == INSTRUCTION_TYPE_JMP){ // jmp 0x73d3673d //printf("ADDRESS: %s\n",pch); unsigned int correct_address = ( (unsigned int)strtoul(strstr(buffer, "jmp") + 4 + 2, NULL, 16)) + invalidApiAddress; //printf("ADDRESS: %08x\n",correct_address); bool res = writeMemoryToProcess(hProcess, (DWORD_PTR)(unresolvedImport->ImportTableAddressPointer), sizeof(correct_address), &correct_address); //printf("writeMemoryToProcess result %d\n" , res); } } //if libdasm fails to recognize the insruction bypass this instruction if(instruction_size == 0){ invalidApiAddress = invalidApiAddress + 1; continue; } unresolvedImport++; //next pointer to struct } }
static void decode_instruction(unsigned short *address) { unsigned int opcode; if (!get_instruction(&opcode, address)) return; decode_opcode(opcode); if ((opcode & 0xc0000000) == 0xc0000000 && (opcode & BIT_MULTI_INS) && (opcode & 0xe8000000) != 0xe8000000) { pr_cont(" || "); if (!get_instruction(&opcode, address + 2)) return; decode_opcode(opcode); pr_cont(" || "); if (!get_instruction(&opcode, address + 3)) return; decode_opcode(opcode); } }
/* * Checks to see if the address pointed to is either a * 16-bit CALL instruction, or a 32-bit CALL instruction */ bool is_bfin_call(unsigned short *addr) { unsigned short opcode = 0, *ins_addr; ins_addr = (unsigned short *)addr; if (!get_instruction(&opcode, ins_addr)) return false; if ((opcode >= 0x0060 && opcode <= 0x0067) || (opcode >= 0x0070 && opcode <= 0x0077)) return true; ins_addr--; if (!get_instruction(&opcode, ins_addr)) return false; if (opcode >= 0xE300 && opcode <= 0xE3FF) return true; return false; }
int QAbstractMalbolgeRunner::execute_malbolge_step(int &executed_command) { int instruction = get_instruction(memory[c],c); if (instruction < 0) { this->err(QString("Invalid command %1 at %2.\n").arg(memory[c]).arg(c)); return -1; } executed_command = instruction; switch (instruction){ case MALBOLGE_JMP: c = memory[d]; break; case MALBOLGE_OUT: { this->char_out((char)a); } break; case MALBOLGE_IN: { char read = 0; bool result = this->in(read, &abort_reading_flag); a = (int)((unsigned char)read); if (!result) a = 59048; } break; case MALBOLGE_ROT: a = (memory[d] = rotateR(memory[d])); break; case MALBOLGE_MOVD: d = memory[d]; break; case MALBOLGE_OPR: a = (memory[d] = crazy(a, memory[d])); break; case MALBOLGE_HALT: return 1; case MALBOLGE_NOP: default: break; } translate(memory[c]); c = (c+1)%59049; d = (d+1)%59049; return 0; }
/* * Checks to see if the address pointed to is either a * 16-bit CALL instruction, or a 32-bit CALL instruction */ static bool is_bfin_call(unsigned short *addr) { unsigned int opcode; if (!get_instruction(&opcode, addr)) return false; if ((opcode >= 0x0060 && opcode <= 0x0067) || (opcode >= 0x0070 && opcode <= 0x0077) || (opcode >= 0xE3000000 && opcode <= 0xE3FFFFFF)) return true; return false; }
static void decode_instruction(unsigned short *address) { unsigned short opcode; if (get_instruction(&opcode, address)) { if (opcode == 0x0010) verbose_printk("RTS"); else if (opcode == 0x0011) verbose_printk("RTI"); else if (opcode == 0x0012) verbose_printk("RTX"); else if (opcode == 0x0013) verbose_printk("RTN"); else if (opcode == 0x0014) verbose_printk("RTE"); else if (opcode == 0x0025) verbose_printk("EMUEXCPT"); else if (opcode == 0x0040 && opcode <= 0x0047) verbose_printk("STI R%i", opcode & 7); else if (opcode >= 0x0050 && opcode <= 0x0057) verbose_printk("JUMP (P%i)", opcode & 7); else if (opcode >= 0x0060 && opcode <= 0x0067) verbose_printk("CALL (P%i)", opcode & 7); else if (opcode >= 0x0070 && opcode <= 0x0077) verbose_printk("CALL (PC+P%i)", opcode & 7); else if (opcode >= 0x0080 && opcode <= 0x0087) verbose_printk("JUMP (PC+P%i)", opcode & 7); else if (opcode >= 0x0090 && opcode <= 0x009F) verbose_printk("RAISE 0x%x", opcode & 0xF); else if (opcode >= 0x00A0 && opcode <= 0x00AF) verbose_printk("EXCPT 0x%x", opcode & 0xF); else if ((opcode >= 0x1000 && opcode <= 0x13FF) || (opcode >= 0x1800 && opcode <= 0x1BFF)) verbose_printk("IF !CC JUMP"); else if ((opcode >= 0x1400 && opcode <= 0x17ff) || (opcode >= 0x1c00 && opcode <= 0x1fff)) verbose_printk("IF CC JUMP"); else if (opcode >= 0x2000 && opcode <= 0x2fff) verbose_printk("JUMP.S"); else if (opcode >= 0xe080 && opcode <= 0xe0ff) verbose_printk("LSETUP"); else if (opcode >= 0xe200 && opcode <= 0xe2ff) verbose_printk("JUMP.L"); else if (opcode >= 0xe300 && opcode <= 0xe3ff) verbose_printk("CALL pcrel"); else verbose_printk("0x%04x", opcode); } }
static void set_labels_instruction(t_labels **labels, char **file_content) { int cur_case; t_labels *labls; cur_case = -1; labls = *labels; while (file_content[++cur_case]) { if (is_label(file_content[cur_case]) != -1) labls = search_in_labels(labls, get_label(file_content[cur_case])); if (is_instruction(file_content[cur_case]) != -1) add_instruction(&(labls->lst_cmd), get_name_instruction(file_content[cur_case]), get_params(get_instruction(file_content[cur_case]))); } }
RT::Instruction* my_disass_function(const RT::BinaryRegion& binaryRegion, const int64_t& address) { // ... Test RT::Instruction* ret_instruction = NULL; INSTRUCTION inst; char localbuf[128] = {'\0'}; size_t size = get_instruction(&inst, (BYTE*)binaryRegion.content() + address - binaryRegion.baseAddress(), MODE_32); switch(inst.type) { // Hijack flow instruction case INSTRUCTION_TYPE_JMP: case INSTRUCTION_TYPE_RET: ret_instruction = new RT::HijackFlowInstruction(size); //RT::ReferencingInstruction* referencing_instruction = static_cast<RT::HijackFlowInstruction*>(ret_instruction); compute_referenced_address(inst, address, static_cast<RT::HijackFlowInstruction*>(ret_instruction)); //std::cout << "Referenced address: " << static_cast<RT::HijackFlowInstruction*>(ret_instruction)->referencedAddress() << std::endl; break; case INSTRUCTION_TYPE_JMPC: // Conditional jump case INSTRUCTION_TYPE_CALL: ret_instruction = new RT::FlowInstruction(size); compute_referenced_address(inst, address, static_cast<RT::HijackFlowInstruction*>(ret_instruction)); break; // TODO: cases for ReferencingInstruction default: ret_instruction = new RT::Instruction(size); } /* get_instruction_string(&inst, FORMAT_INTEL, 0, localbuf, 127); std::cout << localbuf << std::endl; */ return ret_instruction; }
////////////////////////////////////////////////////////////////////////// // CPU运行,是一个循环 int CPURun() { WORD cs=-1; while (1) { if (debugHelp==1&&OutDisam==1 && (eCPU.cs==cs || cs==(WORD)-1)){ get_instruction(&inst, (BYTE *)evIP + MemoryStart, MODE_16); get_instruction_string(&inst, FORMAT_INTEL, 0, szCode, 300); fprintf(fp, "%4x:%4x : %s\n", eCPU.cs, eCPU.ip, szCode); fflush(fp); cs = eCPU.cs; } //MessageBox(NULL, szCode, NULL, NULL); debugHelp = 1; ExecIns(); FlashRAM(); ExecInt(); #ifdef _VM_DEBUG_ if (eCPU.ip==0xa6ba && eCPU.cs==0x1cd) { __asm nop //这里方便自己调试程序 } if (eCPU.ip==0x169 && eCPU.cs==0x8a00) { __asm nop //这里方便自己调试程序 } if (eCPU.ip==0x3d7 && eCPU.cs==0x1e10) { __asm nop //这里方便自己调试程序 } #endif } return 0; }
int Node_dfg::compute_nb_descendant(int nb_instr, int* deja_comptes){ if(!deja_comptes){ deja_comptes = new int[nb_instr]; for(int i=0; i<nb_instr; i++){ deja_comptes[i]=0; } } int index=get_instruction()->get_index(); list<Arc_t*>::iterator it; int sum=0; for(it=_arc.begin(); it!=_arc.end(); it++){ if(!deja_comptes[(*it)->next->get_instruction()->get_index()]) sum+= (*it)->next->compute_nb_descendant(nb_instr, deja_comptes); } if(!deja_comptes[index]){ sum++; deja_comptes[index]=1; } return sum; }
int exec_instructions(t_corewar *core, t_champions *champions) { t_instruction instruction; t_champions *tmp; tmp = champions; while (tmp) { if (tmp->cycle_to_wait <= 1) { get_instruction(core, tmp, &instruction); if ((exec_function(core, tmp, &instruction)) == -1) return (-1); get_cycle_to_wait(core, tmp); } else tmp->cycle_to_wait -= 1; tmp->last_live += 1; if (tmp == tmp->next) return (0); tmp = tmp->next; } return (0); }
/* * decode the instruction if we are printing out the trace, as it * makes things easier to follow, without running it through objdump * These are the normal instructions which cause change of flow, which * would be at the source of the trace buffer */ void decode_instruction(unsigned short *address) { unsigned short opcode; if (get_instruction(&opcode, address)) { if (opcode == 0x0010) printk("RTS"); else if (opcode == 0x0011) printk("RTI"); else if (opcode == 0x0012) printk("RTX"); else if (opcode >= 0x0050 && opcode <= 0x0057) printk("JUMP (P%i)", opcode & 7); else if (opcode >= 0x0060 && opcode <= 0x0067) printk("CALL (P%i)", opcode & 7); else if (opcode >= 0x0070 && opcode <= 0x0077) printk("CALL (PC+P%i)", opcode & 7); else if (opcode >= 0x0080 && opcode <= 0x0087) printk("JUMP (PC+P%i)", opcode & 7); else if ((opcode >= 0x1000 && opcode <= 0x13FF) || (opcode >= 0x1800 && opcode <= 0x1BFF)) printk("IF !CC JUMP"); else if ((opcode >= 0x1400 && opcode <= 0x17ff) || (opcode >= 0x1c00 && opcode <= 0x1fff)) printk("IF CC JUMP"); else if (opcode >= 0x2000 && opcode <= 0x2fff) printk("JUMP.S"); else if (opcode >= 0xe080 && opcode <= 0xe0ff) printk("LSETUP"); else if (opcode >= 0xe200 && opcode <= 0xe2ff) printk("JUMP.L"); else if (opcode >= 0xe300 && opcode <= 0xe3ff) printk("CALL pcrel"); else printk("0x%04x", opcode); } }
// Entry point of the plugin // This function will be called PINdemonium void runPlugin(static HANDLE hProcess, PUNRESOLVED_IMPORT unresolvedImport, unsigned int eip){ //local variable int max_instruction_size = sizeof(UINT8)*15; int insDelta; char buffer[2048]; int j,instruction_size; INSTRUCTION inst; DWORD_PTR invalidApiAddress = 0; MEMORY_BASIC_INFORMATION memBasic = {0}; LPVOID instruction_buffer = (LPVOID)malloc(max_instruction_size); while (unresolvedImport->ImportTableAddressPointer != 0) //last element is a nulled struct { bool resolved = false; insDelta = 0; invalidApiAddress = unresolvedImport->InvalidApiAddress; //get the starting IAT address to be analyzed yet for (j = 0; j < 1000; j++) { //if we cannot query the invalidApiAddress then bypass the analysis of this address SIZE_T result = VirtualQueryEx(hProcess,(LPVOID)invalidApiAddress, &memBasic, sizeof(MEMORY_BASIC_INFORMATION)); if (!result || memBasic.State != MEM_COMMIT || memBasic.Protect == PAGE_NOACCESS) { //if the memory region pointed by invalidApiAddress isn't mapped break the for loop and check the next unresolved import break; } //read the memory pointed by invalidApiAddress of the external process in order to disassembke the first instruction found //we read 15 bytes because in the x86varchitectures the instructions are guaranteed to fit in 15 bytes readMemoryFromProcess(hProcess, invalidApiAddress, max_instruction_size, instruction_buffer); //disassemble the first instruction in the buffer //instruction_size will contains the length of the disassembled instruction (0 if fails) instruction_size = get_instruction(&inst, (BYTE *)instruction_buffer, MODE_32); //if libdasm fails to recognize the insruction bypass this instruction if(instruction_size == 0){ invalidApiAddress = invalidApiAddress + 1; insDelta = insDelta + 1; continue; } get_instruction_string(&inst, FORMAT_ATT, 0, buffer, sizeof(buffer)); //check if it is a jump if (strstr(buffer, "jmp")) { //calculate the correct answer (add the invalidApiAddress to the destination of the jmp because it is a short jump) unsigned int correct_address = ( (unsigned int)std::strtoul(strstr(buffer, "jmp") + 4 + 2, NULL, 16)) + invalidApiAddress; /* printf("\n\n---------------- MINI REP --------------\n"); printf("INST %s: \n", buffer); printf("INVALID API : %08x \n", invalidApiAddress); printf("INST DELTA %d \n", insDelta); printf("IAT POINTER : %p\n", unresolvedImport->ImportTableAddressPointer); printf("CORRECT ADDR : %08x\n", correct_address); //printf("SIZE OF CORRECT ADDR: %d\n", sizeof(correct_address)); printf("---------------- END MINI REP --------------\n\n"); */ //if the target address is in a memory space dedicated to dlls we have finished our check if(correct_address >= 0x50000000 && correct_address <= 0x7f000000){ //subtract the stolen API executed correct_address = correct_address - insDelta; writeMemoryToProcess(hProcess, (DWORD_PTR)(unresolvedImport->ImportTableAddressPointer), sizeof(correct_address), &correct_address); //unresolved import probably resolved resolved = true; break; } //follow the target address of the jmp and continue the search //we don't have to increase the INSDelta beccause the jmp itself is not a stolen API (instruction belonging to the dll) else{ invalidApiAddress = correct_address; continue; } } //if not increment the delta for the next fix (es : if we have encountered 4 instruction before the correct jmp we have to decrement the correct_address by 16 byte) insDelta = insDelta + instruction_size; //check the next row inthe IAT invalidApiAddress = invalidApiAddress + instruction_size; } /* //if we cannot resolve the import fix it with a dummy address so scylla isn't able to resolve the API and it will remove the unresolved import // this functionality is optional (set the flag nullify_unknown_iat_entry_flag as true with command line) because it can break the program if(!resolved){ unsigned int correct_address = 0x0; writeMemoryToProcess(hProcess, (DWORD_PTR)(unresolvedImport->ImportTableAddressPointer), sizeof(correct_address), &correct_address); resolved = false; } */ unresolvedImport++; //next pointer to struct } }
/* Escreve no arquivo de saida o resultado da montagem. Recebe arquivos de entrada e saida, e vetores de rotulo e constantes. */ void print_file(char* fileFrom, char* fileTo, label_table t, set_table s){ FILE* _fileFrom = fopen(fileFrom,"r"); FILE* _fileTo = fopen(fileTo,"w"); char word[20]; int position_count= 0; while (!feof(_fileFrom)) { fscanf(_fileFrom," %s ", word); /* Leu comentario. Le toda a linha */ if (strchr(word,'@')) { char character = fgetc(_fileFrom); while (character != '\n') character = fgetc(_fileFrom); } else if (strchr(word,'.')){ /* Eh diretiva, ou seja foi encontrado um '.' */ int d = get_directive(word), isLabel = 0, isContraint = 0; /* Variaveis auxiliares */ char aux[20]; char *_aux_string = (char*) malloc(10*sizeof(char)); int _num, _aux, _value; /* Le primeiro parametro */ fscanf(_fileFrom," %s ",word); switch (d) { /* .org soh precisamos atualizar contador */ case ORG : position_count = get_number(word)*2; break; /* verificamos se preecisamos alinhar mapa de memoria e se ha a necessidade de imprimirmos 00000 a direita de uma linha */ case ALIGN: _num = get_number(word); if (position_count%(2*_num)) { if (position_count%2) /* imprime zeros caso esteja na direita */ fprintf(_fileTo,"%05X\n",0); position_count = position_count/(2*_num)*2 + 2*_num; } break; /* Se eh um .WORD, verificamos se eh um rotulo ou um valor */ case WORD : _value = is_Label(word, t,&isLabel); /* se for rotulo, temos que dividir endereço de memoria por dois */ if (isLabel) sprintf(aux,"%010X", _value/2); else { get_char_value(word, &_aux_string); sprintf(aux,"%s", _aux_string); /* escreve na variavel auxiliar para depois escrevermos no arquivo */ } fprintf(_fileTo,"%03X %s\n",position_count/2, aux); position_count += 2; break;/* atualiza contador */ case WFILL: word[strlen(word)-1] = '\0'; /* ignora-se a ','*/ _num = get_number(word); /* quantidade de iteracoes */ fscanf(_fileFrom," %s ",word); /* transforma valor lido adequadamente para impressao */ get_char_value(word,&_aux_string); /* verifica se um rotulo, constante ou valor */ _value = get_label_value(word, t, s, &isLabel, &isContraint); for (_aux = 0; _aux < _num; _aux++){ /* trata cada caso individualmente */ if (isContraint) { sprintf(word,"%d", _value); /* passa valor da constante para um string, a fim de utilizarmos a funcao get_char_value */ get_char_value(word,&_aux_string); sprintf(aux,"%s", _aux_string); } else if (isLabel) sprintf(aux,"%010X", _value/2); else sprintf(aux,"%s", _aux_string); /* escreve no arquivo */ fprintf(_fileTo,"%03X %s\n",position_count/2, aux); position_count += 2; } break; /* nao faz nada, soh le valor */ case SET : fscanf(_fileFrom," %s ",word); break; default : printf("Erro"); } free(_aux_string ); } /* se nao for rotulo, soh pode ser instrucao */ else if (!strchr(word,':')){ /* Verificamos 'familia' de instrucao */ int _option = get_instruction(word), opcode, isLabel = 0, _val, isContraint = 0; /* Variaveis auxiliares */ char _aux[20], _aux2[20]; switch (_option) { case M_INSTRUCTION : opcode = get_instruction_opcode(word, position_count%2); fscanf(_fileFrom," %s ",word); /* OBTER VALOR ENTRE M() */ strncpy(_aux, word+2, strlen(word)); _aux[strlen(word)-3] = '\0'; /* obtem valor de constante, rotulo ou valor */ _val = get_label_value(_aux,t,s,&isLabel,&isContraint); break; /* Nao ha posicoes de memoria para serem lidas */ case NO_M_INSTRUCTION : opcode = get_instruction_opcode(word, position_count%2); _val = 0; break; /* Devemos verificar se a instrucao refere-se a direita ou esquerda */ case LR_INSTRUCTION : fscanf(_fileFrom," %s ",_aux2); /* OBTER VALOR ENTRE M() */ sprintf(_aux, "%s", _aux2+2); _aux[strlen(_aux)-1] = '\0'; /* obtem valor de constante, rotulo ou valor */ _val = get_label_value(_aux, t,s,&isLabel, &isContraint); /* obtem valor correto da instrucao */ opcode = get_instruction_opcode(word, _val%2); break; } if (isLabel) _val = _val/2; /* Se for um rotulo, o valor deve ser divido por 2, afinal ele representa uma posicao de memoria */ if (position_count%2) /* Verifica se ha a necessidade de escrever a posicao de memoria atual. */ fprintf(_fileTo,"%02X%03X\n",opcode,_val); else fprintf(_fileTo,"%03X %02X%03X",position_count/2,opcode, _val); position_count++; } } /* Verifica se a necessidade de completarmos fim de arquivo com 0 (termicou na direita */ if (position_count%2) fprintf(_fileTo,"%05X\n",0); fclose(_fileFrom); fclose(_fileTo); return; }
void dump_bfin_mem(struct pt_regs *fp) { unsigned short *addr, *erraddr, val = 0, err = 0; char sti = 0, buf[6]; erraddr = (void *)fp->pc; printk(KERN_NOTICE "return address: [0x%p]; contents of:", erraddr); for (addr = (unsigned short *)((unsigned long)erraddr & ~0xF) - 0x10; addr < (unsigned short *)((unsigned long)erraddr & ~0xF) + 0x10; addr++) { if (!((unsigned long)addr & 0xF)) printk("\n" KERN_NOTICE "0x%p: ", addr); if (get_instruction(&val, addr)) { val = 0; sprintf(buf, "????"); } else sprintf(buf, "%04x", val); if (addr == erraddr) { printk("[%s]", buf); err = val; } else printk(" %s ", buf); /* Do any previous instructions turn on interrupts? */ if (addr <= erraddr && /* in the past */ ((val >= 0x0040 && val <= 0x0047) || /* STI instruction */ val == 0x017b)) /* [SP++] = RETI */ sti = 1; } printk("\n"); /* Hardware error interrupts can be deferred */ if (unlikely(sti && (fp->seqstat & SEQSTAT_EXCAUSE) == VEC_HWERR && oops_in_progress)) { printk(KERN_NOTICE "Looks like this was a deferred error - sorry\n"); #ifndef CONFIG_DEBUG_HWERR printk(KERN_NOTICE "The remaining message may be meaningless\n" KERN_NOTICE "You should enable CONFIG_DEBUG_HWERR to get a" " better idea where it came from\n"); #else /* If we are handling only one peripheral interrupt * and current mm and pid are valid, and the last error * was in that user space process's text area * print it out - because that is where the problem exists */ if ((!(((fp)->ipend & ~0x30) & (((fp)->ipend & ~0x30) - 1))) && (current->pid && current->mm)) { /* And the last RETI points to the current userspace context */ if ((fp + 1)->pc >= current->mm->start_code && (fp + 1)->pc <= current->mm->end_code) { printk(KERN_NOTICE "It might be better to look around here : \n"); printk(KERN_NOTICE "-------------------------------------------\n"); show_regs(fp + 1); printk(KERN_NOTICE "-------------------------------------------\n"); } } #endif } }
// Dynamic TOC. Test for any pc-relative instruction. inline bool MacroAssembler::is_pcrelative_instruction(address iloc) { unsigned long inst; get_instruction(iloc, &inst); return is_pcrelative_short(inst) || is_pcrelative_long(inst); }
bool refiner_wpt::refine_prefix( predicatest &predicates, abstract_modelt &abstract_model, const fail_infot &fail_info) { status("Refining set of predicates according to counterexample (WP)"); reset_num_predicates_added(); bool found_new=false; // keep track of the loops that we're in (may be nested) std::list<fail_infot::induction_infot> loops; exprt invariant; if(fail_info.use_invariants) status("Using recurrence predicates detected by loop detection."); print(10, "refiner_wpt::refine_prefix_async 1"); print(10, "Inconsistent prefix:"); for(abstract_counterexamplet::stepst::const_reverse_iterator r_it=fail_info.steps.rbegin(); r_it!=fail_info.steps.rend(); r_it++) { std::stringstream str; abstract_programt::targett abstract_pc=r_it->pc; goto_programt::const_targett concrete_pc= abstract_pc->code.concrete_pc; if(concrete_pc->is_goto()) str << "GUARD: " << (r_it->branch_taken?"(":"!(") << from_expr(concrete_model.ns, "", concrete_pc->guard) << ")"; else if(concrete_pc->is_assert()) str << "ASSERT: " << from_expr(concrete_model.ns, "", concrete_pc->guard); else if(concrete_pc->is_location()) str << "LOC" << std::endl; else if(concrete_pc->is_other() || concrete_pc->is_assign() || concrete_pc->is_decl()) str << from_expr(concrete_model.ns, "", concrete_pc->code); else { str << concrete_pc->type; } str << " // " << (concrete_pc->location); str << std::endl << "**********"; print(10, str.str()); } { // get the constraint causing the failure exprt predicate=fail_info.guard; #ifdef DEBUG std::cout << "P start0: " << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif simplify(predicate, concrete_model.ns); abstract_counterexamplet::stepst::const_iterator it=--fail_info.steps.end(); // there must be at least two steps, or it's odd assert(it!=fail_info.steps.begin()); { abstract_programt::targett abstract_pc=it->pc; #ifdef DEBUG std::cout << "P start1: " << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif add_predicates( abstract_pc, predicates, predicate, found_new, FROM); } // now do the WPs goto_symex_statet renaming_state; renaming_state.source.thread_nr=it->thread_nr; renaming_state.rename(predicate, concrete_model.ns, goto_symex_statet::L0); for(it--; // skip last instruction it!=fail_info.steps.begin(); it--) { #ifdef DEBUG std::cout << "refiner_wpt::refine_prefix_async 2\n"; #endif // handle loops if(fail_info.use_invariants) { if(it->is_loop_begin()) { loops.pop_back(); // pop induction_info if we leave loop #ifdef DEBUG std::cout << "INV: " << from_expr(concrete_model.ns, "", invariant) << std::endl; #endif exprt wp(ID_and, typet(ID_bool)); wp.operands().resize(2); wp.op0().swap(invariant); wp.op1().swap(predicate); predicate.swap(wp); } else if (it->is_loop_end()) { push_induction_info(fail_info, it, loops); invariant.make_true(); } } if(!it->is_state()) continue; if(predicate.is_true() && found_new) { // ok, refuted it, done break; } // add the predicate goto_programt::const_targett concrete_pc= it->pc->code.concrete_pc; abstract_programt::targett abstract_pc=it->pc; #ifdef DEBUG std::cout << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif exprt no_tid_predicate=predicate; renaming_state.get_original_name(no_tid_predicate); add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, TO); // skip irrelevant instructions if(!it->relevant) continue; exprt pred_bak=predicate; #ifdef DEBUG goto_programt tmp; tmp.output_instruction(concrete_model.ns, "", std::cerr, concrete_pc); #endif // compute weakest precondition switch(it->pc->type) { case ASSUME: // we only do this for assumptions // if we haven't found a new predicate so far if(1/*!found_new*/) { exprt tid_guard=concrete_pc->guard; renaming_state.source.thread_nr=it->thread_nr; renaming_state.rename(tid_guard, concrete_model.ns, goto_symex_statet::L0); predicate=implies_exprt(tid_guard, predicate); simplify(predicate, concrete_model.ns); } break; case GOTO: { exprt tid_guard=concrete_pc->guard; if(!it->branch_taken) tid_guard.make_not(); renaming_state.source.thread_nr=it->thread_nr; renaming_state.rename(tid_guard, concrete_model.ns, goto_symex_statet::L0); predicate=implies_exprt(tid_guard, predicate); simplify(predicate, concrete_model.ns); } break; case OTHER: /* Ignore if user-specified predicate, otherwise treat like assign */ if(it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_predicate || it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_parameter_predicates || it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_return_predicates) break; case DECL: case ASSIGN: #ifdef DEBUG std::cout << "OTHER/ASSIGN/DECL\n"; #endif { codet tid_tmp_code; if(!fail_info.use_invariants || !get_instruction(concrete_pc, loops, tid_tmp_code, invariant)) tid_tmp_code=to_code(concrete_pc->code); #ifdef DEBUG std::cout << "A P before: " << from_expr(concrete_model.ns, "", predicate) << std::endl; std::cout << "Code: " << from_expr(concrete_model.ns, "", tid_tmp_code) << std::endl; #endif // compute weakest precondition if(tid_tmp_code.get_statement()==ID_assign) approximate_nondet(to_code_assign(tid_tmp_code).rhs()); renaming_state.source.thread_nr=it->thread_nr; renaming_state.rename(tid_tmp_code, concrete_model.ns, goto_symex_statet::L0); exprt predicate_wp=wp(tid_tmp_code, predicate, concrete_model.ns); simplify(predicate_wp, concrete_model.ns); predicate=predicate_wp; #ifdef DEBUG std::cout << "A P after: " << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif } break; default: // ignore break; } #ifdef DEBUG std::cout << "B P to-check: " << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif if(pred_bak != predicate) { satcheckt satcheck; bv_pointerst solver(concrete_model.ns, satcheck); solver.unbounded_array=boolbvt::U_NONE; literalt li=make_pos(concrete_model.ns, solver, predicate); satcheck.set_assumptions(bvt(1, li)); propt::resultt result=satcheck.prop_solve(); assert(propt::P_SATISFIABLE==result || propt::P_UNSATISFIABLE==result); if(propt::P_UNSATISFIABLE==result) predicate.make_false(); else { satcheck.set_assumptions(bvt(1, li.negation())); propt::resultt result=satcheck.prop_solve(); assert(propt::P_SATISFIABLE==result || propt::P_UNSATISFIABLE==result); if(propt::P_UNSATISFIABLE==result) { predicate.make_true(); if(it->pc->type==ASSIGN) { const codet &code=concrete_pc->code; if(code.get_statement()==ID_assign) { equal_exprt pred_new(to_code_assign(code).lhs(), to_code_assign(code).rhs()); simplify(pred_new, concrete_model.ns); #ifdef DEBUG std::cout << "Adding new predicate as we arrived at TRUE: " << from_expr(concrete_model.ns, "", pred_new) << std::endl; #endif no_tid_predicate=pred_new; renaming_state.get_original_name(no_tid_predicate); add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM); } } else if(it->pc->type==ASSUME || it->pc->type==GOTO) { exprt pred_new=concrete_pc->guard; simplify(pred_new, concrete_model.ns); #ifdef DEBUG std::cout << "Adding new predicate as we arrived at TRUE: " << from_expr(concrete_model.ns, "", pred_new) << std::endl; #endif no_tid_predicate=pred_new; renaming_state.get_original_name(no_tid_predicate); add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM); } } } } #ifdef DEBUG std::cout << "B P after: " << from_expr(concrete_model.ns, "", predicate) << std::endl; #endif no_tid_predicate=predicate; renaming_state.get_original_name(no_tid_predicate); add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM); } if(!predicate.is_true() && fail_info.warn_on_failure) { warning("Failed to refute spurious trace with WPs (got "+ from_expr(concrete_model.ns, "", predicate)+")"); } } if(found_new && fail_info.use_invariants) { add_induction_predicates( fail_info, abstract_model, predicates); } // make sure we have progress return !found_new; }
asmlinkage notrace void trap_c(struct pt_regs *fp) { #ifdef CONFIG_DEBUG_BFIN_HWTRACE_ON int j; #endif #ifdef CONFIG_BFIN_PSEUDODBG_INSNS int opcode; #endif unsigned int cpu = raw_smp_processor_id(); const char *strerror = NULL; int sig = 0; siginfo_t info; unsigned long trapnr = fp->seqstat & SEQSTAT_EXCAUSE; trace_buffer_save(j); #if defined(CONFIG_DEBUG_MMRS) || defined(CONFIG_DEBUG_MMRS_MODULE) last_seqstat = (u32)fp->seqstat; #endif fp->orig_pc = fp->retx; switch (trapnr) { case VEC_EXCPT01: info.si_code = TRAP_ILLTRAP; sig = SIGTRAP; CHK_DEBUGGER_TRAP_MAYBE(); if (kernel_mode_regs(fp)) goto traps_done; else break; case VEC_EXCPT03: info.si_code = SEGV_STACKFLOW; sig = SIGSEGV; strerror = KERN_NOTICE EXC_0x03(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_EXCPT02: #ifdef CONFIG_KGDB info.si_code = TRAP_ILLTRAP; sig = SIGTRAP; CHK_DEBUGGER_TRAP(); goto traps_done; #endif case VEC_EXCPT04 ... VEC_EXCPT15: info.si_code = ILL_ILLPARAOP; sig = SIGILL; strerror = KERN_NOTICE EXC_0x04(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_STEP: info.si_code = TRAP_STEP; sig = SIGTRAP; CHK_DEBUGGER_TRAP_MAYBE(); if (kernel_mode_regs(fp)) goto traps_done; else break; case VEC_OVFLOW: info.si_code = TRAP_TRACEFLOW; sig = SIGTRAP; strerror = KERN_NOTICE EXC_0x11(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_UNDEF_I: #ifdef CONFIG_BUG if (kernel_mode_regs(fp)) { switch (report_bug(fp->pc, fp)) { case BUG_TRAP_TYPE_NONE: break; case BUG_TRAP_TYPE_WARN: dump_bfin_trace_buffer(); fp->pc += 2; goto traps_done; case BUG_TRAP_TYPE_BUG: panic("BUG()"); } } #endif #ifdef CONFIG_BFIN_PSEUDODBG_INSNS if (!kernel_mode_regs(fp) && get_instruction(&opcode, (unsigned short *)fp->pc)) { if (execute_pseudodbg_assert(fp, opcode)) goto traps_done; if (execute_pseudodbg(fp, opcode)) goto traps_done; } #endif info.si_code = ILL_ILLOPC; sig = SIGILL; strerror = KERN_NOTICE EXC_0x21(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_ILGAL_I: info.si_code = ILL_ILLPARAOP; sig = SIGILL; strerror = KERN_NOTICE EXC_0x22(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_CPLB_VL: info.si_code = ILL_CPLB_VI; sig = SIGSEGV; strerror = KERN_NOTICE EXC_0x23(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_MISALI_D: info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x24(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_UNCOV: info.si_code = ILL_ILLEXCPT; sig = SIGILL; strerror = KERN_NOTICE EXC_0x25(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_CPLB_M: info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x26(KERN_NOTICE); break; case VEC_CPLB_MHIT: info.si_code = ILL_CPLB_MULHIT; sig = SIGSEGV; #ifdef CONFIG_DEBUG_HUNT_FOR_ZERO if (cpu_pda[cpu].dcplb_fault_addr < FIXED_CODE_START) strerror = KERN_NOTICE "NULL pointer access\n"; else #endif strerror = KERN_NOTICE EXC_0x27(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_WATCH: info.si_code = TRAP_WATCHPT; sig = SIGTRAP; pr_debug(EXC_0x28(KERN_DEBUG)); CHK_DEBUGGER_TRAP_MAYBE(); if (kernel_mode_regs(fp)) goto traps_done; else break; #ifdef CONFIG_BF535 case VEC_ISTRU_VL: info.si_code = BUS_OPFETCH; sig = SIGBUS; strerror = KERN_NOTICE "BF535: VEC_ISTRU_VL\n"; CHK_DEBUGGER_TRAP_MAYBE(); break; #else #endif case VEC_MISALI_I: info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x2A(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_CPLB_I_VL: info.si_code = ILL_CPLB_VI; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x2B(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_CPLB_I_M: info.si_code = ILL_CPLB_MISS; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x2C(KERN_NOTICE); break; case VEC_CPLB_I_MHIT: info.si_code = ILL_CPLB_MULHIT; sig = SIGSEGV; #ifdef CONFIG_DEBUG_HUNT_FOR_ZERO if (cpu_pda[cpu].icplb_fault_addr < FIXED_CODE_START) strerror = KERN_NOTICE "Jump to NULL address\n"; else #endif strerror = KERN_NOTICE EXC_0x2D(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_ILL_RES: info.si_code = ILL_PRVOPC; sig = SIGILL; strerror = KERN_NOTICE EXC_0x2E(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; case VEC_HWERR: info.si_code = BUS_ADRALN; sig = SIGBUS; switch (fp->seqstat & SEQSTAT_HWERRCAUSE) { case (SEQSTAT_HWERRCAUSE_SYSTEM_MMR): info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE HWC_x2(KERN_NOTICE); break; case (SEQSTAT_HWERRCAUSE_EXTERN_ADDR): if (ANOMALY_05000310) { static unsigned long anomaly_rets; if ((fp->pc >= (L1_CODE_START + L1_CODE_LENGTH - 512)) && (fp->pc < (L1_CODE_START + L1_CODE_LENGTH))) { anomaly_rets = fp->rets; goto traps_done; } else if (fp->rets == anomaly_rets) { goto traps_done; } else if ((fp->rets >= (L1_CODE_START + L1_CODE_LENGTH - 512)) && (fp->rets < (L1_CODE_START + L1_CODE_LENGTH))) { goto traps_done; } else anomaly_rets = 0; } info.si_code = BUS_ADRERR; sig = SIGBUS; strerror = KERN_NOTICE HWC_x3(KERN_NOTICE); break; case (SEQSTAT_HWERRCAUSE_PERF_FLOW): strerror = KERN_NOTICE HWC_x12(KERN_NOTICE); break; case (SEQSTAT_HWERRCAUSE_RAISE_5): printk(KERN_NOTICE HWC_x18(KERN_NOTICE)); break; default: printk(KERN_NOTICE HWC_default(KERN_NOTICE)); break; } CHK_DEBUGGER_TRAP_MAYBE(); break; default: info.si_code = ILL_ILLPARAOP; sig = SIGILL; verbose_printk(KERN_EMERG "Caught Unhandled Exception, code = %08lx\n", (fp->seqstat & SEQSTAT_EXCAUSE)); CHK_DEBUGGER_TRAP_MAYBE(); break; } BUG_ON(sig == 0); if (kernel_mode_regs(fp) || (current && !current->mm)) { console_verbose(); oops_in_progress = 1; } if (sig != SIGTRAP) { if (strerror) verbose_printk(strerror); dump_bfin_process(fp); dump_bfin_mem(fp); show_regs(fp); #ifndef CONFIG_DEBUG_BFIN_NO_KERN_HWTRACE if (trapnr == VEC_CPLB_I_M || trapnr == VEC_CPLB_M) verbose_printk(KERN_NOTICE "No trace since you do not have " "CONFIG_DEBUG_BFIN_NO_KERN_HWTRACE enabled\n\n"); else #endif dump_bfin_trace_buffer(); if (oops_in_progress) { verbose_printk(KERN_NOTICE "Kernel Stack\n"); show_stack(current, NULL); print_modules(); #ifndef CONFIG_ACCESS_CHECK verbose_printk(KERN_EMERG "Please turn on " "CONFIG_ACCESS_CHECK\n"); #endif panic("Kernel exception"); } else { #ifdef CONFIG_DEBUG_VERBOSE unsigned long *stack; stack = (unsigned long *)rdusp(); verbose_printk(KERN_NOTICE "Userspace Stack\n"); show_stack(NULL, stack); #endif } } #ifdef CONFIG_IPIPE if (!ipipe_trap_notify(fp->seqstat & 0x3f, fp)) #endif { info.si_signo = sig; info.si_errno = 0; switch (trapnr) { case VEC_CPLB_VL: case VEC_MISALI_D: case VEC_CPLB_M: case VEC_CPLB_MHIT: info.si_addr = (void __user *)cpu_pda[cpu].dcplb_fault_addr; break; default: info.si_addr = (void __user *)fp->pc; break; } force_sig_info(sig, &info, current); } if ((ANOMALY_05000461 && trapnr == VEC_HWERR && !access_ok(VERIFY_READ, fp->pc, 8)) || (ANOMALY_05000281 && trapnr == VEC_HWERR) || (ANOMALY_05000189 && (trapnr == VEC_CPLB_I_VL || trapnr == VEC_CPLB_VL))) fp->pc = SAFE_USER_INSTRUCTION; traps_done: trace_buffer_restore(j); }
int main(int argc, char **argv) { INSTRUCTION inst; // declare struct INSTRUCTION unsigned char *data; int i, c = 0, bytes, format = FORMAT_INTEL, mode = MODE_32, size, len; char string[256]; if (argc < 2) { printf("\nSimple x86 disassembler example\n"); printf("Compiled with libdasm %d.%d.%d.%d\n\n", LIBDASM_VERSION_MAJOR, LIBDASM_VERSION_MINOR1, LIBDASM_VERSION_MINOR2, LIBDASM_VERSION_MINOR3); printf("Usage: %s <file> [-a|-i] [bytes]\n" " file file to be disassembled (required)\n" " -a format: ATT (optional)\n" " -i format: INTEL (optional, default)\n" " bytes show raw instruction data (optional, default 8)\n\n", argv[0]); exit (1); } data = read_file(&size, argv[1]); bytes = 8; if (argc > 2) { if (argv[2][0] == '-') { switch(argv[2][1]) { case 'a': format = FORMAT_ATT; break; case 'i': format = FORMAT_INTEL; break; } if (argc > 3) { bytes = atoi(argv[3]); } } else { bytes = atoi(argv[2]); } } signal(SIGSEGV, sighandler); while (c < size) { /* * get_instruction() has the following parameters: * * - &inst is a pointer to struct INSTRUCTION * - data + c is pointer to data to be disassembled * - disassemble in 32-bit mode: MODE_32 */ len = get_instruction(&inst, data + c, mode); // Illegal opcode or opcode longer than remaining buffer if (!len || (len + c > size)) { printf("%.8x ", c); if (bytes) { printf("%.2x ", data[c]); for (i = 1; i < bytes*2 - 1; i++) { printf(" "); } } if (format == FORMAT_INTEL) { printf("db 0x%.2x\n", *(data + c)); } else { printf(".byte 0x%.2x\n", *(data + c)); } c++; continue; } /* * Print absolute offset and raw data bytes up to 'bytes' * (not needed, but looks nice). * */ printf("%.8x ", c); if (bytes) { for (i = 0; i < MIN(bytes, len); i++) { printf("%.2x", data[c + i]); } printf(" "); for (i = MIN(bytes, len); i < bytes*2 - len; i++) { printf(" "); } } /* * Print the parsed instruction, format using user-supplied * format. We could of course format the instruction in some * other way by accessing struct INSTRUCTION members directly. */ get_instruction_string(&inst, format, (DWORD)c, string, sizeof(string)); printf("%s\n", string); c += len; } return 0; }
bool process_code(vm_t * vm, bool verbose) { for (vm->regs.pc = 0; vm->regs.pc < (reg_t) vm->code_size;) { u8 opcode = vm->code[vm->regs.pc]; inst c_inst = get_instruction(opcode); bool pstat = false; switch (c_inst.name) { // op reg, reg case ADD: case SUB: case MUL: case DIV: case XOR: case MOV: { pstat = process_reg_reg(c_inst, vm, true); break; } // op reg, immb case ADDIB: case SUBIB: case MULIB: case DIVIB: case XORIB: case MOVIB: { pstat = process_reg_immb(c_inst, vm, true); break; } // op reg, immw case ADDIW: case SUBIW: case MULIW: case DIVIW: case XORIW: case MOVIW: { pstat = process_reg_immw(c_inst, vm, true); break; } // op reg, immd case ADDID: case SUBID: case MULID: case DIVID: case XORID: case MOVID: { pstat = process_reg_immd(c_inst, vm, true); break; } // op reg case INC: case DEC: { pstat = process_reg(c_inst, vm, true); break; } case PUSHB: { pstat = process_pushb(c_inst, vm, true); break; } case PUSHW: { pstat = process_pushw(c_inst, vm, true); break; } case PUSHD: { pstat = process_pushd(c_inst, vm, true); break; } case POPB: { pstat = process_popb(c_inst, vm, true); break; } case POPW: { pstat = process_popw(c_inst, vm, true); break; } case POPD: { pstat = process_popd(c_inst, vm, true); break; } case PUSHIB: { pstat = process_pushib(c_inst, vm, true); break; } case PUSHIW: { pstat = process_pushiw(c_inst, vm, true); break; } case PUSHID: { pstat = process_pushid(c_inst, vm, true); break; } case GSTK: { pstat = process_gstk(c_inst, vm, true); break; } case PSTK: { pstat = process_pstk(c_inst, vm, true); break; } case EXIT: { pstat = process_exit(c_inst, vm, true); break; } case SYSCALL: { reg_t scall = vm->regs.r1; reg_t nargs = get_syscall_nargs(scall); pstat = process_syscall(scall, nargs, c_inst, vm, true); break; } case INVALID_OPCODE: { pstat = process_invalid(c_inst, vm, true); break; } default: return false; }; if(verbose) { show_regs(vm); } // previous processed opcode failed || exit if(pstat == false) { return false; } vm->regs.pc++; } return true; }
asmlinkage notrace void trap_c(struct pt_regs *fp) { #ifdef CONFIG_DEBUG_BFIN_HWTRACE_ON int j; #endif #ifdef CONFIG_BFIN_PSEUDODBG_INSNS int opcode; #endif unsigned int cpu = raw_smp_processor_id(); const char *strerror = NULL; int sig = 0; siginfo_t info; unsigned long trapnr = fp->seqstat & SEQSTAT_EXCAUSE; trace_buffer_save(j); #if defined(CONFIG_DEBUG_MMRS) || defined(CONFIG_DEBUG_MMRS_MODULE) last_seqstat = (u32)fp->seqstat; #endif /* Important - be very careful dereferncing pointers - will lead to * double faults if the stack has become corrupt */ /* trap_c() will be called for exceptions. During exceptions * processing, the pc value should be set with retx value. * With this change we can cleanup some code in signal.c- TODO */ fp->orig_pc = fp->retx; /* printk("exception: 0x%x, ipend=%x, reti=%x, retx=%x\n", trapnr, fp->ipend, fp->pc, fp->retx); */ /* send the appropriate signal to the user program */ switch (trapnr) { /* This table works in conjunction with the one in ./mach-common/entry.S * Some exceptions are handled there (in assembly, in exception space) * Some are handled here, (in C, in interrupt space) * Some, like CPLB, are handled in both, where the normal path is * handled in assembly/exception space, and the error path is handled * here */ /* 0x00 - Linux Syscall, getting here is an error */ /* 0x01 - userspace gdb breakpoint, handled here */ case VEC_EXCPT01: info.si_code = TRAP_ILLTRAP; sig = SIGTRAP; CHK_DEBUGGER_TRAP_MAYBE(); /* Check if this is a breakpoint in kernel space */ if (kernel_mode_regs(fp)) goto traps_done; else break; /* 0x03 - User Defined, userspace stack overflow */ case VEC_EXCPT03: info.si_code = SEGV_STACKFLOW; sig = SIGSEGV; strerror = KERN_NOTICE EXC_0x03(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x02 - KGDB initial connection and break signal trap */ case VEC_EXCPT02: #ifdef CONFIG_KGDB info.si_code = TRAP_ILLTRAP; sig = SIGTRAP; CHK_DEBUGGER_TRAP(); goto traps_done; #endif /* 0x04 - User Defined */ /* 0x05 - User Defined */ /* 0x06 - User Defined */ /* 0x07 - User Defined */ /* 0x08 - User Defined */ /* 0x09 - User Defined */ /* 0x0A - User Defined */ /* 0x0B - User Defined */ /* 0x0C - User Defined */ /* 0x0D - User Defined */ /* 0x0E - User Defined */ /* 0x0F - User Defined */ /* If we got here, it is most likely that someone was trying to use a * custom exception handler, and it is not actually installed properly */ case VEC_EXCPT04 ... VEC_EXCPT15: info.si_code = ILL_ILLPARAOP; sig = SIGILL; strerror = KERN_NOTICE EXC_0x04(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x10 HW Single step, handled here */ case VEC_STEP: info.si_code = TRAP_STEP; sig = SIGTRAP; CHK_DEBUGGER_TRAP_MAYBE(); /* Check if this is a single step in kernel space */ if (kernel_mode_regs(fp)) goto traps_done; else break; /* 0x11 - Trace Buffer Full, handled here */ case VEC_OVFLOW: info.si_code = TRAP_TRACEFLOW; sig = SIGTRAP; strerror = KERN_NOTICE EXC_0x11(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x12 - Reserved, Caught by default */ /* 0x13 - Reserved, Caught by default */ /* 0x14 - Reserved, Caught by default */ /* 0x15 - Reserved, Caught by default */ /* 0x16 - Reserved, Caught by default */ /* 0x17 - Reserved, Caught by default */ /* 0x18 - Reserved, Caught by default */ /* 0x19 - Reserved, Caught by default */ /* 0x1A - Reserved, Caught by default */ /* 0x1B - Reserved, Caught by default */ /* 0x1C - Reserved, Caught by default */ /* 0x1D - Reserved, Caught by default */ /* 0x1E - Reserved, Caught by default */ /* 0x1F - Reserved, Caught by default */ /* 0x20 - Reserved, Caught by default */ /* 0x21 - Undefined Instruction, handled here */ case VEC_UNDEF_I: #ifdef CONFIG_BUG if (kernel_mode_regs(fp)) { switch (report_bug(fp->pc, fp)) { case BUG_TRAP_TYPE_NONE: break; case BUG_TRAP_TYPE_WARN: dump_bfin_trace_buffer(); fp->pc += 2; goto traps_done; case BUG_TRAP_TYPE_BUG: /* call to panic() will dump trace, and it is * off at this point, so it won't be clobbered */ panic("BUG()"); } } #endif #ifdef CONFIG_BFIN_PSEUDODBG_INSNS /* * Support for the fake instructions, if the instruction fails, * then just execute a illegal opcode failure (like normal). * Don't support these instructions inside the kernel */ if (!kernel_mode_regs(fp) && get_instruction(&opcode, (unsigned short *)fp->pc)) { if (execute_pseudodbg_assert(fp, opcode)) goto traps_done; if (execute_pseudodbg(fp, opcode)) goto traps_done; } #endif info.si_code = ILL_ILLOPC; sig = SIGILL; strerror = KERN_NOTICE EXC_0x21(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x22 - Illegal Instruction Combination, handled here */ case VEC_ILGAL_I: info.si_code = ILL_ILLPARAOP; sig = SIGILL; strerror = KERN_NOTICE EXC_0x22(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x23 - Data CPLB protection violation, handled here */ case VEC_CPLB_VL: info.si_code = ILL_CPLB_VI; sig = SIGSEGV; strerror = KERN_NOTICE EXC_0x23(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x24 - Data access misaligned, handled here */ case VEC_MISALI_D: info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x24(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x25 - Unrecoverable Event, handled here */ case VEC_UNCOV: info.si_code = ILL_ILLEXCPT; sig = SIGILL; strerror = KERN_NOTICE EXC_0x25(KERN_NOTICE); CHK_DEBUGGER_TRAP_MAYBE(); break; /* 0x26 - Data CPLB Miss, normal case is handled in _cplb_hdr, error case is handled here */ case VEC_CPLB_M: info.si_code = BUS_ADRALN; sig = SIGBUS; strerror = KERN_NOTICE EXC_0x26(KERN_NOTICE); break; /* 0x27 - Data CPLB Multiple Hits - Linux Trap Zero, handled here */ case VEC_CPLB_MHIT: info.si_code = ILL_CPLB_MULHIT; sig = SIGSEGV; #ifdef CONFIG_DEBUG_HUNT_FOR_ZERO if (