{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \\n\"\n\t\thtml << \"\\n\"\n\t\t\n\t\treturn html\n\tend"},"docstring":{"kind":"string","value":"def find_log( idx )\n@log_lines.each do | log |\nif( log['idx'] and log['idx'] == idx )\nreturn log\nend\nend\nreturn nil\nend"},"func_name":{"kind":"string","value":"generate_html"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/core/xmlcrashlog.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/core/xmlcrashlog.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":426,"cells":{"code":{"kind":"string","value":"def inject_dll( library_name, pid )\n\t\t\t\t\t\n\t\t\t\t\t# we try to pull the kernel32 base address from our shadow module list\n\t\t\t\t\t# first, this is in case we have a 64bit ruby and a 32bit target process, \n\t\t\t\t\t# in this instance LoadLibraryA would return the 64bit kernel32 address in \n\t\t\t\t\t# our ruby vm and not the 32bit wow64 kernel address we want.\n\t\t\t\t\t\n\t\t\t\t\thkernel = get_dll_imagebase( \"kernel32.dll\" )\n\t\t\t\t\tif( not hkernel )\n\t\t\t\t\t\thkernel = ::Metasm::WinAPI.loadlibrarya( \"kernel32.dll\" )\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\treturn false if not hkernel\n\t\t\t\t\t\n\t\t\t\t\tloadlibrary_addr = get_dll_export( hkernel, \"LoadLibraryA\" )\n\t\t\t\t\tif( not loadlibrary_addr )\t\n\t\t\t\t\t\tloadlibrary_addr = ::Metasm::WinAPI.getprocaddress( hkernel, \"LoadLibraryA\" )\t\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\treturn false if not loadlibrary_addr\n\t\t\t\t\t\n\t\t\t\t\t# XXX: we could use WaitForInputIdle to ensure injection is safe but it deadlocks the ruby VM\n\t\t\t\t\t#Metasm::WinAPI.waitforinputidle( @os_process.handle, 10000 );\t\n\t\t\t\t\t\n\t\t\t\t\tdll_addr = ::Metasm::WinAPI.virtualallocex( @os_process.handle, 0, library_name.length, ::Metasm::WinAPI::MEM_COMMIT|Metasm::WinAPI::MEM_RESERVE, ::Metasm::WinAPI::PAGE_READWRITE )\n\t\t\t\t\t\n\t\t\t\t\treturn false if not dll_addr\n\t\t\t\t\t\n\t\t\t\t\t@os_process.memory[dll_addr, library_name.length] = library_name\n\t\t\t\t\t\n\t\t\t\t\thinject = ::Metasm::WinAPI.createremotethread( @os_process.handle, 0, 0, loadlibrary_addr, dll_addr, 0, 0 )\n\t\t\t\t\t\n\t\t\t\t\treturn false if not hinject\n\t\t\t\t\t\n\t\t\t\t\t# 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 :/\n\t\t\t\t\t#Metasm::WinAPI.waitforsingleobject( hinject, -1 )\t\n\n\t\t\t\t\treturn true\n\t\t\t\tend"},"docstring":{"kind":"string","value":"inject via the standard CreateRemoteThread/LoadLibrary technique..."},"func_name":{"kind":"string","value":"inject_dll"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/core/debug/debugger.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debugger.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":427,"cells":{"code":{"kind":"string","value":"def mem_prot( address )\n\t\t\t\t\t\n\t\t\t\t\tinfo = ::Metasm::WinAPI.alloc_c_struct( \"MEMORY_BASIC_INFORMATION#{::Metasm::WinAPI.host_cpu.size}\" )\n\t\t\t\t\t\n\t\t\t\t\t::Metasm::WinAPI.virtualqueryex( @os_process.handle, address, info, info.sizeof )\n\t\t\t\t\t\n\t\t\t\t\tif( (info[:state] & ::Metasm::WinAPI::MEM_COMMIT) > 0 )\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_NOACCESS => '(---)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_READONLY => '(R--)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_READWRITE => '(RW-)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_WRITECOPY => '(RW-)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_EXECUTE => '(--X)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_EXECUTE_READ => '(R-X)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_EXECUTE_READWRITE => '(RWX)',\n\t\t\t\t\t\t\t::Metasm::WinAPI::PAGE_EXECUTE_WRITECOPY => '(RWX)'\n\t\t\t\t\t\t}[ info[:protect] & 0xFF ]\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\t' '\n\t\t\t\tend"},"docstring":{"kind":"string","value":"Modified from METASM WinOS::Process.mappings (\\metasm\\os\\windows.rb:899)"},"func_name":{"kind":"string","value":"mem_prot"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/core/debug/debugger.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debugger.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":428,"cells":{"code":{"kind":"string","value":"def get_current_fuzzer\n\t\t\t\t\tfuzzer = nil\n\t\t\t\t\tbegin\n\t\t\t\t\t\turi = ::URI.parse( \"http://#{$server_address}:#{$server_port}/current_fuzzer\" )\n\t\t\t\t\t\thttp = Net::HTTP.new( uri.host, uri.port )\n\t\t\t\t\t\trequest = Net::HTTP::Post.new( uri.request_uri )\n\t\t\t\t\t\t\n\t\t\t\t\t\tresponse = http.request( request )\n\n\t\t\t\t\t\tif( response.code.to_i == 200 )\n\t\t\t\t\t\t\tfuzzer = response['fuzzer']\n\t\t\t\t\t\tend\n\t\t\t\t\trescue\n\t\t\t\t\t\tfuzzer = nil\n\t\t\t\t\tend\n\t\t\t\t\treturn fuzzer\n\t\t\t\tend"},"docstring":{"kind":"string","value":"def get_previous_crash\nresult = ''\nbegin\nuri = ::URI.parse( \"http://#{$server_address}:#{$server_port}/previous_crash\" )\nhttp = Net::HTTP.new( uri.host, uri.port )\nrequest = Net::HTTP::Post.new( uri.request_uri )\n\nrequest.set_form_data( { 'hash' => \"#{@hash[0]}.#{@hash[1]}\" } )\n\nresponse = http.request( request )\n\nif( response.code.to_i == 200 )\nresult = response['hash']\nend\nrescue\nresult = ''\nend\nreturn result\nend"},"func_name":{"kind":"string","value":"get_current_fuzzer"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/core/debug/debuggerexception.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/core/debug/debuggerexception.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":429,"cells":{"code":{"kind":"string","value":"def contains?( pointer )\n\t\t\t\t\t\tif( pointer >= @address and pointer < (@address + @size) )\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\tend\n\t\t\t\t\t\treturn false\n\t\t\t\t\tend"},"docstring":{"kind":"string","value":"def object_type\n@callstack.each do | caller |\nresult = caller.scan( /\\w{1,}!([\\w\\:]{0,})::operator new/ )\nif( not result.empty? )\nreturn result.first.first\nend\nend\nreturn ''\nend"},"func_name":{"kind":"string","value":"contains?"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/core/debug/heaphook.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/core/debug/heaphook.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":430,"cells":{"code":{"kind":"string","value":"def exception(msg='EOF unexpected')\n\t\t\tParseError.new \"near #@curexpr: #{msg}\"\n\t\tend"},"docstring":{"kind":"string","value":"allows 'raise self' (eg struct.offsetof)"},"func_name":{"kind":"string","value":"exception"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":431,"cells":{"code":{"kind":"string","value":"def initialize(parser, exeformat=nil, source=[])\n\t\t\texeformat ||= ExeFormat.new\n\t\t\t@parser, @exeformat, @source = parser, exeformat, source\n\t\t\t@auto_label_list = {}\n\t\t\t@label_oldname = {}\n\t\tend"},"docstring":{"kind":"string","value":"creates a new CCompiler from an ExeFormat and a C Parser"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":432,"cells":{"code":{"kind":"string","value":"def compile\n\t\t\tcf = @exeformat.unique_labels_cache.keys & @auto_label_list.keys\n\t\t\traise \"compile_c name conflict: #{cf.inspect}\" if not cf.empty?\n\t\t\t@exeformat.unique_labels_cache.update @auto_label_list\n\n\t\t\t@parser.toplevel.precompile(self)\n\n\t\t\t# reorder statements (arrays of Variables) following exe section typical order\n\t\t\tfuncs, rwdata, rodata, udata = [], [], [], []\n\t\t\t@parser.toplevel.statements.each { |st|\n\t\t\t\tif st.kind_of? Asm\n\t\t\t\t\t@source << st.body\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\traise 'non-declaration at toplevel! ' + st.inspect if not st.kind_of? Declaration\n\t\t\t\tv = st.var\n\t\t\t\tif v.type.kind_of? Function\n\t\t\t\t\tfuncs << v if v.initializer\t# no initializer == storage :extern\n\t\t\t\telsif v.storage == :extern\n\t\t\t\telsif v.initializer\n\t\t\t\t\tif v.type.qualifier.to_a.include?(:const) or\n\t\t\t\t\t(v.type.kind_of? Array and v.type.type.qualifier.to_a.include?(:const))\n\t\t\t\t\t\trodata << v\n\t\t\t\t\telse\n\t\t\t\t\t\trwdata << v\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tudata << v\n\t\t\t\tend\n\t\t\t}\n\n\t\t\tif not funcs.empty?\n\t\t\t\t@exeformat.compile_setsection @source, '.text'\n\t\t\t\tfuncs.each { |func| c_function(func) }\n\t\t\t\tc_program_epilog\n\t\t\tend\n\n\t\t\talign = 1\n\t\t\tif not rwdata.empty?\n\t\t\t\t@exeformat.compile_setsection @source, '.data'\n\t\t\t\trwdata.each { |data| align = c_idata(data, align) }\n\t\t\tend\n\n\t\t\tif not rodata.empty?\n\t\t\t\t@exeformat.compile_setsection @source, '.rodata'\n\t\t\t\trodata.each { |data| align = c_idata(data, align) }\n\t\t\tend\n\n\t\t\tif not udata.empty?\n\t\t\t\t@exeformat.compile_setsection @source, '.bss'\n\t\t\t\tudata.each { |data| align = c_udata(data, align) }\n\t\t\tend\n\n\t\t\t# needed to allow asm parser to use our autogenerated label names\n\t\t\t@exeformat.unique_labels_cache.delete_if { |k, v| @auto_label_list[k] }\n\n\t\t\t@source.join(\"\\n\")\n\t\tend"},"docstring":{"kind":"string","value":"compiles the c parser toplevel to assembler statements in self.source (::Array of ::String)\n\nstarts by precompiling parser.toplevel (destructively):\nstatic symbols are converted to toplevel ones, as nested functions\nuses an ExeFormat (the argument) to create unique label/variable names\n\nremove typedefs/enums\nCExpressions: all expr types are converted to __int8/__int16/__int32/__int64 (sign kept) (incl. ptr), + void\nstruct member dereference/array indexes are converted to *(ptr + off)\ncoma are converted to 2 statements, ?: are converted to If\n:|| and :&& are converted to If + assignment to temporary\nimmediate quotedstrings/floats are converted to references to const static toplevel\npostincrements are replaced by a temporary (XXX arglist)\ncompound statements are unnested\nAsm are kept (TODO precompile clobber types)\nDeclarations: initializers are converted to separate assignment CExpressions\nBlocks are kept unless empty\nstructure dereferences/array indexing are converted to *(ptr + offset)\nWhile/For/DoWhile/Switch are converted to If/Goto\nContinue/Break are converted to Goto\nCases are converted to Labels during Switch conversion\nLabel statements are removed\nReturn: 'return ;' => 'return ; goto ;', 'return;' => 'goto ;'\nIf: 'if (a) b; else c;' => 'if (a) goto l1; { c; }; goto l2; l1: { b; } l2:'\n&& and || in condition are expanded to multiple If\nfunctions returning struct are precompiled (in Declaration/CExpression/Return)\n\nin a second phase, unused labels are removed from functions, as noop goto (goto x; x:)\ndead code is removed ('goto foo; bar; baz:' => 'goto foo; baz:') (TODO)\n\nafter that, toplevel is no longer valid C (bad types, blocks moved...)\n\nthen toplevel statements are sorted (.text, .data, .rodata, .bss) and compiled into asm statements in self.source\n\nreturns the asm source in a single string"},"func_name":{"kind":"string","value":"compile"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":433,"cells":{"code":{"kind":"string","value":"def c_function(func)\n\t\t\t# must wait the Declaration to run the CExpr for dynamic auto offsets,\n\t\t\t# and must run those statements once only\n\t\t\t# TODO alloc a stack variable to maintain the size for each dynamic array\n\t\t\t# TODO offset of arguments\n\t\t\t# TODO nested function\n\t\t\tc_init_state(func)\n\n\t\t\t# hide the full @source while compiling, then add prolog/epilog (saves 1 pass)\n\t\t\t@source << ''\n\t\t\t@source << \"#{@label_oldname[func.name]}:\" if @label_oldname[func.name]\n\t\t\t@source << \"#{func.name}:\"\n\t\t\tpresource, @source = @source, []\n\n\t\t\tc_block(func.initializer)\n\n\t\t\ttmpsource, @source = @source, presource\n\t\t\tc_prolog\n\t\t\t@source.concat tmpsource\n\t\t\tc_epilog\n\t\t\t@source << ''\n\t\tend"},"docstring":{"kind":"string","value":"compiles a C function +func+ to asm source into the array of strings +str+\nin a first pass the stack variable offsets are computed,\nthen each statement is compiled in turn"},"func_name":{"kind":"string","value":"c_function"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":434,"cells":{"code":{"kind":"string","value":"def c_reserve_stack(block, off = 0)\n\t\t\tblock.statements.each { |stmt|\n\t\t\t\tcase stmt\n\t\t\t\twhen Declaration\n\t\t\t\t\tnext if stmt.var.type.kind_of? Function\n\t\t\t\t\toff = c_reserve_stack_var(stmt.var, off)\n\t\t\t\t\t@state.offset[stmt.var] = off\n\t\t\t\twhen Block\n\t\t\t\t\tc_reserve_stack(stmt, off)\n\t\t\t\t\t# do not update off, not nested subblocks can overlap\n\t\t\t\tend\n\t\t\t}\n\t\tend"},"docstring":{"kind":"string","value":"fills @state.offset (empty hash)\nautomatic variable => stack offset, (recursive)\noffset is an ::Integer or a CExpression (dynamic array)\nassumes offset 0 is a ptr-size-aligned address\nTODO registerize automatic variables"},"func_name":{"kind":"string","value":"c_reserve_stack"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":435,"cells":{"code":{"kind":"string","value":"def c_reserve_stack_var(var, off)\n\t\t\tif (arr_type = var.type).kind_of? Array and (arr_sz = arr_type.length).kind_of? CExpression\n\t\t\t\t# dynamic array !\n\t\t\t\tarr_sz = CExpression.new(arr_sz, :*, sizeof(nil, arr_type.type),\n\t\t\t\t\t BaseType.new(:long, :unsigned)).precompile_inner(@parser, nil)\n\t\t\t\toff = CExpression.new(arr_sz, :+, off, arr_sz.type)\n\t\t\t\toff = CExpression.new(off, :+, 7, off.type)\n\t\t\t\toff = CExpression.new(off, :&, -7, off.type)\n\t\t\t\tCExpression.new(off, :+, 0, off.type)\n\t\t\telse\n\t\t\t\tal = var.type.align(@parser)\n\t\t\t\tsz = sizeof(var)\n\t\t\t\tcase off\n\t\t\t\twhen CExpression; CExpression.new(off.lexpr, :+, ((off.rexpr + sz + al - 1) / al * al), off.type)\n\t\t\t\telse (off + sz + al - 1) / al * al\n\t\t\t\tend\n\t\t\tend\n\t\tend"},"docstring":{"kind":"string","value":"computes the new stack offset for var\noff is either an offset from stack start (:ptr-size-aligned) or\na CExpression [[[expr, +, 7], &, -7], +, off]"},"func_name":{"kind":"string","value":"c_reserve_stack_var"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":436,"cells":{"code":{"kind":"string","value":"def c_idata(data, align)\n\t\t\tw = data.type.align(@parser)\n\t\t\t@source << \".align #{align = w}\" if w > align\n\n\t\t\t@source << \"#{@label_oldname[data.name]}:\" if @label_oldname[data.name]\n\t\t\t@source << data.name.dup\n\t\t\tlen = c_idata_inner(data.type, data.initializer)\n\t\t\tlen %= w\n\t\t\tlen == 0 ? w : len\n\t\tend"},"docstring":{"kind":"string","value":"compiles a C static data definition into an asm string\nreturns the new alignment value"},"func_name":{"kind":"string","value":"c_idata"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":437,"cells":{"code":{"kind":"string","value":"def c_idata_inner(type, value)\n\t\t\tcase type\n\t\t\twhen BaseType\n\t\t\t\tvalue ||= 0\n\n\t\t\t\tif type.name == :void\n\t\t\t\t\t@source.last << ':' if not @source.last.empty?\n\t\t\t\t\treturn 0\n\t\t\t\tend\n\n\t\t\t\t@source.last <<\n\t\t\t\tcase type.name\n\t\t\t\twhen :__int8; ' db '\n\t\t\t\twhen :__int16; ' dw '\n\t\t\t\twhen :__int32; ' dd '\n\t\t\t\twhen :__int64; ' dq '\n\t\t\t\twhen :ptr; \" d#{%w[x b w x d x x x q][@parser.typesize[type.name]]} \"\n\t\t\t\twhen :float; ' db ' + [value].pack(@parser.endianness == :little ? 'e' : 'g').unpack('C*').join(', ') + ' // '\n\t\t\t\twhen :double; ' db ' + [value].pack(@parser.endianness == :little ? 'E' : 'G').unpack('C*').join(', ') + ' // '\n\t\t\t\twhen :longdouble; ' db ' + [value].pack(@parser.endianness == :little ? 'E' : 'G').unpack('C*').join(', ') + ' // '\t# XXX same as :double\n\t\t\t\telse raise \"unknown idata type #{type.inspect} #{value.inspect}\"\n\t\t\t\tend\n\n\t\t\t\t@source.last << c_idata_inner_cexpr(value)\n\n\t\t\t\t@parser.typesize[type.name]\n\n\t\t\twhen Struct\n\t\t\t\tvalue ||= []\n\t\t\t\t@source.last << ':' if not @source.last.empty?\n\t\t\t\t# could .align here, but if there is our label name just before, it should have been .aligned too..\n\t\t\t\traise \"unknown struct initializer #{value.inspect}\" if not value.kind_of? ::Array\n\t\t\t\tsz = 0\n\t\t\t\ttype.members.zip(value).each { |m, v|\n\t\t\t\t\tif m.name and wsz = type.offsetof(@parser, m.name) and sz < wsz\n\t\t\t\t\t\t@source << \"db #{wsz-sz} dup(?)\"\n\t\t\t\t\tend\n\t\t\t\t\t@source << ''\n\t\t\t\t\tflen = c_idata_inner(m.type, v)\n\t\t\t\t\tsz += flen\n\t\t\t\t}\n\n\t\t\t\tsz\n\n\t\t\twhen Union\n\t\t\t\tvalue ||= []\n\t\t\t\t@source.last << ':' if not @source.last.empty?\n\t\t\t\tlen = sizeof(nil, type)\n\t\t\t\traise \"unknown union initializer #{value.inspect}\" if not value.kind_of? ::Array\n\t\t\t\tidx = value.rindex(value.compact.last) || 0\n\t\t\t\traise \"empty union initializer\" if not idx\n\t\t\t\twlen = c_idata_inner(type.members[idx].type, value[idx])\n\t\t\t\t@source << \"db #{'0' * (len - wlen) * ', '}\" if wlen < len\n\n\t\t\t\tlen\n\n\t\t\twhen Array\n\t\t\t\tvalue ||= []\n\t\t\t\tif value.kind_of? CExpression and not value.op and value.rexpr.kind_of? ::String\n\t\t\t\t\telen = sizeof(nil, value.type.type)\n\t\t\t\t\t@source.last <<\n\t\t\t\t\tcase elen\n\t\t\t\t\twhen 1; ' db '\n\t\t\t\t\twhen 2; ' dw '\n\t\t\t\t\telse raise 'bad char* type ' + value.inspect\n\t\t\t\t\tend << value.rexpr.inspect\n\n\t\t\t\t\tlen = type.length || (value.rexpr.length+1)\n\t\t\t\t\tif len > value.rexpr.length\n\t\t\t\t\t\t@source.last << (', 0' * (len - value.rexpr.length))\n\t\t\t\t\tend\n\n\t\t\t\t\telen * len\n\n\t\t\t\telsif value.kind_of? ::Array\n\t\t\t\t\t@source.last << ':' if not @source.last.empty?\n\t\t\t\t\tlen = type.length || value.length\n\t\t\t\t\tvalue.each { |v|\n\t\t\t\t\t\t@source << ''\n\t\t\t\t\t\tc_idata_inner(type.type, v)\n\t\t\t\t\t}\n\t\t\t\t\tlen -= value.length\n\t\t\t\t\tif len > 0\n\t\t\t\t\t\t@source << \" db #{len * sizeof(nil, type.type)} dup(0)\"\n\t\t\t\t\tend\n\n\t\t\t\t\tsizeof(nil, type.type) * len\n\n\t\t\t\telse raise \"unknown static array initializer #{value.inspect}\"\n\t\t\t\tend\n\t\t\tend\n\t\tend"},"docstring":{"kind":"string","value":"dumps an anonymous variable definition, appending to the last line of source\nsource.last is a label name or is empty before calling here\nreturn the length of the data written"},"func_name":{"kind":"string","value":"c_idata_inner"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":438,"cells":{"code":{"kind":"string","value":"def check_reserved_name(var)\n\t\t\treturn true if @exeformat.cpu and @exeformat.cpu.check_reserved_name(var.name)\n\t\t\t%w[db dw dd dq].include?(var.name)\n\t\tend"},"docstring":{"kind":"string","value":"return non-nil if the variable name is unsuitable to appear as is in the asm listing\neg filter out asm instruction names"},"func_name":{"kind":"string","value":"check_reserved_name"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":439,"cells":{"code":{"kind":"string","value":"def precompile_make_block(scope)\n\t\t\tb = Block.new scope\n\t\t\tb.statements << self\n\t\t\tb\n\t\tend"},"docstring":{"kind":"string","value":"all Statements/Declaration must define a precompile(compiler, scope) method\nit must append itself to scope.statements\nturns a statement into a new block"},"func_name":{"kind":"string","value":"precompile_make_block"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":440,"cells":{"code":{"kind":"string","value":"def precompile(compiler, scope=nil)\n\t\t\tstmts = @statements.dup\n\t\t\t@statements.clear\n\t\t\tstmts.each { |st|\n\t\t\t\tcompiler.curexpr = st\n\t\t\t\tst.precompile(compiler, self)\n\t\t\t}\n\n\t\t\t# cleanup declarations\n\t\t\t@symbol.delete_if { |n, s| not s.kind_of? Variable }\n\t\t\t@struct.delete_if { |n, s| not s.kind_of? Union }\n\t\t\t@symbol.each_value { |var|\n\t\t\t\tCExpression.precompile_type(compiler, self, var, true)\n\t\t\t}\n\t\t\t@struct.each_value { |var|\n\t\t\t\tnext if not var.members\n\t\t\t\tvar.members.each { |m|\n\t\t\t\t\tCExpression.precompile_type(compiler, self, m, true)\n\t\t\t\t}\n\t\t\t}\n\t\t\tscope.statements << self if scope and not @statements.empty?\n\t\tend"},"docstring":{"kind":"string","value":"precompile all statements, then simplifies symbols/structs types"},"func_name":{"kind":"string","value":"precompile"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":441,"cells":{"code":{"kind":"string","value":"def precompile_optimize\n\t\t\tlist = []\n\t\t\tprecompile_optimize_inner(list, 1)\n\t\t\tprecompile_optimize_inner(list, 2)\n\t\tend"},"docstring":{"kind":"string","value":"removes unused labels, and in-place goto (goto toto; toto:)"},"func_name":{"kind":"string","value":"precompile_optimize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":442,"cells":{"code":{"kind":"string","value":"def precompile_optimize_inner(list, step)\n\t\t\tlastgoto = nil\n\t\t\thadref = false\n\t\t\twalk = lambda { |expr|\n\t\t\t\tnext if not expr.kind_of? CExpression\n\t\t\t\t# gcc's unary && support\n\t\t\t\tif not expr.op and not expr.lexpr and expr.rexpr.kind_of? Label\n\t\t\t\t\tlist << expr.rexpr.name\n\t\t\t\telse\n\t\t\t\t\twalk[expr.lexpr]\n\t\t\t\t\tif expr.rexpr.kind_of? ::Array\n\t\t\t\t\t\texpr.rexpr.each { |r| walk[r] }\n\t\t\t\t\telse\n\t\t\t\t\t\twalk[expr.rexpr]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t}\n\t\t\t@statements.dup.each { |s|\n\t\t\t\tlastgoto = nil if not s.kind_of? Label\n\t\t\t\tcase s\n\t\t\t\twhen Block\n\t\t\t\t\ts.precompile_optimize_inner(list, step)\n\t\t\t\t\t@statements.delete s if step == 2 and s.statements.empty?\n\t\t\t\twhen CExpression; walk[s] if step == 1\n\t\t\t\twhen Label\n\t\t\t\t\tcase step\n\t\t\t\t\twhen 1\n\t\t\t\t\t\tif lastgoto and lastgoto.target == s.name\n\t\t\t\t\t\t\tlist << lastgoto\n\t\t\t\t\t\t\tlist.delete s.name if not hadref\n\t\t\t\t\t\tend\n\t\t\t\t\twhen 2; @statements.delete s if not list.include? s.name\n\t\t\t\t\tend\n\t\t\t\twhen Goto, If\n\t\t\t\t\ts.kind_of?(If) ? g = s.bthen : g = s\n\t\t\t\t\tcase step\n\t\t\t\t\twhen 1\n\t\t\t\t\t\thadref = list.include? g.target\n\t\t\t\t\t\tlastgoto = g\n\t\t\t\t\t\tlist << g.target\n\t\t\t\t\twhen 2\n\t\t\t\t\t\tif list.include? g\n\t\t\t\t\t\t\tidx = @statements.index s\n\t\t\t\t\t\t\t@statements.delete s\n\t\t\t\t\t\t\t@statements[idx, 0] = s.test if s != g and not s.test.constant?\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t}\n\t\t\tlist\n\t\tend"},"docstring":{"kind":"string","value":"step 1: list used labels/unused goto\nstep 2: remove unused labels"},"func_name":{"kind":"string","value":"precompile_optimize_inner"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":443,"cells":{"code":{"kind":"string","value":"def precompile_inner(compiler, scope, nested = true)\n\t\t\tcase @op\n\t\t\twhen :'.'\n\t\t\t\t# a.b => (&a)->b\n\t\t\t\tlexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\tll = lexpr\n\t\t\t\tll = lexpr.rexpr while ll.kind_of? CExpression and not ll.op\n\t\t\t\tif ll.kind_of? CExpression and ll.op == :'*' and not ll.lexpr\n\t\t\t\t\t# do not change lexpr.rexpr.type directly to a pointer, might retrigger (ptr+imm) => (ptr + imm*sizeof(*ptr))\n\t\t\t\t\t@lexpr = CExpression.new(nil, nil, ll.rexpr, Pointer.new(lexpr.type))\n\t\t\t\telse\n\t\t\t\t\t@lexpr = CExpression.new(nil, :'&', lexpr, Pointer.new(lexpr.type))\n\t\t\t\tend\n\t\t\t\t@op = :'->'\n\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\twhen :'->'\n\t\t\t\t# a->b => *(a + off(b))\n\t\t\t\tstruct = @lexpr.type.untypedef.type.untypedef\n\t\t\t\tlexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t@lexpr = nil\n\t\t\t\t@op = nil\n\t\t\t\tif struct.kind_of? Union and (off = struct.offsetof(compiler, @rexpr)) != 0\n\t\t\t\t\toff = CExpression.new(nil, nil, off, BaseType.new(:int, :unsigned))\n\t\t\t\t\t@rexpr = CExpression.new(lexpr, :'+', off, lexpr.type)\n\t\t\t\t\t# ensure the (ptr + value) is not expanded to (ptr + value * sizeof(*ptr))\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, @rexpr)\n\t\t\t\telse\n\t\t\t\t\t# union or 1st struct member\n\t\t\t\t\t@rexpr = lexpr\n\t\t\t\tend\n\t\t\t\tif @type.kind_of? Array # Array member type is already an address\n\t\t\t\telse\n\t\t\t\t\t@rexpr = CExpression.new(nil, :*, @rexpr, @rexpr.type)\n\t\t\t\tend\n\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\twhen :'[]'\n\t\t\t\trexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\tif rexpr.kind_of? CExpression and not rexpr.op and rexpr.rexpr == 0\n\t\t\t\t\t@rexpr = @lexpr\n\t\t\t\telse\n\t\t\t\t\t@rexpr = CExpression.new(@lexpr, :'+', rexpr, @lexpr.type)\n\t\t\t\tend\n\t\t\t\t@op = :'*'\n\t\t\t\t@lexpr = nil\n\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\twhen :'?:'\n\t\t\t\t# cannot precompile in place, a conditionnal expression may have a coma: must turn into If\n\t\t\t\tif @lexpr.kind_of? CExpression\n\t\t\t\t\t@lexpr = @lexpr.precompile_inner(compiler, scope)\n\t\t\t\t\tif not @lexpr.lexpr and not @lexpr.op and @lexpr.rexpr.kind_of? ::Numeric\n\t\t\t\t\t\tif @lexpr.rexpr == 0\n\t\t\t\t\t\t\te = @rexpr[1]\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\te = @rexpr[0]\n\t\t\t\t\t\tend\n\t\t\t\t\t\te = CExpression.new(nil, nil, e, e.type) if not e.kind_of? CExpression\n\t\t\t\t\t\treturn e.precompile_inner(compiler, scope)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\traise 'conditional in toplevel' if scope == compiler.toplevel\t# just in case\n\t\t\t\tvar = Variable.new\n\t\t\t\tvar.storage = :register\n\t\t\t\tvar.name = compiler.new_label('ternary')\n\t\t\t\tvar.type = @rexpr[0].type\n\t\t\t\tCExpression.precompile_type(compiler, scope, var)\n\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\tIf.new(@lexpr, CExpression.new(var, :'=', @rexpr[0], var.type), CExpression.new(var, :'=', @rexpr[1], var.type)).precompile(compiler, scope)\n\t\t\t\t@lexpr = nil\n\t\t\t\t@op = nil\n\t\t\t\t@rexpr = var\n\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\twhen :'&&'\n\t\t\t\tif scope == compiler.toplevel\n\t\t\t\t\t@lexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\tself\n\t\t\t\telse\n\t\t\t\t\tvar = Variable.new\n\t\t\t\t\tvar.storage = :register\n\t\t\t\t\tvar.name = compiler.new_label('and')\n\t\t\t\t\tvar.type = @type\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, var)\n\t\t\t\t\tvar.initializer = CExpression.new(nil, nil, 0, var.type)\n\t\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\t\tl = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type)\n\t\t\t\t\tr = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type)\n\t\t\t\t\tIf.new(l, If.new(r, CExpression.new(var, :'=', CExpression.new(nil, nil, 1, var.type), var.type))).precompile(compiler, scope)\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = var\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\tend\n\t\t\twhen :'||'\n\t\t\t\tif scope == compiler.toplevel\n\t\t\t\t\t@lexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\tself\n\t\t\t\telse\n\t\t\t\t\tvar = Variable.new\n\t\t\t\t\tvar.storage = :register\n\t\t\t\t\tvar.name = compiler.new_label('or')\n\t\t\t\t\tvar.type = @type\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, var)\n\t\t\t\t\tvar.initializer = CExpression.new(nil, nil, 1, var.type)\n\t\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\t\tl = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type)\n\t\t\t\t\tl = CExpression.new(nil, :'!', l, var.type)\n\t\t\t\t\tr = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type)\n\t\t\t\t\tr = CExpression.new(nil, :'!', r, var.type)\n\t\t\t\t\tIf.new(l, If.new(r, CExpression.new(var, :'=', CExpression.new(nil, nil, 0, var.type), var.type))).precompile(compiler, scope)\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = var\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\tend\n\t\t\twhen :funcall\n\t\t\t\tif @lexpr.kind_of? Variable and @lexpr.type.kind_of? Function and @lexpr.attributes and @lexpr.attributes.include? 'inline' and @lexpr.initializer\n\t\t\t\t\t# TODO check recursive call (direct or indirect)\n\t\t\t\t\traise 'inline varargs unsupported' if @lexpr.type.varargs\n\t\t\t\t\trtype = @lexpr.type.type.untypedef\n\t\t\t\t\tif not rtype.kind_of? BaseType or rtype.name != :void\n\t\t\t\t\t\trval = Variable.new\n\t\t\t\t\t\trval.name = compiler.new_label('inline_return')\n\t\t\t\t\t\trval.type = @lexpr.type.type\n\t\t\t\t\t\tDeclaration.new(rval).precompile(compiler, scope)\n\t\t\t\t\tend\n\t\t\t\t\tinline_label = {}\n\t\t\t\t\tlocals = @lexpr.type.args.zip(@rexpr).inject({}) { |h, (fa, a)|\n\t\t\t\t\t\th.update fa => CExpression.new(nil, nil, a, fa.type).precompile_inner(compiler, scope)\n\t\t\t\t\t}\n\t\t\t\t\tcopy_inline_ce = lambda { |ce|\n\t\t\t\t\t\tcase ce\n\t\t\t\t\t\twhen CExpression; CExpression.new(copy_inline_ce[ce.lexpr], ce.op, copy_inline_ce[ce.rexpr], ce.type)\n\t\t\t\t\t\twhen Variable; locals[ce] || ce\n\t\t\t\t\t\twhen ::Array; ce.map { |e_| copy_inline_ce[e_] }\n\t\t\t\t\t\telse ce\n\t\t\t\t\t\tend\n\t\t\t\t\t}\n\t\t\t\t\tcopy_inline = lambda { |stmt, scp|\n\t\t\t\t\t\tcase stmt\n\t\t\t\t\t\twhen Block\n\t\t\t\t\t\t\tb = Block.new(scp)\n\t\t\t\t\t\t\tstmt.statements.each { |s|\n\t\t\t\t\t\t\t\ts = copy_inline[s, b]\n\t\t\t\t\t\t\t\tb.statements << s if s\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tb\n\t\t\t\t\t\twhen If; If.new(copy_inline_ce[stmt.test], copy_inline[stmt.bthen, scp])\t\t# re-precompile ?\n\t\t\t\t\t\twhen Label; Label.new(inline_label[stmt.name] ||= compiler.new_label('inline_'+stmt.name))\n\t\t\t\t\t\twhen Goto; Goto.new(inline_label[stmt.target] ||= compiler.new_label('inline_'+stmt.target))\n\t\t\t\t\t\twhen Return; CExpression.new(rval, :'=', copy_inline_ce[stmt.value], rval.type).precompile_inner(compiler, scp) if stmt.value\n\t\t\t\t\t\twhen CExpression; copy_inline_ce[stmt]\n\t\t\t\t\t\twhen Declaration\n\t\t\t\t\t\t\tnv = stmt.var.dup\n\t\t\t\t\t\t\tif nv.type.kind_of? Array and nv.type.length.kind_of? CExpression\n\t\t\t\t\t\t\t\tnv.type = Array.new(nv.type.type, copy_inline_ce[nv.type.length])\t# XXX nested dynamic?\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tlocals[stmt.var] = nv\n\t\t\t\t\t\t\tscp.symbol[nv.name] = nv\n\t\t\t\t\t\t\tDeclaration.new(nv)\n\t\t\t\t\t\telse raise 'unexpected inline statement ' + stmt.inspect\n\t\t\t\t\t\tend\n\t\t\t\t\t}\n\t\t\t\t\tscope.statements << copy_inline[@lexpr.initializer, scope]\t\t# body already precompiled\n\t\t\t\t\tCExpression.new(nil, nil, rval, rval.type).precompile_inner(compiler, scope)\n\t\t\t\telsif @type.kind_of? Union\n\t\t\t\t\tvar = Variable.new\n\t\t\t\t\tvar.name = compiler.new_label('return_struct')\n\t\t\t\t\tvar.type = @type\n\t\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\t\t@rexpr.unshift CExpression.new(nil, :&, var, Pointer.new(var.type))\n\n\t\t\t\t\tvar2 = Variable.new\n\t\t\t\t\tvar2.name = compiler.new_label('return_struct_ptr')\n\t\t\t\t\tvar2.type = Pointer.new(@type)\n\t\t\t\t\tvar2.storage = :register\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, var2)\n\t\t\t\t\tDeclaration.new(var2).precompile(compiler, scope)\n\t\t\t\t\t@type = var2.type\n\t\t\t\t\tCExpression.new(var2, :'=', self, var2.type).precompile(compiler, scope)\n\n\t\t\t\t\tCExpression.new(nil, :'*', var2, var.type).precompile_inner(compiler, scope)\n\t\t\t\telse\n\t\t\t\t\tt = @lexpr.type.untypedef\n\t\t\t\t\tt = t.type.untypedef if t.pointer?\n\t\t\t\t\t@lexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t\ttypes = t.args.map { |a| a.type }\n\t\t\t\t\t# cast args to func prototype\n\t\t\t\t\t@rexpr.map! { |e_| (types.empty? ? e_ : CExpression.new(nil, nil, e_, types.shift)).precompile_inner(compiler, scope) }\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\tself\n\t\t\t\tend\n\t\t\twhen :','\n\t\t\t\tlexpr = @lexpr.kind_of?(CExpression) ? @lexpr : CExpression.new(nil, nil, @lexpr, @lexpr.type)\n\t\t\t\trexpr = @rexpr.kind_of?(CExpression) ? @rexpr : CExpression.new(nil, nil, @rexpr, @rexpr.type)\n\t\t\t\tlexpr.precompile(compiler, scope)\n\t\t\t\trexpr.precompile_inner(compiler, scope)\n\t\t\twhen :'!'\n\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\tif @rexpr.kind_of?(CExpression)\n\t\t\t\t\tcase @rexpr.op\n\t\t\t\t\twhen :'<', :'>', :'<=', :'>=', :'==', :'!='\n\t\t\t\t\t\t@op = { :'<' => :'>=', :'>' => :'<=', :'<=' => :'>', :'>=' => :'<',\n\t\t\t\t\t\t\t:'==' => :'!=', :'!=' => :'==' }[@rexpr.op]\n\t\t\t\t\t\t@lexpr = @rexpr.lexpr\n\t\t\t\t\t\t@rexpr = @rexpr.rexpr\n\t\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\t\twhen :'&&', :'||'\n\t\t\t\t\t\t@op = { :'&&' => :'||', :'||' => :'&&' }[@rexpr.op]\n\t\t\t\t\t\t@lexpr = CExpression.new(nil, :'!', @rexpr.lexpr, @type)\n\t\t\t\t\t\t@rexpr = CExpression.new(nil, :'!', @rexpr.rexpr, @type)\n\t\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\t\twhen :'!'\n\t\t\t\t\t\tif @rexpr.rexpr.kind_of? CExpression\n\t\t\t\t\t\t\t@op = nil\n\t\t\t\t\t\t\t@rexpr = @rexpr.rexpr\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t@op = :'!='\n\t\t\t\t\t\t\t@lexpr = @rexpr.rexpr\n\t\t\t\t\t\t\t@rexpr = CExpression.new(nil, nil, 0, @lexpr.type)\n\t\t\t\t\t\tend\n\t\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\t\telse\n\t\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\t\tself\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\tself\n\t\t\t\tend\n\t\t\twhen :'++', :'--'\n\t\t\t\tif not @rexpr\n\t\t\t\t\tvar = Variable.new\n\t\t\t\t\tvar.storage = :register\n\t\t\t\t\tvar.name = compiler.new_label('postincrement')\n\t\t\t\t\tvar.type = @type\n\t\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\t\tCExpression.new(var, :'=', @lexpr, @type).precompile(compiler, scope)\n\t\t\t\t\tCExpression.new(nil, @op, @lexpr, @type).precompile(compiler, scope)\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = var\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\telsif @type.pointer? and compiler.sizeof(nil, @type.untypedef.type.untypedef) != 1\n\t\t\t\t\t# ++ptr => ptr += sizeof(*ptr) (done in += precompiler)\n\t\t\t\t\t@op = { :'++' => :'+=', :'--' => :'-=' }[@op]\n\t\t\t\t\t@lexpr = @rexpr\n\t\t\t\t\t@rexpr = CExpression.new(nil, nil, 1, BaseType.new(:ptr, :unsigned))\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\telse\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\tself\n\t\t\t\tend\n\t\t\twhen :'='\n\t\t\t\t# handle structure assignment/array assignment\n\t\t\t\tcase @lexpr.type.untypedef\n\t\t\t\twhen Union\n\t\t\t\t\t# rexpr may be a :funcall\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\t@lexpr.type.untypedef.members.zip(@rexpr.type.untypedef.members) { |m1, m2|\n\t\t\t\t\t\t# assume m1 and m2 are compatible\n\t\t\t\t\t\tv1 = CExpression.new(@lexpr, :'.', m1.name, m1.type)\n\t\t\t\t\t\tv2 = CExpression.new(@rexpr, :'.', m2.name, m1.type)\n\t\t\t\t\t\tCExpression.new(v1, :'=', v2, v1.type).precompile(compiler, scope)\n\t\t\t\t\t}\n\t\t\t\t\t# (foo = bar).toto\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = @lexpr\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@type = @rexpr.type\n\t\t\t\t\tprecompile_inner(compiler, scope) if nested\n\t\t\t\twhen Array\n\t\t\t\t\tif not len = @lexpr.type.untypedef.length\n\t\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\t\t# char toto[] = \"bla\"\n\t\t\t\t\t\tif @rexpr.kind_of? CExpression and not @rexpr.lexpr and not @rexpr.op and\n\t\t\t\t\t\t\t\t@rexpr.rexpr.kind_of? Variable and @rexpr.rexpr.type.kind_of? Array\n\t\t\t\t\t\t\tlen = @rexpr.rexpr.type.length\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\traise 'array initializer with no length !' if not len\n\t\t\t\t\t# TODO optimize...\n\t\t\t\t\tlen.times { |i|\n\t\t\t\t\t\ti = CExpression.new(nil, nil, i, BaseType.new(:long, :unsigned))\n\t\t\t\t\t\tv1 = CExpression.new(@lexpr, :'[]', i, @lexpr.type.untypedef.type)\n\t\t\t\t\t\tv2 = CExpression.new(@rexpr, :'[]', i, v1.type)\n\t\t\t\t\t\tCExpression.new(v1, :'=', v2, v1.type).precompile(compiler, scope)\n\t\t\t\t\t}\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = @lexpr\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@type = @rexpr.type\n\t\t\t\t\tprecompile_inner(compiler, scope) if nested\n\t\t\t\telse\n\t\t\t\t\t@lexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\tself\n\t\t\t\tend\n\t\t\twhen nil\n\t\t\t\tcase @rexpr\n\t\t\t\twhen Block\n\t\t\t\t\t# compound statements\n\t\t\t\t\traise 'compound statement in toplevel' if scope == compiler.toplevel\t# just in case\n\t\t\t\t\tvar = Variable.new\n\t\t\t\t\tvar.storage = :register\n\t\t\t\t\tvar.name = compiler.new_label('compoundstatement')\n\t\t\t\t\tvar.type = @type\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, var)\n\t\t\t\t\tDeclaration.new(var).precompile(compiler, scope)\n\t\t\t\t\tif @rexpr.statements.last.kind_of? CExpression\n\t\t\t\t\t\t@rexpr.statements[-1] = CExpression.new(var, :'=', @rexpr.statements[-1], var.type)\n\t\t\t\t\t\t@rexpr.precompile(compiler, scope)\n\t\t\t\t\tend\n\t\t\t\t\t@rexpr = var\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\twhen ::String\n\t\t\t\t\t# char[] immediate\n\t\t\t\t\tv = Variable.new\n\t\t\t\t\tv.storage = :static\n\t\t\t\t\tv.name = 'char_' + @rexpr.tr('^a-zA-Z', '')[0, 8]\n\t\t\t\t\tv.type = Array.new(@type.type)\n\t\t\t\t\tv.type.length = @rexpr.length + 1\n\t\t\t\t\tv.type.type.qualifier = [:const]\n\t\t\t\t\tv.initializer = CExpression.new(nil, nil, @rexpr, @type)\n\t\t\t\t\tDeclaration.new(v).precompile(compiler, scope)\n\t\t\t\t\t@rexpr = v\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\twhen ::Float\n\t\t\t\t\t# float immediate\n\t\t\t\t\tv = Variable.new\n\t\t\t\t\tv.storage = :static\n\t\t\t\t\tv.name = @type.untypedef.name.to_s\n\t\t\t\t\tv.type = @type\n\t\t\t\t\tv.type.qualifier = [:const]\n\t\t\t\t\tv.initializer = CExpression.new(nil, nil, @rexpr, @type)\n\t\t\t\t\tDeclaration.new(v).precompile(compiler, scope)\n\t\t\t\t\t@rexpr = CExpression.new(nil, :'*', v, v.type)\n\t\t\t\t\tprecompile_inner(compiler, scope)\n\t\t\t\twhen CExpression\n\t\t\t\t\t# simplify casts\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\t# propagate type first so that __uint64 foo() { return -1 } => 0xffffffffffffffff\n\t\t\t\t\t@rexpr.type = @type if @rexpr.kind_of? CExpression and @rexpr.op == :- and not @rexpr.lexpr and @type.kind_of? BaseType and @type.name == :__int64\t# XXX kill me\n\t\t\t\t\t@rexpr = @rexpr.precompile_inner(compiler, scope)\n\t\t\t\t\tif @type.kind_of? BaseType and @rexpr.type.kind_of? BaseType\n\t\t\t\t\t\tif @rexpr.type == @type\n\t\t\t\t\t\t\t# noop cast\n\t\t\t\t\t\t\t@lexpr, @op, @rexpr = @rexpr.lexpr, @rexpr.op, @rexpr.rexpr\n\t\t\t\t\t\telsif not @rexpr.op and @type.integral? and @rexpr.type.integral?\n\t\t\t\t\t\t\tif @rexpr.rexpr.kind_of? ::Numeric and (val = reduce(compiler)).kind_of? ::Numeric\n\t\t\t\t\t\t\t\t@rexpr = val\n\t\t\t\t\t\t\telsif compiler.typesize[@type.name] < compiler.typesize[@rexpr.type.name]\n\t\t\t\t\t\t\t\t# (char)(short)(int)(long)foo => (char)foo\n\t\t\t\t\t\t\t\t@rexpr = @rexpr.rexpr\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tself\n\t\t\t\telse\n\t\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\t\t\t\t\tself\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t# int+ptr => ptr+int\n\t\t\t\tif @op == :+ and @lexpr and @lexpr.type.integral? and @rexpr.type.pointer?\n\t\t\t\t\t@rexpr, @lexpr = @lexpr, @rexpr\n\t\t\t\tend\n\n\t\t\t\t# handle pointer + 2 == ((char *)pointer) + 2*sizeof(*pointer)\n\t\t\t\tif @rexpr and [:'+', :'+=', :'-', :'-='].include? @op and\n\t\t\t\t\t\t@type.pointer? and @rexpr.type.integral?\n\t\t\t\t\tsz = compiler.sizeof(nil, @type.untypedef.type.untypedef)\n\t\t\t\t\tif sz != 1\n\t\t\t\t\t\tsz = CExpression.new(nil, nil, sz, @rexpr.type)\n\t\t\t\t\t\t@rexpr = CExpression.new(@rexpr, :'*', sz, @rexpr.type)\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\t# type promotion => cast\n\t\t\t\tcase @op\n\t\t\t\twhen :+, :-, :*, :/, :&, :|, :^, :%\n\t\t\t\t if @lexpr\n\t\t\t\t\tif @lexpr.type != @type\n\t\t\t\t\t\t@lexpr = CExpression.new(nil, nil, @lexpr, @lexpr.type) if not @lexpr.kind_of? CExpression\n\t\t\t\t\t\t@lexpr = CExpression.new(nil, nil, @lexpr, @type)\n\t\t\t\t\tend\n\t\t\t\t\tif @rexpr.type != @type\n\t\t\t\t\t\t@rexpr = CExpression.new(nil, nil, @rexpr, @rexpr.type) if not @rexpr.kind_of? CExpression\n\t\t\t\t\t\t@rexpr = CExpression.new(nil, nil, @rexpr, @type)\n\t\t\t\t\tend\n\t\t\t\t end\n\t\t\t\twhen :>>, :<<\n\t\t\t\t\t# char => int\n\t\t\t\t\tif @lexpr.type != @type\n\t\t\t\t\t\t@lexpr = CExpression.new(nil, nil, @lexpr, @lexpr.type) if not @lexpr.kind_of? CExpression\n\t\t\t\t\t\t@lexpr = CExpression.new(nil, nil, @lexpr, @type)\n\t\t\t\t\tend\n\t\t\t\twhen :'+=', :'-=', :'*=', :'/=', :'&=', :'|=', :'^=', :'%='\n\t\t\t\t\tif @rexpr.type != @lexpr.type\n\t\t\t\t\t\t@rexpr = CExpression.new(nil, nil, @rexpr, @rexpr.type) if not @rexpr.kind_of? CExpression\n\t\t\t\t\t\t@rexpr = CExpression.new(nil, nil, @rexpr, @type)\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\t@lexpr = CExpression.precompile_inner(compiler, scope, @lexpr)\n\t\t\t\t@rexpr = CExpression.precompile_inner(compiler, scope, @rexpr)\n\n\t\t\t\tif @op == :'&' and not @lexpr\n\t\t\t\t\trr = @rexpr\n\t\t\t\t\trr = rr.rexpr while rr.kind_of? CExpression and not rr.op\n\t\t\t\t\tif rr.kind_of? CExpression and rr.op == :'*' and not rr.lexpr\n\t\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t\t@op = nil\n\t\t\t\t\t\t@rexpr = rr.rexpr\n\t\t\t\t\t\treturn precompile_inner(compiler, scope)\n\t\t\t\t\telsif rr != @rexpr\n\t\t\t\t\t\t@rexpr = rr\n\t\t\t\t\t\treturn precompile_inner(compiler, scope)\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tCExpression.precompile_type(compiler, scope, self)\n\n\t\t\t\tisnumeric = lambda { |e_| e_.kind_of?(::Numeric) or (e_.kind_of? CExpression and\n\t\t\t\t\tnot e_.lexpr and not e_.op and e_.rexpr.kind_of? ::Numeric) }\n\n\t\t\t\t# calc numeric\n\t\t\t\t# XXX do not simplify operations involving variables (for type overflow etc)\n\t\t\t\tif isnumeric[@rexpr] and (not @lexpr or isnumeric[@lexpr]) and (val = reduce(compiler)).kind_of? ::Numeric\n\t\t\t\t\t@lexpr = nil\n\t\t\t\t\t@op = nil\n\t\t\t\t\t@rexpr = val\n\t\t\t\tend\n\n\t\t\t\tself\n\t\t\tend\n\t\tend"},"docstring":{"kind":"string","value":"returns a new CExpression with simplified self.type, computes structure offsets\nturns char[]/float immediates to reference to anonymised const\nTODO 'a = b += c' => 'b += c; a = b' (use nested argument)\nTODO handle precompile_inner return nil\nTODO struct.bits"},"func_name":{"kind":"string","value":"precompile_inner"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/compile_c.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/compile_c.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":444,"cells":{"code":{"kind":"string","value":"def add_bpm\n\t\t\tm = @address + @internal[:len]\n\t\t\ta = @address & -0x1000\n\t\t\t@hash_shared = [self]\n\n\t\t\t@internal ||= {}\n\t\t\t@internal[:orig_prot] ||= {}\n\t\t\twhile a < m\n\t\t\t\tif pv = @hash_owner[a]\n\t\t\t\t\tif not pv.hash_shared.include?(self)\n\t\t\t\t\t\tpv.hash_shared.concat @hash_shared-pv.hash_shared\n\t\t\t\t\t\t@hash_shared.each { |bpm| bpm.hash_shared = pv.hash_shared }\n\t\t\t\t\tend\n\t\t\t\t\t@internal[:orig_prot][a] = pv.internal[:orig_prot][a]\n\t\t\t\telse\n\t\t\t\t\t@hash_owner[a] = self\n\t\t\t\tend\n\t\t\t\ta += 0x1000\n\t\t\tend\n\t\tend"},"docstring":{"kind":"string","value":"register a bpm: add references to all page start covered in @hash_owner"},"func_name":{"kind":"string","value":"add_bpm"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":445,"cells":{"code":{"kind":"string","value":"def del\n\t\t\treturn del_bpm if @type == :bpm\n\t\t\t@hash_shared.delete self\n\t\t\tif @hash_shared.empty?\n\t\t\t\t@hash_owner.delete @hash_key\n\t\t\telsif @hash_owner[@hash_key] == self\n\t\t\t\t@hash_owner[@hash_key] = @hash_shared.first\n\t\t\tend\n\t\tend"},"docstring":{"kind":"string","value":"delete the breakpoint from hash_shared, and hash_owner if empty"},"func_name":{"kind":"string","value":"del"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":446,"cells":{"code":{"kind":"string","value":"def initialize\n\t\t@pid_stuff = {}\n\t\t@tid_stuff = {}\n\t\t@log_proc = nil\n\t\t@state = :dead\n\t\t@info = ''\n\t\t# stuff saved when we switch pids\n\t\t@pid_stuff_list = [:memory, :cpu, :disassembler, :symbols, :symbols_len,\n\t\t\t:modulemap, :breakpoint, :breakpoint_memory, :tid, :tid_stuff,\n\t\t\t:dead_process]\n\t\t@tid_stuff_list = [:state, :info, :breakpoint_thread, :singlestep_cb,\n\t\t\t:run_method, :run_args, :breakpoint_cause, :dead_thread]\n\t\t@callback_loadlibrary = lambda { |h| loadsyms(h[:address]) ; continue }\n\t\t@callback_newprocess = lambda { |h| log \"process #{@pid} attached\" }\n\t\t@callback_endprocess = lambda { |h| log \"process #{@pid} died\" }\n\t\tinitialize_newpid\n\t\tinitialize_newtid\n\tend"},"docstring":{"kind":"string","value":"initializes the disassembler internal data - subclasses should call super()"},"func_name":{"kind":"string","value":"initialize"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":447,"cells":{"code":{"kind":"string","value":"def initialize_newpid\n\t\treturn if not pid\n\t\t@pid_stuff_list.each { |s| instance_variable_set(\"@#{s}\", nil) }\n\n\t\t@symbols = {}\n\t\t@symbols_len = {}\n\t\t@modulemap = {}\n\t\t@breakpoint = {}\n\t\t@breakpoint_memory = {}\n\t\t@tid_stuff = {}\n\t\tinitialize_cpu\n\t\tinitialize_memory\n\t\tinitialize_disassembler\n\tend"},"docstring":{"kind":"string","value":"creates stuff related to a new process being debugged\nincludes disassembler, modulemap, symbols, breakpoints\nsubclasses should check that @pid maps to a real process and raise() otherwise\nto be called with @pid/@tid set, calls initialize_memory+initialize_cpu"},"func_name":{"kind":"string","value":"initialize_newpid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":448,"cells":{"code":{"kind":"string","value":"def initialize_newtid\n\t\treturn if not tid\n\t\t@tid_stuff_list.each { |s| instance_variable_set(\"@#{s}\", nil) }\n\n\t\t@state = :stopped\n\t\t@info = 'new'\n\t\t@breakpoint_thread = {}\n\t\tgui.swapin_tid if @disassembler and gui.respond_to?(:swapin_tid)\n\tend"},"docstring":{"kind":"string","value":"subclasses should check that @tid maps to a real thread and raise() otherwise"},"func_name":{"kind":"string","value":"initialize_newtid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":449,"cells":{"code":{"kind":"string","value":"def initialize_disassembler\n\t\treturn if not @memory or not @cpu\n\t\t@disassembler = Shellcode.decode(@memory, @cpu).disassembler\n\t\tgui.swapin_pid if gui.respond_to?(:swapin_pid)\n\tend"},"docstring":{"kind":"string","value":"initialize the disassembler from @cpu/@memory"},"func_name":{"kind":"string","value":"initialize_disassembler"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":450,"cells":{"code":{"kind":"string","value":"def swapout_pid\n\t\treturn if not pid\n\t\tswapout_tid\n\t\tgui.swapout_pid if gui.respond_to?(:swapout_pid)\n\t\t@pid_stuff[@pid] ||= {}\n\t\t@pid_stuff_list.each { |fld|\n\t\t\t@pid_stuff[@pid][fld] = instance_variable_get(\"@#{fld}\")\n\t\t}\n\tend"},"docstring":{"kind":"string","value":"we're switching focus from one pid to another, save current pid data"},"func_name":{"kind":"string","value":"swapout_pid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":451,"cells":{"code":{"kind":"string","value":"def swapout_tid\n\t\treturn if not tid\n\t\tgui.swapout_tid if gui.respond_to?(:swapout_tid)\n\t\t@tid_stuff[@tid] ||= {}\n\t\t@tid_stuff_list.each { |fld|\n\t\t\t@tid_stuff[@tid][fld] = instance_variable_get(\"@#{fld}\")\n\t\t}\n\tend"},"docstring":{"kind":"string","value":"we're switching focus from one tid to another, save current tid data"},"func_name":{"kind":"string","value":"swapout_tid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":452,"cells":{"code":{"kind":"string","value":"def swapin_pid\n\t\treturn initialize_newpid if not @pid_stuff[@pid]\n\n\t\t@pid_stuff_list.each { |fld|\n\t\t\tinstance_variable_set(\"@#{fld}\", @pid_stuff[@pid][fld])\n\t\t}\n\t\tswapin_tid\n\t\tgui.swapin_pid if gui.respond_to?(:swapin_pid)\n\tend"},"docstring":{"kind":"string","value":"we're switching focus from one pid to another, load current pid data"},"func_name":{"kind":"string","value":"swapin_pid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":453,"cells":{"code":{"kind":"string","value":"def swapin_tid\n\t\treturn initialize_newtid if not @tid_stuff[@tid]\n\n\t\t@tid_stuff_list.each { |fld|\n\t\t\tinstance_variable_set(\"@#{fld}\", @tid_stuff[@tid][fld])\n\t\t}\n\t\tgui.swapin_tid if gui.respond_to?(:swapin_tid)\n\tend"},"docstring":{"kind":"string","value":"we're switching focus from one tid to another, load current tid data"},"func_name":{"kind":"string","value":"swapin_tid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":454,"cells":{"code":{"kind":"string","value":"def del_pid\n\t\t@pid_stuff.delete @pid\n\t\tif @pid = @pid_stuff.keys.first\n\t\t\tswapin_pid\n\t\telse\n\t\t\t@state = :dead\n\t\t\t@info = ''\n\t\t\t@tid = nil\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"delete references to the current pid\nswitch to another pid, set @state = :dead if none available"},"func_name":{"kind":"string","value":"del_pid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":455,"cells":{"code":{"kind":"string","value":"def del_tid\n\t\t@tid_stuff.delete @tid\n\t\tif @tid = @tid_stuff.keys.first\n\t\t\tswapin_tid\n\t\telse\n\t\t\tdel_tid_notid\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"delete references to the current thread"},"func_name":{"kind":"string","value":"del_tid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":456,"cells":{"code":{"kind":"string","value":"def switch_context(npid, ntid=nil, &b)\n\t\tif npid.respond_to?(:pid)\n\t\t\tntid ||= npid.tid\n\t\t\tnpid = npid.pid\n\t\tend\n\t\toldpid = pid\n\t\toldtid = tid\n\t\tset_pid npid\n\t\tset_tid ntid if ntid\n\t\tif b\n\t\t\t# shortcut begin..ensure overhead\n\t\t\treturn b.call if oldpid == pid and oldtid == tid\n\n\t\t\tbegin\n\t\t\t\tb.call\n\t\t\tensure\n\t\t\t\tset_pid oldpid\n\t\t\t\tset_tid oldtid\n\t\t\tend\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"change the debugger to a specific pid/tid\nif given a block, run the block and then restore the original pid/tid\npid may be an object that respond to #pid/#tid"},"func_name":{"kind":"string","value":"switch_context"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":457,"cells":{"code":{"kind":"string","value":"def each_pid(&b)\n\t\t# ensure @pid is last, so that we finish in the current context\n\t\tlst = @pid_stuff.keys - [@pid]\n\t\tlst << @pid\n\t\treturn lst if not b\n\t\tlst.each { |p|\n\t\t\tset_pid p\n\t\t\tb.call\n\t\t}\n\tend"},"docstring":{"kind":"string","value":"iterate over all pids, yield in the context of this pid"},"func_name":{"kind":"string","value":"each_pid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":458,"cells":{"code":{"kind":"string","value":"def each_tid(&b)\n\t\tlst = @tid_stuff.keys - [@tid]\n\t\tlst << @tid\n\t\treturn lst if not b\n\t\tlst.each { |t|\n\t\t\tset_tid t rescue next\n\t\t\tb.call\n\t\t}\n\tend"},"docstring":{"kind":"string","value":"iterate over all tids of the current process, yield in its context"},"func_name":{"kind":"string","value":"each_tid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":459,"cells":{"code":{"kind":"string","value":"def each_pid_tid(&b)\n\t\teach_pid { each_tid { b.call } }\n\tend"},"docstring":{"kind":"string","value":"iterate over all tids of all pids, yield in their context"},"func_name":{"kind":"string","value":"each_pid_tid"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":460,"cells":{"code":{"kind":"string","value":"def add_bp(addr, info={})\n\t\tinfo[:pid] ||= @pid\n\t\t# dont define :tid for bpx, otherwise on del_bp we may switch_context to this thread that may not be stopped -> cant ptrace_write\n\t\tinfo[:tid] ||= @tid if info[:pid] == @pid and info[:type] == :hwbp\n\n\t\tb = Breakpoint.new\n\t\tinfo.each { |k, v|\n\t\t\tb.send(\"#{k}=\", v)\n\t\t}\n\n\t\tswitch_context(b) {\n\t\t\taddr = resolve_expr(addr) if not addr.kind_of? ::Integer\n\t\t\tb.address = addr\n\n\t\t\tb.hash_owner ||= case b.type\n\t\t\t\twhen :bpm; @breakpoint_memory\n\t\t\t\twhen :hwbp; @breakpoint_thread\n\t\t\t\twhen :bpx; @breakpoint\n\t\t\t\tend\n\t\t\t# XXX bpm may hash_share with an :active, but be larger and still need enable()\n\t\t\tb.add\n\n\t\t\tenable_bp(b) if not info[:state]\n\t\t}\n\n\t\tb\n\tend"},"docstring":{"kind":"string","value":"create a thread/process breakpoint\naddr can be a numeric address, an Expression that is resolved, or\na String that is parsed+resolved\ninfo's keys are set to the breakpoint\nstandard keys are :type, :oneshot, :condition, :action\nreturns the Breakpoint object"},"func_name":{"kind":"string","value":"add_bp"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":461,"cells":{"code":{"kind":"string","value":"def del_all_breakpoints_thread\n\t\t@breakpoint_thread.values.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) }\n\tend"},"docstring":{"kind":"string","value":"delete all breakpoints defined in the current thread"},"func_name":{"kind":"string","value":"del_all_breakpoints_thread"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":462,"cells":{"code":{"kind":"string","value":"def del_all_breakpoints\n\t\teach_tid { del_all_breakpoints_thread }\n\t\t@breakpoint.values.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) }\n\t\t@breakpoint_memory.values.uniq.map { |b| b.hash_shared }.flatten.uniq.each { |b| del_bp(b) }\n\tend"},"docstring":{"kind":"string","value":"delete all breakpoints for the current process and all its threads"},"func_name":{"kind":"string","value":"del_all_breakpoints"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":463,"cells":{"code":{"kind":"string","value":"def init_bpx(b)\n\t\t# dont bother setting stuff up if it is never to be used\n\t\treturn if b.oneshot and not b.condition\n\n\t\t# lazy setup of b.emul_instr: delay building emulating lambda to if/when actually needed\n\t\t# we still need to disassemble now and update @disassembler, before we patch the memory for the bpx\n\t\tdi = init_bpx_disassemble(b.address)\n\t\tb.hash_shared.each { |bb| bb.emul_instr = di }\n\tend"},"docstring":{"kind":"string","value":"called in the context of the target when a bpx is to be initialized\nmay (lazily) initialize b.emul_instr for virtual singlestep"},"func_name":{"kind":"string","value":"init_bpx"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":464,"cells":{"code":{"kind":"string","value":"def init_bpx_disassemble(addr)\n\t\t@disassembler.disassemble_fast_block(addr)\n\t\t@disassembler.di_at(addr)\n\tend"},"docstring":{"kind":"string","value":"retrieve the di at a given address, disassemble if needed\nTODO make it so this doesn't interfere with other 'real' disassembler later commands, eg disassemble() or disassemble_fast_deep()\n(right now, when they see the block already present they stop all processing)"},"func_name":{"kind":"string","value":"init_bpx_disassemble"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":465,"cells":{"code":{"kind":"string","value":"def has_emul_instr(bp)\n\t\tif bp.emul_instr.kind_of?(DecodedInstruction)\n\t\t\tif di = bp.emul_instr and fdbd = @disassembler.get_fwdemu_binding(di, register_pc) and\n\t\t\t\t\tfdbd.all? { |k, v| (k.kind_of?(Symbol) or k.kind_of?(Indirection)) and\n\t\t\t\t\t\tk != :incomplete_binding and v != Expression::Unknown }\n\t\t\t\t# setup a lambda that will mimic, using the debugger primitives, the actual execution of the instruction\n\t\t\t\tbp.emul_instr = lambda {\n\t\t\t\t\tfdbd.map { |k, v|\n\t\t\t\t\t\tk = Indirection[emulinstr_resv(k.pointer), k.len] if k.kind_of?(Indirection)\n\t\t\t\t\t\t[k, emulinstr_resv(v)]\n\t\t\t\t\t}.each { |k, v|\n\t\t\t\t\t\tif k.to_s =~ /flags?_(.+)/i\n\t\t\t\t\t\t\tf = $1.downcase.to_sym\n\t\t\t\t\t\t\tset_flag_value(f, v)\n\t\t\t\t\t\telsif k.kind_of?(Symbol)\n\t\t\t\t\t\t\tset_reg_value(k, v)\n\t\t\t\t\t\telsif k.kind_of?(Indirection)\n\t\t\t\t\t\t\tmemory_write_int(k.pointer, v, k.len)\n\t\t\t\t\t\tend\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbp.hash_shared.each { |bb| bb.emul_instr = bp.emul_instr }\n\t\t\telse\n\t\t\t\tbp.hash_shared.each { |bb| bb.emul_instr = nil }\n\t\t\tend\n\t\tend\n\n\t\tbp.emul_instr\n\tend"},"docstring":{"kind":"string","value":"checks if bp has an emul_instr\ndo the lazy initialization if needed"},"func_name":{"kind":"string","value":"has_emul_instr"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":466,"cells":{"code":{"kind":"string","value":"def hwbp(addr, mtype=:x, mlen=1, oneshot=false, cond=nil, &action)\n\t\th = { :type => :hwbp }\n\t\th[:hash_owner] = @breakpoint_thread\n\t\taddr = resolve_expr(addr) if not addr.kind_of? ::Integer\n\t\tmtype = mtype.to_sym\n\t\th[:hash_key] = [addr, mtype, mlen]\n\t\th[:internal] = { :type => mtype, :len => mlen }\n\t\th[:oneshot] = true if oneshot\n\t\th[:condition] = cond if cond\n\t\th[:action] = action if action\n\t\tadd_bp(addr, h)\n\tend"},"docstring":{"kind":"string","value":"sets a hardware breakpoint\nmtype in :r :w :x\nmlen is the size of the memory zone to cover\nmlen may be constrained by the architecture"},"func_name":{"kind":"string","value":"hwbp"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":467,"cells":{"code":{"kind":"string","value":"def bpm(addr, mtype=:r, mlen=4096, oneshot=false, cond=nil, &action)\n\t\th = { :type => :bpm }\n\t\taddr = resolve_expr(addr) if not addr.kind_of? ::Integer\n\t\th[:hash_key] = addr & -4096\t# XXX actually referenced at addr, addr+4096, ... addr+len\n\t\th[:internal] = { :type => mtype, :len => mlen }\n\t\th[:oneshot] = true if oneshot\n\t\th[:condition] = cond if cond\n\t\th[:action] = action if action\n\t\tadd_bp(addr, h)\n\tend"},"docstring":{"kind":"string","value":"sets a memory breakpoint\nmtype is :r :w :rw or :x\nmlen is the size of the memory zone to cover"},"func_name":{"kind":"string","value":"bpm"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":468,"cells":{"code":{"kind":"string","value":"def set_log_proc(l=nil, &b)\n\t\t@log_proc = l || b\n\tend"},"docstring":{"kind":"string","value":"define the lambda to use to log stuff"},"func_name":{"kind":"string","value":"set_log_proc"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":469,"cells":{"code":{"kind":"string","value":"def log(*a)\n\t\tif @log_proc\n\t\t\ta.each { |aa| @log_proc[aa] }\n\t\telse\n\t\t\tputs(*a) if $VERBOSE\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"show information to the user, uses log_proc if defined"},"func_name":{"kind":"string","value":"log"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":470,"cells":{"code":{"kind":"string","value":"def invalidate\n\t\t@memory.invalidate if @memory\n\tend"},"docstring":{"kind":"string","value":"marks the current cache of memory/regs invalid"},"func_name":{"kind":"string","value":"invalidate"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":471,"cells":{"code":{"kind":"string","value":"def dasm_invalidate\n\t\tdisassembler.sections.each_value { |s| s.data.invalidate if s.data.respond_to?(:invalidate) } if disassembler\n\tend"},"docstring":{"kind":"string","value":"invalidates the EncodedData backend for the dasm sections"},"func_name":{"kind":"string","value":"dasm_invalidate"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":472,"cells":{"code":{"kind":"string","value":"def all_breakpoints(addr=nil)\n\t\tret = []\n\t\tif addr\n\t\t\tif b = @breakpoint[addr]\n\t\t\t\tret |= b.hash_shared\n\t\t\tend\n\t\telse\n\t\t\t@breakpoint.each_value { |bb| ret |= bb.hash_shared }\n\t\tend\n\n\t\t@breakpoint_thread.each_value { |bb|\n\t\t\tnext if addr and bb.address != addr\n\t\t\tret |= bb.hash_shared\n\t\t}\n\n\t\t@breakpoint_memory.each_value { |bb|\n\t\t\tnext if addr and (bb.address+bb.internal[:len] <= addr or bb.address > addr)\n\t\t\tret |= bb.hash_shared\n\t\t}\n\n\t\tret\n\tend"},"docstring":{"kind":"string","value":"return all breakpoints set on a specific address (or all bp)"},"func_name":{"kind":"string","value":"all_breakpoints"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":473,"cells":{"code":{"kind":"string","value":"def find_breakpoint(addr=nil, &b)\n\t\treturn @breakpoint[addr] if @breakpoint[addr] and (not b or b.call(@breakpoint[addr]))\n\t\tall_breakpoints(addr).find { |bp| b.call bp }\n\tend"},"docstring":{"kind":"string","value":"return on of the breakpoints at address addr"},"func_name":{"kind":"string","value":"find_breakpoint"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":474,"cells":{"code":{"kind":"string","value":"def check_pre_run(run_m, *run_a)\n\t\tif @dead_process\n\t\t\tdel_pid\n\t\t\treturn\n\t\telsif @dead_thread\n\t\t\tdel_tid\n\t\t\treturn\n\t\telsif @state == :running\n\t\t\treturn\n\t\tend\n\t\t@cpu.dbg_check_pre_run(self) if @cpu.respond_to?(:dbg_check_pre_run)\n\t\t@breakpoint_cause = nil\n\t\t@run_method = run_m\n\t\t@run_args = run_a\n\t\t@info = nil\n\t\ttrue\n\tend"},"docstring":{"kind":"string","value":"to be called right before resuming execution of the target\nrun_m is the method that should be called if the execution is stopped\ndue to a side-effect of the debugger (bpx with wrong condition etc)\nreturns nil if the execution should be avoided (just deleted the dead thread/process)"},"func_name":{"kind":"string","value":"check_pre_run"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":475,"cells":{"code":{"kind":"string","value":"def evt_singlestep(b=nil)\n\t\tb ||= find_singlestep\n\t\treturn evt_exception(:type => 'singlestep') if not b\n\n\t\t@state = :stopped\n\t\t@info = 'singlestep'\n\t\t@cpu.dbg_evt_singlestep(self) if @cpu.respond_to?(:dbg_evt_singlestep)\n\n\t\tcallback_singlestep[] if callback_singlestep\n\n\t\tif cb = @singlestep_cb\n\t\t\t@singlestep_cb = nil\n\t\t\tcb.call\t# call last, as the cb may change singlestep_cb/state/etc\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"called when the target stops due to a singlestep exception"},"func_name":{"kind":"string","value":"evt_singlestep"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":476,"cells":{"code":{"kind":"string","value":"def find_singlestep\n\t\treturn @cpu.dbg_find_singlestep(self) if @cpu.respond_to?(:dbg_find_singlestep)\n\t\t@run_method == :singlestep\n\tend"},"docstring":{"kind":"string","value":"returns true if the singlestep is due to us"},"func_name":{"kind":"string","value":"find_singlestep"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":477,"cells":{"code":{"kind":"string","value":"def evt_bpx(b=nil)\n\t\tb ||= find_bp_bpx\n\t\t# TODO handle race:\n\t\t# 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\n\t\treturn evt_exception(:type => 'breakpoint') if not b\n\n\t\t@state = :stopped\n\t\t@info = 'breakpoint'\n\t\t@cpu.dbg_evt_bpx(self, b) if @cpu.respond_to?(:dbg_evt_bpx)\n\n\t\tcallback_bpx[b] if callback_bpx\n\n\t\tpost_evt_bp(b)\n\tend"},"docstring":{"kind":"string","value":"called when the target stops due to a soft breakpoint exception"},"func_name":{"kind":"string","value":"evt_bpx"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":478,"cells":{"code":{"kind":"string","value":"def find_bp_bpx\n\t\treturn @cpu.dbg_find_bpx(self) if @cpu.respond_to?(:dbg_find_bpx)\n\t\t@breakpoint[pc]\n\tend"},"docstring":{"kind":"string","value":"return the breakpoint that is responsible for the evt_bpx"},"func_name":{"kind":"string","value":"find_bp_bpx"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":479,"cells":{"code":{"kind":"string","value":"def evt_hwbp(b=nil)\n\t\tb ||= find_bp_hwbp\n\t\treturn evt_exception(:type => 'hwbp') if not b\n\n\t\t@state = :stopped\n\t\t@info = 'hwbp'\n\t\t@cpu.dbg_evt_hwbp(self, b) if @cpu.respond_to?(:dbg_evt_hwbp)\n\n\t\tcallback_hwbp[b] if callback_hwbp\n\n\t\tpost_evt_bp(b)\n\tend"},"docstring":{"kind":"string","value":"called when the target stops due to a hwbp exception"},"func_name":{"kind":"string","value":"evt_hwbp"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":480,"cells":{"code":{"kind":"string","value":"def find_bp_hwbp\n\t\treturn @cpu.dbg_find_hwbp(self) if @cpu.respond_to?(:dbg_find_hwbp)\n\t\t@breakpoint_thread.find { |b| b.address == pc }\n\tend"},"docstring":{"kind":"string","value":"return the breakpoint that is responsible for the evt_hwbp"},"func_name":{"kind":"string","value":"find_bp_hwbp"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":481,"cells":{"code":{"kind":"string","value":"def evt_hwbp_singlestep\n\t\tif b = find_bp_hwbp\n\t\t\tevt_hwbp(b)\n\t\telse\n\t\t\tevt_singlestep\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"called for archs where the same interrupt is generated for hwbp and singlestep\nchecks if a hwbp matches, then call evt_hwbp, else call evt_singlestep (which\nwill forward to evt_exception if singlestep does not match either)"},"func_name":{"kind":"string","value":"evt_hwbp_singlestep"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":482,"cells":{"code":{"kind":"string","value":"def evt_bpm(b)\n\t\t@state = :stopped\n\t\t@info = 'bpm'\n\n\t\tcallback_bpm[b] if callback_bpm\n\n\t\tpost_evt_bp(b)\n\tend"},"docstring":{"kind":"string","value":"called when the target stops due to a memory exception caused by a memory bp\ncalled by evt_exception"},"func_name":{"kind":"string","value":"evt_bpm"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":483,"cells":{"code":{"kind":"string","value":"def find_bp_bpm(info)\n\t\t@breakpoint_memory[info[:fault_addr] & -0x1000]\n\tend"},"docstring":{"kind":"string","value":"return a bpm whose page coverage includes the fault described in info"},"func_name":{"kind":"string","value":"find_bp_bpm"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":484,"cells":{"code":{"kind":"string","value":"def check_bpm_range(b, info)\n\t\treturn if b.address+b.internal[:len] <= info[:fault_addr]\n\t\treturn if b.address >= info[:fault_addr] + info[:fault_len]\n\t\tcase b.internal[:type]\n\t\twhen :r; info[:fault_access] == :r\t# or info[:fault_access] == :x\n\t\twhen :w; info[:fault_access] == :w\n\t\twhen :x; info[:fault_access] == :x\t# XXX non-NX cpu => check pc is in bpm range ?\n\t\twhen :rw; true\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"returns true if the fault described in info is valid to trigger b"},"func_name":{"kind":"string","value":"check_bpm_range"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":485,"cells":{"code":{"kind":"string","value":"def evt_exception(info={})\n\t\tif info[:type] == 'access violation' and b = find_bp_bpm(info)\n\t\t\tinfo[:fault_len] ||= 1\n\t\t\tb.internal.update info\n\t\t\treturn evt_bpm(b)\n\t\tend\n\n\t\t@state = :stopped\n\t\t@info = \"exception #{info[:type]}\"\n\n\t\tcallback_exception[info] if callback_exception\n\n\t\tpass = pass_all_exceptions\n\t\tpass = pass[info] if pass.kind_of? Proc\n\t\tif pass\n\t\t\tpass_current_exception\n\t\t\tresume_badbreak\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"called whenever the target stops due to an exception\ntype may be:\n* 'access violation', :fault_addr, :fault_len, :fault_access (:r/:w/:x)\nanything else for other exceptions (access violation is special to handle bpm)\n..."},"func_name":{"kind":"string","value":"evt_exception"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":486,"cells":{"code":{"kind":"string","value":"def resume_badbreak(b=nil)\n\t\t# ensure we didn't delete b\n\t\tif b and b.hash_shared.find { |bb| bb.state == :active }\n\t\t\trm = @run_method\n\t\t\tif rm == :singlestep\n\t\t\t\tsinglestep_bp(b)\n\t\t\telse\n\t\t\t\tra = @run_args\n\t\t\t\tsinglestep_bp(b) { send rm, *ra }\n\t\t\tend\n\t\telse\n\t\t\tsend @run_method, *@run_args\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"called when we did break due to a breakpoint whose condition is invalid\nresume execution as if we never stopped\ndisable offending bp + singlestep if needed"},"func_name":{"kind":"string","value":"resume_badbreak"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":487,"cells":{"code":{"kind":"string","value":"def singlestep_bp(bp, &b)\n\t\tif has_emul_instr(bp)\n\t\t\t@state = :stopped\n\t\t\tbp.emul_instr.call\n\t\t\tb.call if b\n\t\telse\n\t\t\tbp.hash_shared.each { |bb|\n\t\t\t\tdisable_bp(bb, :temp_inactive) if bb.state == :active\n\t\t\t}\n\t\t\t# this *should* work with different bps stopping the current instr\n\t\t\tprev_sscb = @singlestep_cb\n\t\t\tsinglestep {\n\t\t\t\tbp.hash_shared.each { |bb|\n\t\t\t\t\tenable_bp(bb) if bb.state == :temp_inactive\n\t\t\t\t}\n\t\t\t\tprev_sscb[] if prev_sscb\n\t\t\t\tb.call if b\n\t\t\t}\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"singlesteps over an active breakpoint and run its block\nif the breakpoint provides an emulation stub, run that, otherwise\ndisable the breakpoint, singlestep, and re-enable"},"func_name":{"kind":"string","value":"singlestep_bp"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":488,"cells":{"code":{"kind":"string","value":"def check_breakpoint_cause\n\t\tif bp = @breakpoint_cause and\n\t\t\t\t(bp.type == :bpx or (bp.type == :hwbp and bp.internal[:type] == :x)) and\n\t\t\t\tpc != bp.address\n\t\t\tbp = @breakpoint_cause = nil\n\t\tend\n\t\tbp\n\tend"},"docstring":{"kind":"string","value":"checks if @breakpoint_cause is valid, or was obsoleted by the user changing pc"},"func_name":{"kind":"string","value":"check_breakpoint_cause"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":489,"cells":{"code":{"kind":"string","value":"def wait_target\n\t\tdo_wait_target while @state == :running\n\tend"},"docstring":{"kind":"string","value":"waits until the running target stops (due to a breakpoint, fault, etc)"},"func_name":{"kind":"string","value":"wait_target"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":490,"cells":{"code":{"kind":"string","value":"def continue\n\t\tif b = check_breakpoint_cause and b.hash_shared.find { |bb| bb.state == :active }\n\t\t\tsinglestep_bp(b) {\n\t\t\t\tnext if not check_pre_run(:continue)\n\t\t\t\tdo_continue\n\t\t\t}\n\t\telse\n\t\t\treturn if not check_pre_run(:continue)\n\t\t\tdo_continue\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"resume execution of the target\nbypasses a software breakpoint on pc if needed\nthread breakpoints must be manually disabled before calling continue"},"func_name":{"kind":"string","value":"continue"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":491,"cells":{"code":{"kind":"string","value":"def singlestep(&b)\n\t\t@singlestep_cb = b\n\t\tbp = check_breakpoint_cause\n\t\treturn if not check_pre_run(:singlestep)\n\t\tif bp and bp.hash_shared.find { |bb| bb.state == :active } and has_emul_instr(bp)\n\t\t\t@state = :stopped\n\t\t\tbp.emul_instr.call\n\t\t\tinvalidate\n\t\t\tevt_singlestep(true)\n\t\telse\n\t\t\tdo_singlestep\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"resume execution of the target one instruction at a time"},"func_name":{"kind":"string","value":"singlestep"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":492,"cells":{"code":{"kind":"string","value":"def need_stepover(di = di_at(pc))\n\t\tdi and @cpu.dbg_need_stepover(self, di.address, di)\n\tend"},"docstring":{"kind":"string","value":"tests if the specified instructions should be stepover() using singlestep or\nby putting a breakpoint at next_addr"},"func_name":{"kind":"string","value":"need_stepover"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":493,"cells":{"code":{"kind":"string","value":"def stepover\n\t\tdi = di_at(pc)\n\t\tif need_stepover(di)\n\t\t\tbpx di.next_addr, true, Expression[:tid, :==, @tid]\n\t\t\tcontinue\n\t\telse\n\t\t\tsinglestep\n\t\tend\n\tend"},"docstring":{"kind":"string","value":"stepover: singlesteps, but do not enter in subfunctions"},"func_name":{"kind":"string","value":"stepover"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":494,"cells":{"code":{"kind":"string","value":"def end_stepout(di = di_at(pc))\n\t\tdi and @cpu.dbg_end_stepout(self, di.address, di)\n\tend"},"docstring":{"kind":"string","value":"checks if an instruction should stop the stepout() (eg it is a return instruction)"},"func_name":{"kind":"string","value":"end_stepout"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":495,"cells":{"code":{"kind":"string","value":"def stepout\n\t\t# TODO thread-local bps\n\t\twhile not end_stepout\n\t\t\tstepover\n\t\t\twait_target\n\t\tend\n\t\tdo_singlestep\n\tend"},"docstring":{"kind":"string","value":"stepover until finding the last instruction of the function"},"func_name":{"kind":"string","value":"stepout"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":496,"cells":{"code":{"kind":"string","value":"def go(target, cond=nil)\n\t\tbpx(target, true, cond)\n\t\tcontinue_wait\n\tend"},"docstring":{"kind":"string","value":"set a singleshot breakpoint, run the process, and wait"},"func_name":{"kind":"string","value":"go"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":497,"cells":{"code":{"kind":"string","value":"def di_at(addr)\n\t\t@disassembler.di_at(addr) || @disassembler.disassemble_instruction(addr)\n\tend"},"docstring":{"kind":"string","value":"decode the Instruction at the address, use the @disassembler cache if available"},"func_name":{"kind":"string","value":"di_at"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":498,"cells":{"code":{"kind":"string","value":"def get_flag(f)\n\t\tget_flag_value(f) != 0\n\tend"},"docstring":{"kind":"string","value":"retrieve the value of a flag (true/false)"},"func_name":{"kind":"string","value":"get_flag"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}},{"rowIdx":499,"cells":{"code":{"kind":"string","value":"def toggle_flag(f)\n\t\tset_flag_value(f, 1-get_flag_value(f))\n\tend"},"docstring":{"kind":"string","value":"switch the value of a flag (true->false, false->true)"},"func_name":{"kind":"string","value":"toggle_flag"},"language":{"kind":"string","value":"ruby"},"repo":{"kind":"string","value":"stephenfewer/grinder"},"path":{"kind":"string","value":"node/lib/metasm/metasm/debug.rb"},"url":{"kind":"string","value":"https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb"},"license":{"kind":"string","value":"BSD-3-Clause"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":4,"numItemsPerPage":100,"numTotalItems":138807,"offset":400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NTg3MjYyOCwic3ViIjoiL2RhdGFzZXRzL1NodXUxMjEyMS9ydWJ5LXRyZWVzaXR0ZXItZmlsdGVyZWQtZGF0YXNldHNWMiIsImV4cCI6MTc1NTg3NjIyOCwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.7ln0e9SQn04feQFCaGjRsx2Jh_CuZNFA917hSTqyZwpdTcvtspO8hzVSg26yvRNA1FThcsAzXun0V4ZbCzgIDA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
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