code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def recurring_tasks if supports_recurring_tasks? raise_incompatible_adapter_error_from :recurring_tasks end end
Returns an array with the list of recurring tasks. Each task is represented as a hash with these attributes: { id: "periodic-job", job_class_name: "MyJob", arguments: [ 123, { arg: :value }] schedule: "every monday at 9 am", last_enqueued_at: Fri, 26 Jan 2024 20:31:09.652174000 UTC +00:00, }
recurring_tasks
ruby
rails/mission_control-jobs
lib/mission_control/jobs/adapter.rb
https://github.com/rails/mission_control-jobs/blob/master/lib/mission_control/jobs/adapter.rb
MIT
def find_recurring_task(recurring_task_id) if supports_recurring_tasks? raise_incompatible_adapter_error_from :find_recurring_task end end
Returns a recurring task represented by a hash as indicated above
find_recurring_task
ruby
rails/mission_control-jobs
lib/mission_control/jobs/adapter.rb
https://github.com/rails/mission_control-jobs/blob/master/lib/mission_control/jobs/adapter.rb
MIT
def workers if exposes_workers? raise_incompatible_adapter_error_from :workers end end
Returns an array with the list of workers. Each worker is represented as a hash with these attributes: { id: 123, name: "worker-name", hostname: "hey-default-101", last_heartbeat_at: Fri, 26 Jan 2024 20:31:09.652174000 UTC +00:00, configuration: { ... } raw_data: { ... } }
workers
ruby
rails/mission_control-jobs
lib/mission_control/jobs/adapter.rb
https://github.com/rails/mission_control-jobs/blob/master/lib/mission_control/jobs/adapter.rb
MIT
def find_worker(worker_id) if exposes_workers? raise_incompatible_adapter_error_from :find_worker end end
Returns a worker represented by a hash as indicated above
find_worker
ruby
rails/mission_control-jobs
lib/mission_control/jobs/adapter.rb
https://github.com/rails/mission_control-jobs/blob/master/lib/mission_control/jobs/adapter.rb
MIT
def queues raise_incompatible_adapter_error_from :queue_names end
Returns an array with the list of queues. Each queue is represented as a hash with these attributes: { name: "queue_name", size: 1, active: true }
queues
ruby
rails/mission_control-jobs
lib/mission_control/jobs/adapter.rb
https://github.com/rails/mission_control-jobs/blob/master/lib/mission_control/jobs/adapter.rb
MIT
def perform_enqueued_jobs worker = Resque::Worker.new("*") worker.work(0.0) end
UI tests just use Resque for now
perform_enqueued_jobs
ruby
rails/mission_control-jobs
test/application_system_test_case.rb
https://github.com/rails/mission_control-jobs/blob/master/test/application_system_test_case.rb
MIT
def queue_adapter raise NotImplementedError end
Returns the adapter to test. Template method to override in child classes. E.g: +:resque+, +:sidekiq+
queue_adapter
ruby
rails/mission_control-jobs
test/active_job/queue_adapters/adapter_testing.rb
https://github.com/rails/mission_control-jobs/blob/master/test/active_job/queue_adapters/adapter_testing.rb
MIT
def perform_enqueued_jobs raise NotImplementedError end
Perform the jobs in the queue. Template method to override in child classes.
perform_enqueued_jobs
ruby
rails/mission_control-jobs
test/active_job/queue_adapters/adapter_testing.rb
https://github.com/rails/mission_control-jobs/blob/master/test/active_job/queue_adapters/adapter_testing.rb
MIT
def configuration if ActiveRecord::Base.configurations.respond_to?(:configs_for) ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).first else ActiveRecord::Base.configurations[Rails.env] end end
[] is deprecated and will be removed in 6.2
configuration
ruby
gocardless/statesman
lib/generators/statesman/generator_helpers.rb
https://github.com/gocardless/statesman/blob/master/lib/generators/statesman/generator_helpers.rb
MIT
def validate_not_from_terminal_state(from) unless from.nil? || successors.key?(from) raise InvalidTransitionError, "Cannot transition away from terminal state '#{from}'" end end
Check that the 'from' state is not terminal
validate_not_from_terminal_state
ruby
gocardless/statesman
lib/statesman/machine.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/machine.rb
MIT
def validate_not_to_initial_state(to) unless to.nil? || successors.values.flatten.include?(to) raise InvalidTransitionError, "Cannot transition to initial state '#{to}'" end end
Check that the 'to' state is not initial
validate_not_to_initial_state
ruby
gocardless/statesman
lib/statesman/machine.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/machine.rb
MIT
def validate_from_and_to_state(from, to) unless successors.fetch(from, []).include?(to) raise InvalidTransitionError, "Cannot transition from '#{from}' to '#{to}'" end end
Check that the transition is valid when 'from' and 'to' are given
validate_from_and_to_state
ruby
gocardless/statesman
lib/statesman/machine.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/machine.rb
MIT
def update_most_recents(most_recent_id = nil) update = build_arel_manager(::Arel::UpdateManager, transition_class) update.table(transition_table) update.where(most_recent_transitions(most_recent_id)) update.set(build_most_recents_update_all_values(most_recent_id)) # MySQL will validate index constraints across the intermediate result of an # update. This means we must order our update to deactivate the previous # most_recent before setting the new row to be true. if mysql_gaplock_protection?(transition_class.connection) update.order(transition_table[:most_recent].desc) end transition_class.connection.update(update.to_sql(transition_class)) end
Sets the given transition most_recent = t while unsetting the most_recent of any previous transitions.
update_most_recents
ruby
gocardless/statesman
lib/statesman/adapters/active_record.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/adapters/active_record.rb
MIT
def build_most_recents_update_all_values(most_recent_id = nil) [ [ transition_table[:most_recent], Arel::Nodes::SqlLiteral.new(most_recent_value(most_recent_id)), ], ].tap do |values| # Only if we support the updated at timestamps should we add this column to the # update updated_column, updated_at = updated_column_and_timestamp if updated_column values << [ transition_table[updated_column.to_sym], updated_at, ] end end end
Generates update_all Arel values that will touch the updated timestamp (if valid for this model) and set most_recent to true only for the transition with a matching most_recent ID. This is quite nasty, but combines two updates (set all most_recent = f, set current most_recent = t) into one, which helps improve transition performance especially when database latency is significant. The SQL this can help produce looks like: update transitions set most_recent = (case when id = 'PA123' then TRUE else FALSE end) , updated_at = '...' ...
build_most_recents_update_all_values
ruby
gocardless/statesman
lib/statesman/adapters/active_record.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/adapters/active_record.rb
MIT
def not_most_recent_value(db_cast: true) if transition_class.columns_hash["most_recent"].null == false return db_cast ? db_false : false end db_cast ? db_null : nil end
Check whether the `most_recent` column allows null values. If it doesn't, set old records to `false`, otherwise, set them to `NULL`. Some conditioning here is required to support databases that don't support partial indexes. By doing the conditioning on the column, rather than Rails' opinion of whether the database supports partial indexes, we're robust to DBs later adding support for partial indexes.
not_most_recent_value
ruby
gocardless/statesman
lib/statesman/adapters/active_record.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/adapters/active_record.rb
MIT
def initialize(transition_class, parent_model, observer, _opts = {}) @history = [] @transition_class = transition_class @parent_model = parent_model @observer = observer end
We only accept mode as a parameter to maintain a consistent interface with other adapters which require it.
initialize
ruby
gocardless/statesman
lib/statesman/adapters/memory.rb
https://github.com/gocardless/statesman/blob/master/lib/statesman/adapters/memory.rb
MIT
def testcase_crash( hash ) thread = ::Thread.new do finished_pass = false # if this is a new crash for this reduction, log the hash if( @crash_hashes.has_key?( hash ) ) @crash_hashes[hash] += 1 else @crash_hashes[hash] = 1 end # flag the current testcase as being able to trigger a crash (moving on to the next pass if required)... case @current_pass when 1 # Initial verification finished_pass = true when 2 # Reducing elements spawn_browser when 3 # Reducing idx's spawn_browser when 4 # Final verification finished_pass = true else finished_pass = true end if( finished_pass ) @reduction_server.stop ::Thread.current.kill end end thread.join return true end
def previous_crash( hash ) if( @crash_hashes.index( hash ) > 0 ) return @crash_hashes[ @crash_hashes.index( hash ) - 1 ] end return nil end
testcase_crash
ruby
stephenfewer/grinder
node/reduction.rb
https://github.com/stephenfewer/grinder/blob/master/node/reduction.rb
BSD-3-Clause
def testcase_generate html = '' thread = ::Thread.new do finished_pass = false case @current_pass when 1 # Initial verification finished_pass = @genopts.finished? @genopts.skip().call if not finished_pass when 2 # Reducing elements finished_pass = @elems.finished? @elems.skip if not finished_pass when 3 # Reducing idx's finished_pass = @idxs.finished? @idxs.skip if not finished_pass when 4 # Final verification # do nothing, we just want to verify the final testcase will still generate a crash else finished_pass = true end if( finished_pass ) @reduction_server.stop ::Thread.current.kill end # generate the html testcase from the log file html = @xmlcrashlog.generate_html( @opts, @elems ? @elems.skipping : [], @idxs ? @idxs.skipping : [] ) end thread.join # and serve it back out to the browser via the server return html end
generate the next testcase to try
testcase_generate
ruby
stephenfewer/grinder
node/reduction.rb
https://github.com/stephenfewer/grinder/blob/master/node/reduction.rb
BSD-3-Clause
def testcase_processed continue = true thread = ::Thread.new do kill_browser case @current_pass when 1 # Initial verification @genopts.keep when 2 # Reducing elements @elems.keep when 3 # Reducing idx's @idxs.keep when 4 # Final verification # booo, pass 4 has failed!?!. continue = false else continue = false end # while we still have testcases to generate... if( continue ) # we go again an try the next testcase in a new browser instance spawn_browser else @reduction_server.stop ::Thread.current.kill end end thread.join return continue end
return true if we are to continue generating and serving out testcases, or false if its time to finish.
testcase_processed
ruby
stephenfewer/grinder
node/reduction.rb
https://github.com/stephenfewer/grinder/blob/master/node/reduction.rb
BSD-3-Clause
def reduction( pass ) return false if pass > 4 @current_pass = pass case @current_pass when 1 p = [ ::Proc.new do @opts['print_message_comments'] = false @opts['uncomment_code_comments'] = @opts['print_code_comments'] = false end, ::Proc.new do @opts['uncomment_code_comments'] = @opts['print_code_comments'] = true end, ::Proc.new do @opts['uncomment_code_comments'] = @opts['print_code_comments'] = false line = '' @xmlcrashlog.generate_elems( @opts ).each do | elem | line << "try { tickle( #{elem} ); } catch(e){}\n" # some of these elems might not exist later on (due to @skip_elems) but we wont know yet (hence try/catch). end @opts['testcase_append_function'] = line << @opts['testcase_append_function'] end, ::Proc.new do @opts['uncomment_code_comments'] = @opts['print_code_comments'] = true # XXX: @opts['testcase_append_function'] will already include the element tickle stuff from above. #line = '' #@xmlcrashlog.generate_elems( @opts ).each do | elem | # line << "tickle( #{elem} );\n" #end #@opts['testcase_append_function'] = line << @opts['testcase_append_function'] end ] p.reverse! @genopts = SkipAndKeepItems.new( p ) print_status( "Performing pass 1: Initial verification." ) when 2 @elems = SkipAndKeepItems.new( @xmlcrashlog.generate_elems( @opts ) ) print_status( "Performing pass 2: Reducing elements (#{@elems.keeping.length} elements's)." ) when 3 @idxs = SkipAndKeepItems.new( @xmlcrashlog.generate_idxs( @opts, @elems.skipping ) ) print_status( "Performing pass 3: Reducing idx's (#{@idxs.keeping.length} idx's)." ) when 4 print_status( "Performing pass 4: Final verification." ) end if( @current_pass == 2 and @elems.keeping.length == 1 ) success = true else # spin up a server to serve out the html testcase @reduction_server = Grinder::Core::Server.new( $server_address, $server_port, @browser_type, nil, self ) @reduction_server.start # start a browser instance to visit /testcase_generate spawn_browser @reduction_server.wait kill_browser success = true end # print pass results (like above) case @current_pass when 1 success = ( not @crash_hashes.empty? ) if( success ) print_status( "Finished pass 1: Successfully performed the initial verification." ) else print_error( "Finished pass 1: Couldn't trigger a crash." ) end when 2 print_status( "Finished pass 2: Reduced elements to #{@elems.keeping.length}." ) when 3 print_status( "Finished pass 3: Reduced idx's to #{@idxs.keeping.length}." ) when 4 print_status( "Finished pass 4: Final verification." ) end return success end
pass 1: initial verification (find out if we can cause a crash, do we need to enable code comments, do we need to tickle?) pass 2: skip elements (find what elements we can skip to still cause a crash) pass 3: skip idxs (find out what idxs we can remove to still generate a crash) pass 4: final verification (finally verify the end result still generates a crash)
reduction
ruby
stephenfewer/grinder
node/reduction.rb
https://github.com/stephenfewer/grinder/blob/master/node/reduction.rb
BSD-3-Clause
def loader_javascript_chrome( pid, imagebase, chrome_dll ) print_status( "#{chrome_dll} DLL loaded into process #{pid} at address 0x#{'%08X' % imagebase }" ) if( not @attached[pid].logmessage or not @attached[pid].finishedtest ) print_error( "Unable to hook JavaScript parseFloat() in process #{pid}, grinder_logger.dll not injected." ) return false end symbol = 'v8::internal::Runtime_StringParseFloat' parsefloat = @attached[pid].name2address( imagebase, chrome_dll, symbol ) if( not parsefloat ) print_error( "Unable to resolved #{chrome_dll}!#{symbol}") return false end print_status( "Resolved #{chrome_dll}!#{symbol} @ 0x#{'%08X' % parsefloat }" ) cpu = ::Metasm::Ia32.new patch_size = 6 backup = @os_process.memory[parsefloat,patch_size] proxy_addr = ::Metasm::WinAPI.virtualallocex( @os_process.handle, 0, 1024, ::Metasm::WinAPI::MEM_COMMIT|Metasm::WinAPI::MEM_RESERVE, ::Metasm::WinAPI::PAGE_EXECUTE_READWRITE ) proxy = ::Metasm::Shellcode.assemble( cpu, %Q{ pushfd pushad mov eax,dword ptr [esp+0x08+0x24] mov eax,dword ptr [eax] lea eax, [eax+0x0B] mov ebx, [eax] lea eax, [eax+4] push eax cmp ebx, 0xDEADCAFE jne passthru1 pop eax push dword [eax] lea eax, [eax+4] push eax mov edi, 0x#{'%08X' % @attached[pid].logmessage2 } call edi pop eax jmp passthru_end passthru1: cmp ebx, 0xDEADC0DE jne passthru2 mov edi, 0x#{'%08X' % @attached[pid].logmessage } call edi jmp passthru_end passthru2: cmp ebx, 0xDEADF00D jne passthru3 mov edi, 0x#{'%08X' % @attached[pid].finishedtest } call edi jmp passthru_end passthru3: cmp ebx, 0xDEADBEEF jne passthru4 mov edi, 0x#{'%08X' % @attached[pid].startingtest } call edi passthru4: cmp ebx, 0xDEADDEAD jne passthru_end mov [ebx], ebx passthru_end: pop eax popad popfd } ).encode_string proxy << backup proxy << encode_jmp( (parsefloat+backup.length), (proxy_addr+proxy.length) ) @os_process.memory[proxy_addr, proxy.length] = proxy @os_process.memory[parsefloat,patch_size] = encode_jmp( proxy_addr, parsefloat, patch_size ) print_status( "Hooked JavaScript parseFloat() to grinder_logger.dll via proxy @ 0x#{'%08X' % proxy_addr }" ) return true end
hook chrome.dll!v8::internal::Runtime_StringParseFloat to call LOGGER_logMessage/LOGGER_finishedTest
loader_javascript_chrome
ruby
stephenfewer/grinder
node/browser/chrome.rb
https://github.com/stephenfewer/grinder/blob/master/node/browser/chrome.rb
BSD-3-Clause
def use_heaphook?( pid ) return use_logger?( pid ) end
we dont want to use grinder_heaphook.dll in the broker process...
use_heaphook?
ruby
stephenfewer/grinder
node/browser/internetexplorer.rb
https://github.com/stephenfewer/grinder/blob/master/node/browser/internetexplorer.rb
BSD-3-Clause
def use_logger?( pid ) if( ie_major_version == 8 ) return true elsif( ie_major_version >= 9 && @attached[pid].commandline =~ /SCODEF:/i ) return true end return false end
we dont want to use grinder_logger.dll in the broker process...
use_logger?
ruby
stephenfewer/grinder
node/browser/internetexplorer.rb
https://github.com/stephenfewer/grinder/blob/master/node/browser/internetexplorer.rb
BSD-3-Clause
def generate_idxs( opts={}, skip_elem=[], skip_idx=[], level=nil ) idx = [] enumerate_log( opts, skip_elem, skip_idx, level ) do | log | idx << log['idx'] if log['message'] end return idx end
returns an array of log idx's which pass any restrictions (via opts/skip_elem/skip_idx)
generate_idxs
ruby
stephenfewer/grinder
node/core/xmlcrashlog.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/xmlcrashlog.rb
BSD-3-Clause
def generate_elems( opts={}, skip_elem=[], skip_idx=[] ) elems = [] 0.upto( @log_elems ) do | i | elem = @elem_prefix + i.to_s if( skip_elem.include?( elem ) ) next end elems << elem end return elems end
returns an array of log elements which pass any restrictions (via opts/skip_elem/skip_idx)
generate_elems
ruby
stephenfewer/grinder
node/core/xmlcrashlog.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/xmlcrashlog.rb
BSD-3-Clause
def generate_html( opts={}, skip_elem=[], skip_idx=[] ) html = '' result = @log_file.scan( /([a-fA-F0-9]{8}\.[a-fA-F0-9]{8})/ ) if( not result.empty? ) title = result.first.first else title = @log_file end html << "<!doctype html>\n" html << "<html>\n" html << "\t<head>\n" html << "\t\t<meta http-equiv='Cache-Control' content='no-cache'/>\n" html << "\t" << opts['testcase_head'] << "\n" if opts['testcase_head'] html << "\t\t<title>#{title}</title>\n" html << "\t\t<style>\n" html << "\t\t\t" << opts['testcase_style'] << "\n" if opts['testcase_style'] html << "\t\t</style>\n" html << "\t\t<script type='text/javascript' src='logging.js'></script>\n" html << "\t\t<script>\n" html << "\t\t\t" << opts['testcase_script'] << "\n" if opts['testcase_script'] html << "\t\t\tfunction testcase()\n" html << "\t\t\t{\n" html << "\t\t\t" << opts['testcase_prepend_function'] << "\n" if opts['testcase_prepend_function'] html << "\n" generate_elems( opts, skip_elem, skip_idx ).each do | elem | html << "\t\t\t\tvar #{elem} = null;\n" end html << "\n" #a = [] enumerate_log( opts, skip_elem, skip_idx ) do | log | #if( not a.empty? and log['idx'] > a.last ) # html << "\t\t\t\t}\n" # a.pop #end message = log['message'] if( message ) if( opts['testcase_fixups'] ) opts['testcase_fixups'].each do | key, value | message = message.gsub( key, value ) end end if( opts['uncomment_code_comments'] and message.start_with?( '/*' ) and message.end_with?( '*/' ) ) message = message[2, message.length-4] end #if( log['parent_idx'] and not a.include?( log['parent_idx'] ) ) # # plog = find_log( log['parent_idx'] ) # if( plog['count'] > 1 and not a.include?( log['last_idx'] ) ) # html << "\t\t\t\tfor( var q=0 ; q<#{plog['count']} ; q++ ) { // #{plog['last_idx']}\n" # a.push( plog['last_idx'] ) # end #end if( log['count'] > 1 ) html << "\t\t\t\tfor( var i=0 ; i<#{log['count']} ; i++ ) {\n" end tabs = log['count'] > 1 ? "\t\t\t\t\t" : "\t\t\t\t" #message += " - #{log['parent_idx']}" if log['parent_idx'] if( opts['try_catch'] and not message.start_with?( '//' ) ) html << "#{tabs}try { #{message} } catch(e){}\n" else html << "#{tabs}#{message}\n" end if( log['count'] > 1 ) html << "\t\t\t\t}\n" end end end html << "\t\t\t" << opts['testcase_append_function'] << "\n" if opts['testcase_append_function'] html << "\t\t\t}\n" html << "\t\t</script>\n" html << "\t</head>\n" html << "\t<body onload='testcase();'>\n" html << "\t\t" << opts['testcase_body'] << "\n" if opts['testcase_body'] html << "\t</body>\n" html << "</html>\n" return html end
def find_log( idx ) @log_lines.each do | log | if( log['idx'] and log['idx'] == idx ) return log end end return nil end
generate_html
ruby
stephenfewer/grinder
node/core/xmlcrashlog.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/xmlcrashlog.rb
BSD-3-Clause
def inject_dll( library_name, pid ) # we try to pull the kernel32 base address from our shadow module list # first, this is in case we have a 64bit ruby and a 32bit target process, # in this instance LoadLibraryA would return the 64bit kernel32 address in # our ruby vm and not the 32bit wow64 kernel address we want. hkernel = get_dll_imagebase( "kernel32.dll" ) if( not hkernel ) hkernel = ::Metasm::WinAPI.loadlibrarya( "kernel32.dll" ) end return false if not hkernel loadlibrary_addr = get_dll_export( hkernel, "LoadLibraryA" ) if( not loadlibrary_addr ) loadlibrary_addr = ::Metasm::WinAPI.getprocaddress( hkernel, "LoadLibraryA" ) end return false if not loadlibrary_addr # XXX: we could use WaitForInputIdle to ensure injection is safe but it deadlocks the ruby VM #Metasm::WinAPI.waitforinputidle( @os_process.handle, 10000 ); dll_addr = ::Metasm::WinAPI.virtualallocex( @os_process.handle, 0, library_name.length, ::Metasm::WinAPI::MEM_COMMIT|Metasm::WinAPI::MEM_RESERVE, ::Metasm::WinAPI::PAGE_READWRITE ) return false if not dll_addr @os_process.memory[dll_addr, library_name.length] = library_name hinject = ::Metasm::WinAPI.createremotethread( @os_process.handle, 0, 0, loadlibrary_addr, dll_addr, 0, 0 ) return false if not hinject # XXX: again we could use this to wait for the library to be loaded and get its base address, but it deadlocks the ruby VM :/ #Metasm::WinAPI.waitforsingleobject( hinject, -1 ) return true end
inject via the standard CreateRemoteThread/LoadLibrary technique...
inject_dll
ruby
stephenfewer/grinder
node/core/debug/debugger.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debugger.rb
BSD-3-Clause
def mem_prot( address ) info = ::Metasm::WinAPI.alloc_c_struct( "MEMORY_BASIC_INFORMATION#{::Metasm::WinAPI.host_cpu.size}" ) ::Metasm::WinAPI.virtualqueryex( @os_process.handle, address, info, info.sizeof ) if( (info[:state] & ::Metasm::WinAPI::MEM_COMMIT) > 0 ) return { ::Metasm::WinAPI::PAGE_NOACCESS => '(---)', ::Metasm::WinAPI::PAGE_READONLY => '(R--)', ::Metasm::WinAPI::PAGE_READWRITE => '(RW-)', ::Metasm::WinAPI::PAGE_WRITECOPY => '(RW-)', ::Metasm::WinAPI::PAGE_EXECUTE => '(--X)', ::Metasm::WinAPI::PAGE_EXECUTE_READ => '(R-X)', ::Metasm::WinAPI::PAGE_EXECUTE_READWRITE => '(RWX)', ::Metasm::WinAPI::PAGE_EXECUTE_WRITECOPY => '(RWX)' }[ info[:protect] & 0xFF ] end ' ' end
Modified from METASM WinOS::Process.mappings (\metasm\os\windows.rb:899)
mem_prot
ruby
stephenfewer/grinder
node/core/debug/debugger.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debugger.rb
BSD-3-Clause
def get_current_fuzzer fuzzer = nil begin uri = ::URI.parse( "http://#{$server_address}:#{$server_port}/current_fuzzer" ) http = Net::HTTP.new( uri.host, uri.port ) request = Net::HTTP::Post.new( uri.request_uri ) response = http.request( request ) if( response.code.to_i == 200 ) fuzzer = response['fuzzer'] end rescue fuzzer = nil end return fuzzer end
def get_previous_crash result = '' begin uri = ::URI.parse( "http://#{$server_address}:#{$server_port}/previous_crash" ) http = Net::HTTP.new( uri.host, uri.port ) request = Net::HTTP::Post.new( uri.request_uri ) request.set_form_data( { 'hash' => "#{@hash[0]}.#{@hash[1]}" } ) response = http.request( request ) if( response.code.to_i == 200 ) result = response['hash'] end rescue result = '' end return result end
get_current_fuzzer
ruby
stephenfewer/grinder
node/core/debug/debuggerexception.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debuggerexception.rb
BSD-3-Clause
def contains?( pointer ) if( pointer >= @address and pointer < (@address + @size) ) return true end return false end
def object_type @callstack.each do | caller | result = caller.scan( /\w{1,}!([\w\:]{0,})::operator new/ ) if( not result.empty? ) return result.first.first end end return '' end
contains?
ruby
stephenfewer/grinder
node/core/debug/heaphook.rb
https://github.com/stephenfewer/grinder/blob/master/node/core/debug/heaphook.rb
BSD-3-Clause
def exception(msg='EOF unexpected') ParseError.new "near #@curexpr: #{msg}" end
allows 'raise self' (eg struct.offsetof)
exception
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def initialize(parser, exeformat=nil, source=[]) exeformat ||= ExeFormat.new @parser, @exeformat, @source = parser, exeformat, source @auto_label_list = {} @label_oldname = {} end
creates a new CCompiler from an ExeFormat and a C Parser
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def compile cf = @exeformat.unique_labels_cache.keys & @auto_label_list.keys raise "compile_c name conflict: #{cf.inspect}" if not cf.empty? @exeformat.unique_labels_cache.update @auto_label_list @parser.toplevel.precompile(self) # reorder statements (arrays of Variables) following exe section typical order funcs, rwdata, rodata, udata = [], [], [], [] @parser.toplevel.statements.each { |st| if st.kind_of? Asm @source << st.body next end raise 'non-declaration at toplevel! ' + st.inspect if not st.kind_of? Declaration v = st.var if v.type.kind_of? Function funcs << v if v.initializer # no initializer == storage :extern elsif v.storage == :extern elsif v.initializer if v.type.qualifier.to_a.include?(:const) or (v.type.kind_of? Array and v.type.type.qualifier.to_a.include?(:const)) rodata << v else rwdata << v end else udata << v end } if not funcs.empty? @exeformat.compile_setsection @source, '.text' funcs.each { |func| c_function(func) } c_program_epilog end align = 1 if not rwdata.empty? @exeformat.compile_setsection @source, '.data' rwdata.each { |data| align = c_idata(data, align) } end if not rodata.empty? @exeformat.compile_setsection @source, '.rodata' rodata.each { |data| align = c_idata(data, align) } end if not udata.empty? @exeformat.compile_setsection @source, '.bss' udata.each { |data| align = c_udata(data, align) } end # needed to allow asm parser to use our autogenerated label names @exeformat.unique_labels_cache.delete_if { |k, v| @auto_label_list[k] } @source.join("\n") end
compiles the c parser toplevel to assembler statements in self.source (::Array of ::String) starts by precompiling parser.toplevel (destructively): static symbols are converted to toplevel ones, as nested functions uses an ExeFormat (the argument) to create unique label/variable names remove typedefs/enums CExpressions: all expr types are converted to __int8/__int16/__int32/__int64 (sign kept) (incl. ptr), + void struct member dereference/array indexes are converted to *(ptr + off) coma are converted to 2 statements, ?: are converted to If :|| and :&& are converted to If + assignment to temporary immediate quotedstrings/floats are converted to references to const static toplevel postincrements are replaced by a temporary (XXX arglist) compound statements are unnested Asm are kept (TODO precompile clobber types) Declarations: initializers are converted to separate assignment CExpressions Blocks are kept unless empty structure dereferences/array indexing are converted to *(ptr + offset) While/For/DoWhile/Switch are converted to If/Goto Continue/Break are converted to Goto Cases are converted to Labels during Switch conversion Label statements are removed Return: 'return <foo>;' => 'return <foo>; goto <end_of_func>;', 'return;' => 'goto <eof>;' If: 'if (a) b; else c;' => 'if (a) goto l1; { c; }; goto l2; l1: { b; } l2:' && and || in condition are expanded to multiple If functions returning struct are precompiled (in Declaration/CExpression/Return) in a second phase, unused labels are removed from functions, as noop goto (goto x; x:) dead code is removed ('goto foo; bar; baz:' => 'goto foo; baz:') (TODO) after that, toplevel is no longer valid C (bad types, blocks moved...) then toplevel statements are sorted (.text, .data, .rodata, .bss) and compiled into asm statements in self.source returns the asm source in a single string
compile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def c_function(func) # must wait the Declaration to run the CExpr for dynamic auto offsets, # and must run those statements once only # TODO alloc a stack variable to maintain the size for each dynamic array # TODO offset of arguments # TODO nested function c_init_state(func) # hide the full @source while compiling, then add prolog/epilog (saves 1 pass) @source << '' @source << "#{@label_oldname[func.name]}:" if @label_oldname[func.name] @source << "#{func.name}:" presource, @source = @source, [] c_block(func.initializer) tmpsource, @source = @source, presource c_prolog @source.concat tmpsource c_epilog @source << '' end
compiles a C function +func+ to asm source into the array of strings +str+ in a first pass the stack variable offsets are computed, then each statement is compiled in turn
c_function
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def c_reserve_stack(block, off = 0) block.statements.each { |stmt| case stmt when Declaration next if stmt.var.type.kind_of? Function off = c_reserve_stack_var(stmt.var, off) @state.offset[stmt.var] = off when Block c_reserve_stack(stmt, off) # do not update off, not nested subblocks can overlap end } end
fills @state.offset (empty hash) automatic variable => stack offset, (recursive) offset is an ::Integer or a CExpression (dynamic array) assumes offset 0 is a ptr-size-aligned address TODO registerize automatic variables
c_reserve_stack
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def c_reserve_stack_var(var, off) if (arr_type = var.type).kind_of? Array and (arr_sz = arr_type.length).kind_of? CExpression # dynamic array ! arr_sz = CExpression.new(arr_sz, :*, sizeof(nil, arr_type.type), BaseType.new(:long, :unsigned)).precompile_inner(@parser, nil) off = CExpression.new(arr_sz, :+, off, arr_sz.type) off = CExpression.new(off, :+, 7, off.type) off = CExpression.new(off, :&, -7, off.type) CExpression.new(off, :+, 0, off.type) else al = var.type.align(@parser) sz = sizeof(var) case off when CExpression; CExpression.new(off.lexpr, :+, ((off.rexpr + sz + al - 1) / al * al), off.type) else (off + sz + al - 1) / al * al end end end
computes the new stack offset for var off is either an offset from stack start (:ptr-size-aligned) or a CExpression [[[expr, +, 7], &, -7], +, off]
c_reserve_stack_var
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def c_idata(data, align) w = data.type.align(@parser) @source << ".align #{align = w}" if w > align @source << "#{@label_oldname[data.name]}:" if @label_oldname[data.name] @source << data.name.dup len = c_idata_inner(data.type, data.initializer) len %= w len == 0 ? w : len end
compiles a C static data definition into an asm string returns the new alignment value
c_idata
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def c_idata_inner(type, value) case type when BaseType value ||= 0 if type.name == :void @source.last << ':' if not @source.last.empty? return 0 end @source.last << case type.name when :__int8; ' db ' when :__int16; ' dw ' when :__int32; ' dd ' when :__int64; ' dq ' when :ptr; " d#{%w[x b w x d x x x q][@parser.typesize[type.name]]} " when :float; ' db ' + [value].pack(@parser.endianness == :little ? 'e' : 'g').unpack('C*').join(', ') + ' // ' when :double; ' db ' + [value].pack(@parser.endianness == :little ? 'E' : 'G').unpack('C*').join(', ') + ' // ' when :longdouble; ' db ' + [value].pack(@parser.endianness == :little ? 'E' : 'G').unpack('C*').join(', ') + ' // ' # XXX same as :double else raise "unknown idata type #{type.inspect} #{value.inspect}" end @source.last << c_idata_inner_cexpr(value) @parser.typesize[type.name] when Struct value ||= [] @source.last << ':' if not @source.last.empty? # could .align here, but if there is our label name just before, it should have been .aligned too.. raise "unknown struct initializer #{value.inspect}" if not value.kind_of? ::Array sz = 0 type.members.zip(value).each { |m, v| if m.name and wsz = type.offsetof(@parser, m.name) and sz < wsz @source << "db #{wsz-sz} dup(?)" end @source << '' flen = c_idata_inner(m.type, v) sz += flen } sz when Union value ||= [] @source.last << ':' if not @source.last.empty? len = sizeof(nil, type) raise "unknown union initializer #{value.inspect}" if not value.kind_of? ::Array idx = value.rindex(value.compact.last) || 0 raise "empty union initializer" if not idx wlen = c_idata_inner(type.members[idx].type, value[idx]) @source << "db #{'0' * (len - wlen) * ', '}" if wlen < len len when Array value ||= [] if value.kind_of? CExpression and not value.op and value.rexpr.kind_of? ::String elen = sizeof(nil, value.type.type) @source.last << case elen when 1; ' db ' when 2; ' dw ' else raise 'bad char* type ' + value.inspect end << value.rexpr.inspect len = type.length || (value.rexpr.length+1) if len > value.rexpr.length @source.last << (', 0' * (len - value.rexpr.length)) end elen * len elsif value.kind_of? ::Array @source.last << ':' if not @source.last.empty? len = type.length || value.length value.each { |v| @source << '' c_idata_inner(type.type, v) } len -= value.length if len > 0 @source << " db #{len * sizeof(nil, type.type)} dup(0)" end sizeof(nil, type.type) * len else raise "unknown static array initializer #{value.inspect}" end end end
dumps an anonymous variable definition, appending to the last line of source source.last is a label name or is empty before calling here return the length of the data written
c_idata_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def check_reserved_name(var) return true if @exeformat.cpu and @exeformat.cpu.check_reserved_name(var.name) %w[db dw dd dq].include?(var.name) end
return non-nil if the variable name is unsuitable to appear as is in the asm listing eg filter out asm instruction names
check_reserved_name
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def precompile_make_block(scope) b = Block.new scope b.statements << self b end
all Statements/Declaration must define a precompile(compiler, scope) method it must append itself to scope.statements turns a statement into a new block
precompile_make_block
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def precompile(compiler, scope=nil) stmts = @statements.dup @statements.clear stmts.each { |st| compiler.curexpr = st st.precompile(compiler, self) } # cleanup declarations @symbol.delete_if { |n, s| not s.kind_of? Variable } @struct.delete_if { |n, s| not s.kind_of? Union } @symbol.each_value { |var| CExpression.precompile_type(compiler, self, var, true) } @struct.each_value { |var| next if not var.members var.members.each { |m| CExpression.precompile_type(compiler, self, m, true) } } scope.statements << self if scope and not @statements.empty? end
precompile all statements, then simplifies symbols/structs types
precompile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def precompile_optimize list = [] precompile_optimize_inner(list, 1) precompile_optimize_inner(list, 2) end
removes unused labels, and in-place goto (goto toto; toto:)
precompile_optimize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def precompile_optimize_inner(list, step) lastgoto = nil hadref = false walk = lambda { |expr| next if not expr.kind_of? CExpression # gcc's unary && support if not expr.op and not expr.lexpr and expr.rexpr.kind_of? Label list << expr.rexpr.name else walk[expr.lexpr] if expr.rexpr.kind_of? ::Array expr.rexpr.each { |r| walk[r] } else walk[expr.rexpr] end end } @statements.dup.each { |s| lastgoto = nil if not s.kind_of? Label case s when Block s.precompile_optimize_inner(list, step) @statements.delete s if step == 2 and s.statements.empty? when CExpression; walk[s] if step == 1 when Label case step when 1 if lastgoto and lastgoto.target == s.name list << lastgoto list.delete s.name if not hadref end when 2; @statements.delete s if not list.include? s.name end when Goto, If s.kind_of?(If) ? g = s.bthen : g = s case step when 1 hadref = list.include? g.target lastgoto = g list << g.target when 2 if list.include? g idx = @statements.index s @statements.delete s @statements[idx, 0] = s.test if s != g and not s.test.constant? end end end } list end
step 1: list used labels/unused goto step 2: remove unused labels
precompile_optimize_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def precompile_inner(compiler, scope, nested = true) case @op when :'.' # a.b => (&a)->b lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) ll = lexpr ll = lexpr.rexpr while ll.kind_of? CExpression and not ll.op if ll.kind_of? CExpression and ll.op == :'*' and not ll.lexpr # do not change lexpr.rexpr.type directly to a pointer, might retrigger (ptr+imm) => (ptr + imm*sizeof(*ptr)) @lexpr = CExpression.new(nil, nil, ll.rexpr, Pointer.new(lexpr.type)) else @lexpr = CExpression.new(nil, :'&', lexpr, Pointer.new(lexpr.type)) end @op = :'->' precompile_inner(compiler, scope) when :'->' # a->b => *(a + off(b)) struct = @lexpr.type.untypedef.type.untypedef lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) @lexpr = nil @op = nil if struct.kind_of? Union and (off = struct.offsetof(compiler, @rexpr)) != 0 off = CExpression.new(nil, nil, off, BaseType.new(:int, :unsigned)) @rexpr = CExpression.new(lexpr, :'+', off, lexpr.type) # ensure the (ptr + value) is not expanded to (ptr + value * sizeof(*ptr)) CExpression.precompile_type(compiler, scope, @rexpr) else # union or 1st struct member @rexpr = lexpr end if @type.kind_of? Array # Array member type is already an address else @rexpr = CExpression.new(nil, :*, @rexpr, @rexpr.type) end precompile_inner(compiler, scope) when :'[]' rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) if rexpr.kind_of? CExpression and not rexpr.op and rexpr.rexpr == 0 @rexpr = @lexpr else @rexpr = CExpression.new(@lexpr, :'+', rexpr, @lexpr.type) end @op = :'*' @lexpr = nil precompile_inner(compiler, scope) when :'?:' # cannot precompile in place, a conditionnal expression may have a coma: must turn into If if @lexpr.kind_of? CExpression @lexpr = @lexpr.precompile_inner(compiler, scope) if not @lexpr.lexpr and not @lexpr.op and @lexpr.rexpr.kind_of? ::Numeric if @lexpr.rexpr == 0 e = @rexpr[1] else e = @rexpr[0] end e = CExpression.new(nil, nil, e, e.type) if not e.kind_of? CExpression return e.precompile_inner(compiler, scope) end end raise 'conditional in toplevel' if scope == compiler.toplevel # just in case var = Variable.new var.storage = :register var.name = compiler.new_label('ternary') var.type = @rexpr[0].type CExpression.precompile_type(compiler, scope, var) Declaration.new(var).precompile(compiler, scope) If.new(@lexpr, CExpression.new(var, :'=', @rexpr[0], var.type), CExpression.new(var, :'=', @rexpr[1], var.type)).precompile(compiler, scope) @lexpr = nil @op = nil @rexpr = var precompile_inner(compiler, scope) when :'&&' if scope == compiler.toplevel @lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) CExpression.precompile_type(compiler, scope, self) self else var = Variable.new var.storage = :register var.name = compiler.new_label('and') var.type = @type CExpression.precompile_type(compiler, scope, var) var.initializer = CExpression.new(nil, nil, 0, var.type) Declaration.new(var).precompile(compiler, scope) l = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type) r = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type) If.new(l, If.new(r, CExpression.new(var, :'=', CExpression.new(nil, nil, 1, var.type), var.type))).precompile(compiler, scope) @lexpr = nil @op = nil @rexpr = var precompile_inner(compiler, scope) end when :'||' if scope == compiler.toplevel @lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) CExpression.precompile_type(compiler, scope, self) self else var = Variable.new var.storage = :register var.name = compiler.new_label('or') var.type = @type CExpression.precompile_type(compiler, scope, var) var.initializer = CExpression.new(nil, nil, 1, var.type) Declaration.new(var).precompile(compiler, scope) l = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type) l = CExpression.new(nil, :'!', l, var.type) r = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type) r = CExpression.new(nil, :'!', r, var.type) If.new(l, If.new(r, CExpression.new(var, :'=', CExpression.new(nil, nil, 0, var.type), var.type))).precompile(compiler, scope) @lexpr = nil @op = nil @rexpr = var precompile_inner(compiler, scope) end when :funcall if @lexpr.kind_of? Variable and @lexpr.type.kind_of? Function and @lexpr.attributes and @lexpr.attributes.include? 'inline' and @lexpr.initializer # TODO check recursive call (direct or indirect) raise 'inline varargs unsupported' if @lexpr.type.varargs rtype = @lexpr.type.type.untypedef if not rtype.kind_of? BaseType or rtype.name != :void rval = Variable.new rval.name = compiler.new_label('inline_return') rval.type = @lexpr.type.type Declaration.new(rval).precompile(compiler, scope) end inline_label = {} locals = @lexpr.type.args.zip(@rexpr).inject({}) { |h, (fa, a)| h.update fa => CExpression.new(nil, nil, a, fa.type).precompile_inner(compiler, scope) } copy_inline_ce = lambda { |ce| case ce when CExpression; CExpression.new(copy_inline_ce[ce.lexpr], ce.op, copy_inline_ce[ce.rexpr], ce.type) when Variable; locals[ce] || ce when ::Array; ce.map { |e_| copy_inline_ce[e_] } else ce end } copy_inline = lambda { |stmt, scp| case stmt when Block b = Block.new(scp) stmt.statements.each { |s| s = copy_inline[s, b] b.statements << s if s } b when If; If.new(copy_inline_ce[stmt.test], copy_inline[stmt.bthen, scp]) # re-precompile ? when Label; Label.new(inline_label[stmt.name] ||= compiler.new_label('inline_'+stmt.name)) when Goto; Goto.new(inline_label[stmt.target] ||= compiler.new_label('inline_'+stmt.target)) when Return; CExpression.new(rval, :'=', copy_inline_ce[stmt.value], rval.type).precompile_inner(compiler, scp) if stmt.value when CExpression; copy_inline_ce[stmt] when Declaration nv = stmt.var.dup if nv.type.kind_of? Array and nv.type.length.kind_of? CExpression nv.type = Array.new(nv.type.type, copy_inline_ce[nv.type.length]) # XXX nested dynamic? end locals[stmt.var] = nv scp.symbol[nv.name] = nv Declaration.new(nv) else raise 'unexpected inline statement ' + stmt.inspect end } scope.statements << copy_inline[@lexpr.initializer, scope] # body already precompiled CExpression.new(nil, nil, rval, rval.type).precompile_inner(compiler, scope) elsif @type.kind_of? Union var = Variable.new var.name = compiler.new_label('return_struct') var.type = @type Declaration.new(var).precompile(compiler, scope) @rexpr.unshift CExpression.new(nil, :&, var, Pointer.new(var.type)) var2 = Variable.new var2.name = compiler.new_label('return_struct_ptr') var2.type = Pointer.new(@type) var2.storage = :register CExpression.precompile_type(compiler, scope, var2) Declaration.new(var2).precompile(compiler, scope) @type = var2.type CExpression.new(var2, :'=', self, var2.type).precompile(compiler, scope) CExpression.new(nil, :'*', var2, var.type).precompile_inner(compiler, scope) else t = @lexpr.type.untypedef t = t.type.untypedef if t.pointer? @lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) types = t.args.map { |a| a.type } # cast args to func prototype @rexpr.map! { |e_| (types.empty? ? e_ : CExpression.new(nil, nil, e_, types.shift)).precompile_inner(compiler, scope) } CExpression.precompile_type(compiler, scope, self) self end when :',' lexpr = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type) rexpr = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type) lexpr.precompile(compiler, scope) rexpr.precompile_inner(compiler, scope) when :'!' CExpression.precompile_type(compiler, scope, self) if @rexpr.kind_of?(CExpression) case @rexpr.op when :'<', :'>', :'<=', :'>=', :'==', :'!=' @op = { :'<' => :'>=', :'>' => :'<=', :'<=' => :'>', :'>=' => :'<', :'==' => :'!=', :'!=' => :'==' }[@rexpr.op] @lexpr = @rexpr.lexpr @rexpr = @rexpr.rexpr precompile_inner(compiler, scope) when :'&&', :'||' @op = { :'&&' => :'||', :'||' => :'&&' }[@rexpr.op] @lexpr = CExpression.new(nil, :'!', @rexpr.lexpr, @type) @rexpr = CExpression.new(nil, :'!', @rexpr.rexpr, @type) precompile_inner(compiler, scope) when :'!' if @rexpr.rexpr.kind_of? CExpression @op = nil @rexpr = @rexpr.rexpr else @op = :'!=' @lexpr = @rexpr.rexpr @rexpr = CExpression.new(nil, nil, 0, @lexpr.type) end precompile_inner(compiler, scope) else @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) self end else @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) self end when :'++', :'--' if not @rexpr var = Variable.new var.storage = :register var.name = compiler.new_label('postincrement') var.type = @type Declaration.new(var).precompile(compiler, scope) CExpression.new(var, :'=', @lexpr, @type).precompile(compiler, scope) CExpression.new(nil, @op, @lexpr, @type).precompile(compiler, scope) @lexpr = nil @op = nil @rexpr = var precompile_inner(compiler, scope) elsif @type.pointer? and compiler.sizeof(nil, @type.untypedef.type.untypedef) != 1 # ++ptr => ptr += sizeof(*ptr) (done in += precompiler) @op = { :'++' => :'+=', :'--' => :'-=' }[@op] @lexpr = @rexpr @rexpr = CExpression.new(nil, nil, 1, BaseType.new(:ptr, :unsigned)) precompile_inner(compiler, scope) else CExpression.precompile_type(compiler, scope, self) @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) self end when :'=' # handle structure assignment/array assignment case @lexpr.type.untypedef when Union # rexpr may be a :funcall @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) @lexpr.type.untypedef.members.zip(@rexpr.type.untypedef.members) { |m1, m2| # assume m1 and m2 are compatible v1 = CExpression.new(@lexpr, :'.', m1.name, m1.type) v2 = CExpression.new(@rexpr, :'.', m2.name, m1.type) CExpression.new(v1, :'=', v2, v1.type).precompile(compiler, scope) } # (foo = bar).toto @op = nil @rexpr = @lexpr @lexpr = nil @type = @rexpr.type precompile_inner(compiler, scope) if nested when Array if not len = @lexpr.type.untypedef.length @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) # char toto[] = "bla" if @rexpr.kind_of? CExpression and not @rexpr.lexpr and not @rexpr.op and @rexpr.rexpr.kind_of? Variable and @rexpr.rexpr.type.kind_of? Array len = @rexpr.rexpr.type.length end end raise 'array initializer with no length !' if not len # TODO optimize... len.times { |i| i = CExpression.new(nil, nil, i, BaseType.new(:long, :unsigned)) v1 = CExpression.new(@lexpr, :'[]', i, @lexpr.type.untypedef.type) v2 = CExpression.new(@rexpr, :'[]', i, v1.type) CExpression.new(v1, :'=', v2, v1.type).precompile(compiler, scope) } @op = nil @rexpr = @lexpr @lexpr = nil @type = @rexpr.type precompile_inner(compiler, scope) if nested else @lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) CExpression.precompile_type(compiler, scope, self) self end when nil case @rexpr when Block # compound statements raise 'compound statement in toplevel' if scope == compiler.toplevel # just in case var = Variable.new var.storage = :register var.name = compiler.new_label('compoundstatement') var.type = @type CExpression.precompile_type(compiler, scope, var) Declaration.new(var).precompile(compiler, scope) if @rexpr.statements.last.kind_of? CExpression @rexpr.statements[-1] = CExpression.new(var, :'=', @rexpr.statements[-1], var.type) @rexpr.precompile(compiler, scope) end @rexpr = var precompile_inner(compiler, scope) when ::String # char[] immediate v = Variable.new v.storage = :static v.name = 'char_' + @rexpr.tr('^a-zA-Z', '')[0, 8] v.type = Array.new(@type.type) v.type.length = @rexpr.length + 1 v.type.type.qualifier = [:const] v.initializer = CExpression.new(nil, nil, @rexpr, @type) Declaration.new(v).precompile(compiler, scope) @rexpr = v precompile_inner(compiler, scope) when ::Float # float immediate v = Variable.new v.storage = :static v.name = @type.untypedef.name.to_s v.type = @type v.type.qualifier = [:const] v.initializer = CExpression.new(nil, nil, @rexpr, @type) Declaration.new(v).precompile(compiler, scope) @rexpr = CExpression.new(nil, :'*', v, v.type) precompile_inner(compiler, scope) when CExpression # simplify casts CExpression.precompile_type(compiler, scope, self) # propagate type first so that __uint64 foo() { return -1 } => 0xffffffffffffffff @rexpr.type = @type if @rexpr.kind_of? CExpression and @rexpr.op == :- and not @rexpr.lexpr and @type.kind_of? BaseType and @type.name == :__int64 # XXX kill me @rexpr = @rexpr.precompile_inner(compiler, scope) if @type.kind_of? BaseType and @rexpr.type.kind_of? BaseType if @rexpr.type == @type # noop cast @lexpr, @op, @rexpr = @rexpr.lexpr, @rexpr.op, @rexpr.rexpr elsif not @rexpr.op and @type.integral? and @rexpr.type.integral? if @rexpr.rexpr.kind_of? ::Numeric and (val = reduce(compiler)).kind_of? ::Numeric @rexpr = val elsif compiler.typesize[@type.name] < compiler.typesize[@rexpr.type.name] # (char)(short)(int)(long)foo => (char)foo @rexpr = @rexpr.rexpr end end end self else CExpression.precompile_type(compiler, scope, self) self end else # int+ptr => ptr+int if @op == :+ and @lexpr and @lexpr.type.integral? and @rexpr.type.pointer? @rexpr, @lexpr = @lexpr, @rexpr end # handle pointer + 2 == ((char *)pointer) + 2*sizeof(*pointer) if @rexpr and [:'+', :'+=', :'-', :'-='].include? @op and @type.pointer? and @rexpr.type.integral? sz = compiler.sizeof(nil, @type.untypedef.type.untypedef) if sz != 1 sz = CExpression.new(nil, nil, sz, @rexpr.type) @rexpr = CExpression.new(@rexpr, :'*', sz, @rexpr.type) end end # type promotion => cast case @op when :+, :-, :*, :/, :&, :|, :^, :% if @lexpr if @lexpr.type != @type @lexpr = CExpression.new(nil, nil, @lexpr, @lexpr.type) if not @lexpr.kind_of? CExpression @lexpr = CExpression.new(nil, nil, @lexpr, @type) end if @rexpr.type != @type @rexpr = CExpression.new(nil, nil, @rexpr, @rexpr.type) if not @rexpr.kind_of? CExpression @rexpr = CExpression.new(nil, nil, @rexpr, @type) end end when :>>, :<< # char => int if @lexpr.type != @type @lexpr = CExpression.new(nil, nil, @lexpr, @lexpr.type) if not @lexpr.kind_of? CExpression @lexpr = CExpression.new(nil, nil, @lexpr, @type) end when :'+=', :'-=', :'*=', :'/=', :'&=', :'|=', :'^=', :'%=' if @rexpr.type != @lexpr.type @rexpr = CExpression.new(nil, nil, @rexpr, @rexpr.type) if not @rexpr.kind_of? CExpression @rexpr = CExpression.new(nil, nil, @rexpr, @type) end end @lexpr = CExpression.precompile_inner(compiler, scope, @lexpr) @rexpr = CExpression.precompile_inner(compiler, scope, @rexpr) if @op == :'&' and not @lexpr rr = @rexpr rr = rr.rexpr while rr.kind_of? CExpression and not rr.op if rr.kind_of? CExpression and rr.op == :'*' and not rr.lexpr @lexpr = nil @op = nil @rexpr = rr.rexpr return precompile_inner(compiler, scope) elsif rr != @rexpr @rexpr = rr return precompile_inner(compiler, scope) end end CExpression.precompile_type(compiler, scope, self) isnumeric = lambda { |e_| e_.kind_of?(::Numeric) or (e_.kind_of? CExpression and not e_.lexpr and not e_.op and e_.rexpr.kind_of? ::Numeric) } # calc numeric # XXX do not simplify operations involving variables (for type overflow etc) if isnumeric[@rexpr] and (not @lexpr or isnumeric[@lexpr]) and (val = reduce(compiler)).kind_of? ::Numeric @lexpr = nil @op = nil @rexpr = val end self end end
returns a new CExpression with simplified self.type, computes structure offsets turns char[]/float immediates to reference to anonymised const TODO 'a = b += c' => 'b += c; a = b' (use nested argument) TODO handle precompile_inner return nil TODO struct.bits
precompile_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb
BSD-3-Clause
def add_bpm m = @address + @internal[:len] a = @address & -0x1000 @hash_shared = [self] @internal ||= {} @internal[:orig_prot] ||= {} while a < m if pv = @hash_owner[a] if not pv.hash_shared.include?(self) pv.hash_shared.concat @hash_shared-pv.hash_shared @hash_shared.each { |bpm| bpm.hash_shared = pv.hash_shared } end @internal[:orig_prot][a] = pv.internal[:orig_prot][a] else @hash_owner[a] = self end a += 0x1000 end end
register a bpm: add references to all page start covered in @hash_owner
add_bpm
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def del return del_bpm if @type == :bpm @hash_shared.delete self if @hash_shared.empty? @hash_owner.delete @hash_key elsif @hash_owner[@hash_key] == self @hash_owner[@hash_key] = @hash_shared.first end end
delete the breakpoint from hash_shared, and hash_owner if empty
del
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def initialize @pid_stuff = {} @tid_stuff = {} @log_proc = nil @state = :dead @info = '' # stuff saved when we switch pids @pid_stuff_list = [:memory, :cpu, :disassembler, :symbols, :symbols_len, :modulemap, :breakpoint, :breakpoint_memory, :tid, :tid_stuff, :dead_process] @tid_stuff_list = [:state, :info, :breakpoint_thread, :singlestep_cb, :run_method, :run_args, :breakpoint_cause, :dead_thread] @callback_loadlibrary = lambda { |h| loadsyms(h[:address]) ; continue } @callback_newprocess = lambda { |h| log "process #{@pid} attached" } @callback_endprocess = lambda { |h| log "process #{@pid} died" } initialize_newpid initialize_newtid end
initializes the disassembler internal data - subclasses should call super()
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def initialize_newpid return if not pid @pid_stuff_list.each { |s| instance_variable_set("@#{s}", nil) } @symbols = {} @symbols_len = {} @modulemap = {} @breakpoint = {} @breakpoint_memory = {} @tid_stuff = {} initialize_cpu initialize_memory initialize_disassembler end
creates stuff related to a new process being debugged includes disassembler, modulemap, symbols, breakpoints subclasses should check that @pid maps to a real process and raise() otherwise to be called with @pid/@tid set, calls initialize_memory+initialize_cpu
initialize_newpid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def initialize_newtid return if not tid @tid_stuff_list.each { |s| instance_variable_set("@#{s}", nil) } @state = :stopped @info = 'new' @breakpoint_thread = {} gui.swapin_tid if @disassembler and gui.respond_to?(:swapin_tid) end
subclasses should check that @tid maps to a real thread and raise() otherwise
initialize_newtid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def initialize_disassembler return if not @memory or not @cpu @disassembler = Shellcode.decode(@memory, @cpu).disassembler gui.swapin_pid if gui.respond_to?(:swapin_pid) end
initialize the disassembler from @cpu/@memory
initialize_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def swapout_pid return if not pid swapout_tid gui.swapout_pid if gui.respond_to?(:swapout_pid) @pid_stuff[@pid] ||= {} @pid_stuff_list.each { |fld| @pid_stuff[@pid][fld] = instance_variable_get("@#{fld}") } end
we're switching focus from one pid to another, save current pid data
swapout_pid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def swapout_tid return if not tid gui.swapout_tid if gui.respond_to?(:swapout_tid) @tid_stuff[@tid] ||= {} @tid_stuff_list.each { |fld| @tid_stuff[@tid][fld] = instance_variable_get("@#{fld}") } end
we're switching focus from one tid to another, save current tid data
swapout_tid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def swapin_pid return initialize_newpid if not @pid_stuff[@pid] @pid_stuff_list.each { |fld| instance_variable_set("@#{fld}", @pid_stuff[@pid][fld]) } swapin_tid gui.swapin_pid if gui.respond_to?(:swapin_pid) end
we're switching focus from one pid to another, load current pid data
swapin_pid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def swapin_tid return initialize_newtid if not @tid_stuff[@tid] @tid_stuff_list.each { |fld| instance_variable_set("@#{fld}", @tid_stuff[@tid][fld]) } gui.swapin_tid if gui.respond_to?(:swapin_tid) end
we're switching focus from one tid to another, load current tid data
swapin_tid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def del_pid @pid_stuff.delete @pid if @pid = @pid_stuff.keys.first swapin_pid else @state = :dead @info = '' @tid = nil end end
delete references to the current pid switch to another pid, set @state = :dead if none available
del_pid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def del_tid @tid_stuff.delete @tid if @tid = @tid_stuff.keys.first swapin_tid else del_tid_notid end end
delete references to the current thread
del_tid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def switch_context(npid, ntid=nil, &b) if npid.respond_to?(:pid) ntid ||= npid.tid npid = npid.pid end oldpid = pid oldtid = tid set_pid npid set_tid ntid if ntid if b # shortcut begin..ensure overhead return b.call if oldpid == pid and oldtid == tid begin b.call ensure set_pid oldpid set_tid oldtid end end end
change the debugger to a specific pid/tid if given a block, run the block and then restore the original pid/tid pid may be an object that respond to #pid/#tid
switch_context
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def each_pid(&b) # ensure @pid is last, so that we finish in the current context lst = @pid_stuff.keys - [@pid] lst << @pid return lst if not b lst.each { |p| set_pid p b.call } end
iterate over all pids, yield in the context of this pid
each_pid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def each_tid(&b) lst = @tid_stuff.keys - [@tid] lst << @tid return lst if not b lst.each { |t| set_tid t rescue next b.call } end
iterate over all tids of the current process, yield in its context
each_tid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def each_pid_tid(&b) each_pid { each_tid { b.call } } end
iterate over all tids of all pids, yield in their context
each_pid_tid
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def add_bp(addr, info={}) info[:pid] ||= @pid # dont define :tid for bpx, otherwise on del_bp we may switch_context to this thread that may not be stopped -> cant ptrace_write info[:tid] ||= @tid if info[:pid] == @pid and info[:type] == :hwbp b = Breakpoint.new info.each { |k, v| b.send("#{k}=", v) } switch_context(b) { addr = resolve_expr(addr) if not addr.kind_of? ::Integer b.address = addr b.hash_owner ||= case b.type when :bpm; @breakpoint_memory when :hwbp; @breakpoint_thread when :bpx; @breakpoint end # XXX bpm may hash_share with an :active, but be larger and still need enable() b.add enable_bp(b) if not info[:state] } b end
create a thread/process breakpoint addr can be a numeric address, an Expression that is resolved, or a String that is parsed+resolved info's keys are set to the breakpoint standard keys are :type, :oneshot, :condition, :action returns the Breakpoint object
add_bp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def del_all_breakpoints_thread @breakpoint_thread.values.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) } end
delete all breakpoints defined in the current thread
del_all_breakpoints_thread
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def del_all_breakpoints each_tid { del_all_breakpoints_thread } @breakpoint.values.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) } @breakpoint_memory.values.uniq.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) } end
delete all breakpoints for the current process and all its threads
del_all_breakpoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def init_bpx(b) # dont bother setting stuff up if it is never to be used return if b.oneshot and not b.condition # lazy setup of b.emul_instr: delay building emulating lambda to if/when actually needed # we still need to disassemble now and update @disassembler, before we patch the memory for the bpx di = init_bpx_disassemble(b.address) b.hash_shared.each { |bb| bb.emul_instr = di } end
called in the context of the target when a bpx is to be initialized may (lazily) initialize b.emul_instr for virtual singlestep
init_bpx
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def init_bpx_disassemble(addr) @disassembler.disassemble_fast_block(addr) @disassembler.di_at(addr) end
retrieve the di at a given address, disassemble if needed TODO make it so this doesn't interfere with other 'real' disassembler later commands, eg disassemble() or disassemble_fast_deep() (right now, when they see the block already present they stop all processing)
init_bpx_disassemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def has_emul_instr(bp) if bp.emul_instr.kind_of?(DecodedInstruction) if di = bp.emul_instr and fdbd = @disassembler.get_fwdemu_binding(di, register_pc) and fdbd.all? { |k, v| (k.kind_of?(Symbol) or k.kind_of?(Indirection)) and k != :incomplete_binding and v != Expression::Unknown } # setup a lambda that will mimic, using the debugger primitives, the actual execution of the instruction bp.emul_instr = lambda { fdbd.map { |k, v| k = Indirection[emulinstr_resv(k.pointer), k.len] if k.kind_of?(Indirection) [k, emulinstr_resv(v)] }.each { |k, v| if k.to_s =~ /flags?_(.+)/i f = $1.downcase.to_sym set_flag_value(f, v) elsif k.kind_of?(Symbol) set_reg_value(k, v) elsif k.kind_of?(Indirection) memory_write_int(k.pointer, v, k.len) end } } bp.hash_shared.each { |bb| bb.emul_instr = bp.emul_instr } else bp.hash_shared.each { |bb| bb.emul_instr = nil } end end bp.emul_instr end
checks if bp has an emul_instr do the lazy initialization if needed
has_emul_instr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def hwbp(addr, mtype=:x, mlen=1, oneshot=false, cond=nil, &action) h = { :type => :hwbp } h[:hash_owner] = @breakpoint_thread addr = resolve_expr(addr) if not addr.kind_of? ::Integer mtype = mtype.to_sym h[:hash_key] = [addr, mtype, mlen] h[:internal] = { :type => mtype, :len => mlen } h[:oneshot] = true if oneshot h[:condition] = cond if cond h[:action] = action if action add_bp(addr, h) end
sets a hardware breakpoint mtype in :r :w :x mlen is the size of the memory zone to cover mlen may be constrained by the architecture
hwbp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def bpm(addr, mtype=:r, mlen=4096, oneshot=false, cond=nil, &action) h = { :type => :bpm } addr = resolve_expr(addr) if not addr.kind_of? ::Integer h[:hash_key] = addr & -4096 # XXX actually referenced at addr, addr+4096, ... addr+len h[:internal] = { :type => mtype, :len => mlen } h[:oneshot] = true if oneshot h[:condition] = cond if cond h[:action] = action if action add_bp(addr, h) end
sets a memory breakpoint mtype is :r :w :rw or :x mlen is the size of the memory zone to cover
bpm
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def set_log_proc(l=nil, &b) @log_proc = l || b end
define the lambda to use to log stuff
set_log_proc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def log(*a) if @log_proc a.each { |aa| @log_proc[aa] } else puts(*a) if $VERBOSE end end
show information to the user, uses log_proc if defined
log
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def invalidate @memory.invalidate if @memory end
marks the current cache of memory/regs invalid
invalidate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def dasm_invalidate disassembler.sections.each_value { |s| s.data.invalidate if s.data.respond_to?(:invalidate) } if disassembler end
invalidates the EncodedData backend for the dasm sections
dasm_invalidate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def all_breakpoints(addr=nil) ret = [] if addr if b = @breakpoint[addr] ret |= b.hash_shared end else @breakpoint.each_value { |bb| ret |= bb.hash_shared } end @breakpoint_thread.each_value { |bb| next if addr and bb.address != addr ret |= bb.hash_shared } @breakpoint_memory.each_value { |bb| next if addr and (bb.address+bb.internal[:len] <= addr or bb.address > addr) ret |= bb.hash_shared } ret end
return all breakpoints set on a specific address (or all bp)
all_breakpoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def find_breakpoint(addr=nil, &b) return @breakpoint[addr] if @breakpoint[addr] and (not b or b.call(@breakpoint[addr])) all_breakpoints(addr).find { |bp| b.call bp } end
return on of the breakpoints at address addr
find_breakpoint
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def check_pre_run(run_m, *run_a) if @dead_process del_pid return elsif @dead_thread del_tid return elsif @state == :running return end @cpu.dbg_check_pre_run(self) if @cpu.respond_to?(:dbg_check_pre_run) @breakpoint_cause = nil @run_method = run_m @run_args = run_a @info = nil true end
to be called right before resuming execution of the target run_m is the method that should be called if the execution is stopped due to a side-effect of the debugger (bpx with wrong condition etc) returns nil if the execution should be avoided (just deleted the dead thread/process)
check_pre_run
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_singlestep(b=nil) b ||= find_singlestep return evt_exception(:type => 'singlestep') if not b @state = :stopped @info = 'singlestep' @cpu.dbg_evt_singlestep(self) if @cpu.respond_to?(:dbg_evt_singlestep) callback_singlestep[] if callback_singlestep if cb = @singlestep_cb @singlestep_cb = nil cb.call # call last, as the cb may change singlestep_cb/state/etc end end
called when the target stops due to a singlestep exception
evt_singlestep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def find_singlestep return @cpu.dbg_find_singlestep(self) if @cpu.respond_to?(:dbg_find_singlestep) @run_method == :singlestep end
returns true if the singlestep is due to us
find_singlestep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_bpx(b=nil) b ||= find_bp_bpx # TODO handle race: # bpx foo ; thread hits foo ; we bc foo ; os notify us of bp hit but we already cleared everything related to 'bpx foo' -> unhandled bp exception return evt_exception(:type => 'breakpoint') if not b @state = :stopped @info = 'breakpoint' @cpu.dbg_evt_bpx(self, b) if @cpu.respond_to?(:dbg_evt_bpx) callback_bpx[b] if callback_bpx post_evt_bp(b) end
called when the target stops due to a soft breakpoint exception
evt_bpx
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def find_bp_bpx return @cpu.dbg_find_bpx(self) if @cpu.respond_to?(:dbg_find_bpx) @breakpoint[pc] end
return the breakpoint that is responsible for the evt_bpx
find_bp_bpx
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_hwbp(b=nil) b ||= find_bp_hwbp return evt_exception(:type => 'hwbp') if not b @state = :stopped @info = 'hwbp' @cpu.dbg_evt_hwbp(self, b) if @cpu.respond_to?(:dbg_evt_hwbp) callback_hwbp[b] if callback_hwbp post_evt_bp(b) end
called when the target stops due to a hwbp exception
evt_hwbp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def find_bp_hwbp return @cpu.dbg_find_hwbp(self) if @cpu.respond_to?(:dbg_find_hwbp) @breakpoint_thread.find { |b| b.address == pc } end
return the breakpoint that is responsible for the evt_hwbp
find_bp_hwbp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_hwbp_singlestep if b = find_bp_hwbp evt_hwbp(b) else evt_singlestep end end
called for archs where the same interrupt is generated for hwbp and singlestep checks if a hwbp matches, then call evt_hwbp, else call evt_singlestep (which will forward to evt_exception if singlestep does not match either)
evt_hwbp_singlestep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_bpm(b) @state = :stopped @info = 'bpm' callback_bpm[b] if callback_bpm post_evt_bp(b) end
called when the target stops due to a memory exception caused by a memory bp called by evt_exception
evt_bpm
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def find_bp_bpm(info) @breakpoint_memory[info[:fault_addr] & -0x1000] end
return a bpm whose page coverage includes the fault described in info
find_bp_bpm
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def check_bpm_range(b, info) return if b.address+b.internal[:len] <= info[:fault_addr] return if b.address >= info[:fault_addr] + info[:fault_len] case b.internal[:type] when :r; info[:fault_access] == :r # or info[:fault_access] == :x when :w; info[:fault_access] == :w when :x; info[:fault_access] == :x # XXX non-NX cpu => check pc is in bpm range ? when :rw; true end end
returns true if the fault described in info is valid to trigger b
check_bpm_range
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def evt_exception(info={}) if info[:type] == 'access violation' and b = find_bp_bpm(info) info[:fault_len] ||= 1 b.internal.update info return evt_bpm(b) end @state = :stopped @info = "exception #{info[:type]}" callback_exception[info] if callback_exception pass = pass_all_exceptions pass = pass[info] if pass.kind_of? Proc if pass pass_current_exception resume_badbreak end end
called whenever the target stops due to an exception type may be: * 'access violation', :fault_addr, :fault_len, :fault_access (:r/:w/:x) anything else for other exceptions (access violation is special to handle bpm) ...
evt_exception
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def resume_badbreak(b=nil) # ensure we didn't delete b if b and b.hash_shared.find { |bb| bb.state == :active } rm = @run_method if rm == :singlestep singlestep_bp(b) else ra = @run_args singlestep_bp(b) { send rm, *ra } end else send @run_method, *@run_args end end
called when we did break due to a breakpoint whose condition is invalid resume execution as if we never stopped disable offending bp + singlestep if needed
resume_badbreak
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def singlestep_bp(bp, &b) if has_emul_instr(bp) @state = :stopped bp.emul_instr.call b.call if b else bp.hash_shared.each { |bb| disable_bp(bb, :temp_inactive) if bb.state == :active } # this *should* work with different bps stopping the current instr prev_sscb = @singlestep_cb singlestep { bp.hash_shared.each { |bb| enable_bp(bb) if bb.state == :temp_inactive } prev_sscb[] if prev_sscb b.call if b } end end
singlesteps over an active breakpoint and run its block if the breakpoint provides an emulation stub, run that, otherwise disable the breakpoint, singlestep, and re-enable
singlestep_bp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def check_breakpoint_cause if bp = @breakpoint_cause and (bp.type == :bpx or (bp.type == :hwbp and bp.internal[:type] == :x)) and pc != bp.address bp = @breakpoint_cause = nil end bp end
checks if @breakpoint_cause is valid, or was obsoleted by the user changing pc
check_breakpoint_cause
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def wait_target do_wait_target while @state == :running end
waits until the running target stops (due to a breakpoint, fault, etc)
wait_target
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def continue if b = check_breakpoint_cause and b.hash_shared.find { |bb| bb.state == :active } singlestep_bp(b) { next if not check_pre_run(:continue) do_continue } else return if not check_pre_run(:continue) do_continue end end
resume execution of the target bypasses a software breakpoint on pc if needed thread breakpoints must be manually disabled before calling continue
continue
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def singlestep(&b) @singlestep_cb = b bp = check_breakpoint_cause return if not check_pre_run(:singlestep) if bp and bp.hash_shared.find { |bb| bb.state == :active } and has_emul_instr(bp) @state = :stopped bp.emul_instr.call invalidate evt_singlestep(true) else do_singlestep end end
resume execution of the target one instruction at a time
singlestep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def need_stepover(di = di_at(pc)) di and @cpu.dbg_need_stepover(self, di.address, di) end
tests if the specified instructions should be stepover() using singlestep or by putting a breakpoint at next_addr
need_stepover
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def stepover di = di_at(pc) if need_stepover(di) bpx di.next_addr, true, Expression[:tid, :==, @tid] continue else singlestep end end
stepover: singlesteps, but do not enter in subfunctions
stepover
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def end_stepout(di = di_at(pc)) di and @cpu.dbg_end_stepout(self, di.address, di) end
checks if an instruction should stop the stepout() (eg it is a return instruction)
end_stepout
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def stepout # TODO thread-local bps while not end_stepout stepover wait_target end do_singlestep end
stepover until finding the last instruction of the function
stepout
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def go(target, cond=nil) bpx(target, true, cond) continue_wait end
set a singleshot breakpoint, run the process, and wait
go
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def di_at(addr) @disassembler.di_at(addr) || @disassembler.disassemble_instruction(addr) end
decode the Instruction at the address, use the @disassembler cache if available
di_at
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def get_flag(f) get_flag_value(f) != 0 end
retrieve the value of a flag (true/false)
get_flag
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def toggle_flag(f) set_flag_value(f, 1-get_flag_value(f)) end
switch the value of a flag (true->false, false->true)
toggle_flag
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause