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 initialize(owner, str, opts={})
owner ||= Gtk::Window.toplevels.first
super(nil, owner, Gtk::Dialog::DESTROY_WITH_PARENT,
[Gtk::Stock::OK, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_REJECT])
self.title = opts[:title] if opts[:title]
@label = Gtk::Label.new(str)
@textwidget = Gtk::TextView.new
if opts[:text]
@textwidget.buffer.text = opts[:text].to_s
text_select_all
end
@@history ||= {}
histkey = opts[:history] || str[0, 10]
@history = (@@history[histkey] ||= [])
@history_off = @history.length
@textwidget.signal_connect('key_press_event') { |w, ev|
key = DrawableWidget::Keyboard_trad[ev.keyval]
case key
when :escape
response(RESPONSE_REJECT)
true
when :enter
@history << @textwidget.buffer.text.to_s
@history.pop if @history.last == ''
@history.pop if @history.last == @history[-2]
response(RESPONSE_ACCEPT)
true
when :up, :down
txt = @textwidget.buffer.text.to_s
if (@history_off < @history.length or @history.last != txt)
@history[@history_off] = txt
end
@history_off += (key == :up ? -1 : 1)
@history_off %= @history.length
@textwidget.buffer.text = @history[@history_off].to_s
text_select_all
end
}
signal_connect('response') { |win, id|
resp = @textwidget.buffer.text if id == RESPONSE_ACCEPT
destroy
yield resp.strip if resp
true
}
vbox.pack_start label, false, false, 8
vbox.pack_start @textwidget, false, false, 8
Gtk::Drag.dest_set(self,
Gtk::Drag::DEST_DEFAULT_MOTION |
Gtk::Drag::DEST_DEFAULT_DROP,
[['text/plain', 0, 0], ['text/uri-list', 0, 0]],
Gdk::DragContext::ACTION_COPY | Gdk::DragContext::ACTION_MOVE)
signal_connect('drag_data_received') { |w, dc, x, y, data, info, time|
dc.targets.each { |target|
next if target.name != 'text/plain' and target.name != 'text/uri-list'
data.data.each_line { |l|
l = l.chomp.sub(%r{^file://}, '')
self.text = l
}
}
Gtk::Drag.finish(dc, true, false, time)
}
show_all
present
end | shows a simplitic input box (eg window with a 1-line textbox + OK button), yields the text
TODO history, dropdown, autocomplete, contexts, 3D stereo surround, etc | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def initialize(owner, title, opts={})
owner ||= Gtk::Window.toplevels.first
super(title, owner, Gtk::FileChooser::ACTION_OPEN, nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL], [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT])
f = opts[:path] || @@currentfolder
self.current_folder = f if f
signal_connect('response') { |win, id|
if id == Gtk::Dialog::RESPONSE_ACCEPT
file = filename
@@currentfolder = File.dirname(file)
end
destroy
yield file if file
true
}
show_all
present
end | shows an asynchronous FileChooser window, yields the chosen filename
TODO save last path | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def initialize(owner, title, opts={})
owner ||= Gtk::Window.toplevels.first
super(title, owner, Gtk::FileChooser::ACTION_SAVE, nil,
[Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL], [Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT])
f = opts[:path] || @@currentfolder
self.current_folder = f if f
signal_connect('response') { |win, id|
if id == Gtk::Dialog::RESPONSE_ACCEPT
file = filename
@@currentfolder = File.dirname(file)
end
destroy
yield file if file
true
}
show_all
present
end | shows an asynchronous FileChooser window, yields the chosen filename
TODO save last path | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def initialize(owner, title, list, h={})
owner ||= Gtk::Window.toplevels.first
super(title, owner, Gtk::Dialog::DESTROY_WITH_PARENT)
cols = list.shift
treeview = Gtk::TreeView.new
treeview.model = Gtk::ListStore.new(*[String]*cols.length)
treeview.selection.mode = Gtk::SELECTION_NONE
if @color_callback = h[:color_callback]
@drawable = DrawableWidget.new # needed for color()...
@drawable.signal_emit('realize')
end
cols.each_with_index { |col, i|
crt = Gtk::CellRendererText.new
tvc = Gtk::TreeViewColumn.new(col, crt)
tvc.sort_column_id = i
tvc.set_cell_data_func(crt) { |_tvc, _crt, model, iter|
_crt.text = iter[i]
if @color_callback
fu = (0...cols.length).map { |ii| iter[ii] }
fg, bg = @color_callback[fu]
fg ||= :black
bg ||= :white
_crt.foreground = @drawable.color(fg).to_s
_crt.cell_background = @drawable.color(bg).to_s
end
}
treeview.append_column tvc
}
list.each { |e|
iter = treeview.model.append
e.each_with_index { |v, i| iter[i] = v.to_s }
}
treeview.model.set_sort_column_id(0)
treeview.signal_connect('cursor_changed') { |x|
if iter = treeview.selection.selected
yield iter
end
}
treeview.signal_connect('row_activated') { destroy }
signal_connect('destroy') { h[:ondestroy].call } if h[:ondestroy]
remove vbox
add Gtk::ScrolledWindow.new.add(treeview)
toplevel.set_default_size cols.length*240, 400
show if not h[:noshow]
# so that the 1st line is not selected by default
treeview.selection.mode = Gtk::SELECTION_SINGLE
end | shows a window with a list of items
the list is an array of arrays, displayed as String
the first array is the column names
each item clicked yields the block with the selected iterator, double-click also close the popup | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def find_menu(name, from=@menu)
name = name.gsub('_', '')
if not l = from.find { |e| e.grep(::String).find { |es| es.gsub('_', '') == name } }
l = from.map { |e| e.grep(::Array).map { |ae| find_menu(name, ae) }.compact.first }.compact.first
end
l.grep(::Array).first if l
end | finds a menu by name (recursive)
returns a valid arg for addsubmenu(ret) | find_menu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def addsubmenu(menu, *args, &action)
args << action if action
menu << args
menu.last
end | append stuff to a menu
arglist:
empty = menu separator
string = menu entry display name (use a single '_' keyboard for shortcut, eg 'Sho_rtcut' => 'r')
:check = menu entry is a checkbox type, add a true/false argument to specify initial value
second string = keyboard shortcut (accelerator) - use '^' for Ctrl, and '<up>' for special keys
a menu object = this entry will open a submenu (you must specify a name, and action is ignored)
the method takes a block or a Proc argument that will be run whenever the menu item is selected
use @menu to reference the top-level menu bar
call update_menu when the menu is done | addsubmenu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def update_menu
# clear
@menubar.children.dup.each { |mc| @menubar.remove mc }
# populate the menubar using @menu
@menu.each { |e| create_menu_item(@menubar, e) }
@menubar.show_all
end | make the window's MenuBar reflect the content of @menu | update_menu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def messagebox(text, opts={})
opts = {:title => opts} if opts.kind_of? String
mbox = Qt::MessageBox.new#(self)
mbox.text = text
mbox.window_title = opts[:title] if opts[:title]
mbox.window_modality = Qt::NonModal
mbox.show
mbox
end | shows a message box (non-modal)
args: message, title/optionhash | messagebox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def inputbox(prompt, opts={})
ibox = Qt::InputDialog.new#(self)
ibox.label_text = prompt
ibox.window_title = opts[:title] if opts[:title]
ibox.text_value = opts[:text] if opts[:text]
connect(ibox, SIGNAL('TextValueSelected(v)')) { |v| protect { yield v } }
ibox.show
ibox
end | asks for user input, yields the result (unless 'cancel' clicked)
args: prompt, :text => default text, :title => title | inputbox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def openfile(title, opts={})
f = Qt::FileDialog.get_open_file_name(nil, title, @@dialogfilefolder)
if f and f != ''
@@dialogfilefolder = File.dirname(f)
protect { yield f }
end
f # useless, dialog is modal
end | asks to chose a file to open, yields filename
args: title, :path => path | openfile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def savefile(title, opts={})
f = Qt::FileDialog.get_save_file_name(nil, title, @@dialogfilefolder)
if f and f != ''
@@dialogfilefolder = File.dirname(f)
protect { yield f }
end
f # useless, dialog is modal
end | same as openfile, but for writing a (new) file | savefile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def listwindow(title, list, h={})
l = Qt::TreeWidget.new#(self)
l.window_title = title
cols = list.shift
#l.column_count = cols.length
l.header_labels = cols
list.each { |e|
i = Qt::TreeWidgetItem.new
e.length.times { |idx| i.set_text(idx, e[idx].to_s) }
l.add_top_level_item i
}
connect(l, SIGNAL('itemActivated(QTreeWidgetItem*,int)')) { |item, col|
next if not item.is_selected
next if not idx = l.index_of_top_level_item(item)
protect { yield(list[idx].map { |e| e.to_s }) } #if iter = treeview.selection.selected
}
connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*,int)')) { l.close }
l.resize(cols.length*120, 400)
l.show if not h[:noshow]
l
end | shows a window with a list of items
the list is an array of arrays, displayed as String
the first array is the column names
each item clicked yields the block with the selected iterator, double-click also close the popup
args: title, [[col0 title, col1 title...], [col0 val0, col1 val0...], [val1], [val2]...] | listwindow | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def set_font(descr)
descr, sz = descr.split
super(Qt::Font.new(descr, sz.to_i))
@font_width = font_metrics.width('x')
@font_height = font_metrics.line_spacing
@font_descent = font_metrics.descent
gui_update
end | change the font of the widget
arg is a Gtk Fontdescription string (eg 'courier 10') | set_font | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def set_color_association(hash)
hash.each { |k, v| @color[k] = color(v) }
#set_background_role Qt::Palette::Window(color(:background))
palette.set_color(Qt::Palette::Window, color(:background))
gui_update
end | change the color association
arg is a hash function symbol => color symbol
color must be allocated
check #initialize/sig('realize') for initial function/color list | set_color_association | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def update_hl_word(line, offset, mode=:asm)
return if not line
word = line[0...offset].to_s[/\w*$/] << line[offset..-1].to_s[/^\w*/]
word = nil if word == ''
if @hl_word != word
if word
if mode == :asm and defined?(@dasm) and @dasm
re = @dasm.gui_hilight_word_regexp(word)
else
re = Regexp.escape word
end
@hl_word_re = /^(.*?)(\b(?:#{re})\b)/
end
@hl_word = word
end
end | update @hl_word from a line & offset, return nil if unchanged | update_hl_word | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/qt.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/qt.rb | BSD-3-Clause |
def messagebox(*a)
MessageBox.new(toplevel, *a)
end | shows a message box (non-modal)
args: message, title/optionhash | messagebox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def inputbox(*a)
InputBox.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | asks for user input, yields the result (unless 'cancel' clicked)
args: prompt, :text => default text, :title => title | inputbox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def openfile(*a)
OpenFile.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | asks to chose a file to open, yields filename
args: title, :path => path | openfile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def savefile(*a)
SaveFile.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | same as openfile, but for writing a (new) file | savefile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def listwindow(*a)
ListWindow.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | displays a popup showing a table, yields the selected row
args: title, [[col0 title, col1 title...], [col0 val0, col1 val0...], [val1], [val2]...] | listwindow | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def initialize(text='Ok', c1=:palegrey, c2=:grey, &b)
@x = @y = @w = @h = 0
@c1, @c2 = c1, c2
@text = text
@down = false
@action = b
end | create a new Button with the specified text & border color | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def paint(w)
c1, c2 = @c1, @c2
c1, c2 = c2, c1 if @down
w.draw_string_color(:text, @x+(@w-w.font_width*@text.length)/2, @y+(@h - w.font_height)/2, @text)
w.draw_line_color(c1, @x, @y, @x, @y+@h)
w.draw_line_color(c1, @x, @y, @x+@w, @y)
w.draw_line_color(c2, @x+@w, @y+@h, @x, @y+@h)
w.draw_line_color(c2, @x+@w, @y+@h, @x+@w, @y)
end | draw the button on the parent widget | paint | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def click(x, y)
@down = true if x >= @x and x < @x+@w and y >= @y and y < @y+@h
end | checks if the click is on the button, returns true if so | click | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def add_button(text='Ok', *a, &b)
@buttons ||= []
@buttons << Button.new(text, *a, &b)
end | add a new button to the widget | add_button | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def paint_buttons
@buttons.each { |b| b.paint(self) }
end | render the buttons on the widget
should be called during #paint | paint_buttons | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def click_buttons(x, y)
@buttons.find { |b| b.click(x, y) }
end | checks if the click is inside a button, returns true if it is
should be called during #click | click_buttons | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def mouserelease_buttons(x, y)
@buttons.find { |b| b.mouserelease(x, y) }
end | the mouse was released, call button action if it is pressed
should be called during #mouserelease | mouserelease_buttons | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def windowproc(hwnd, msg, wparam, lparam)
#puts "wproc #{'%x' % hwnd} #{MSGNAME[msg] || msg} #{'%x' % wparam} #{'%x' % lparam}" if not %w[WM_NCHITTEST WM_SETCURSOR WM_MOUSEMOVE WM_NCMOUSEMOVE].include? MSGNAME[msg]
@hwnd ||= hwnd # some messages are sent before createwin returns
case msg
when Win32Gui::WM_NCHITTEST, Win32Gui::WM_SETCURSOR
# most frequent messages (with MOUSEMOVE)
return Win32Gui.defwindowproca(hwnd, msg, wparam, lparam)
when Win32Gui::WM_MOUSEMOVE, Win32Gui::WM_LBUTTONDOWN, Win32Gui::WM_RBUTTONDOWN,
Win32Gui::WM_LBUTTONDBLCLK, Win32Gui::WM_MOUSEWHEEL, Win32Gui::WM_LBUTTONUP
mouse_msg(msg, wparam, lparam)
when Win32Gui::WM_PAINT
ps = Win32Gui.alloc_c_struct('PAINTSTRUCT')
hdc = Win32Gui.beginpaint(hwnd, ps)
if @widget
@widget.paint_(hdc)
else
Win32Gui.selectobject(hdc, Win32Gui.getstockobject(Win32Gui::DC_BRUSH))
Win32Gui.selectobject(hdc, Win32Gui.getstockobject(Win32Gui::DC_PEN))
col = Win32Gui.getsyscolor(Win32Gui::COLOR_BTNFACE)
Win32Gui.setdcbrushcolor(hdc, col)
Win32Gui.setdcpencolor(hdc, col)
Win32Gui.rectangle(hdc, 0, 0, @width, @height)
end
Win32Gui.endpaint(hwnd, ps)
when Win32Gui::WM_MOVE
rect = Win32Gui.alloc_c_struct('RECT')
Win32Gui.getwindowrect(@hwnd, rect)
@x, @y, @width, @height = rect[:left], rect[:top], rect[:right]-rect[:left], rect[:bottom]-rect[:top]
@clientx = lparam & 0xffff
@clienty = (lparam >> 16) & 0xffff
when Win32Gui::WM_SIZE
rect = Win32Gui.alloc_c_struct('RECT')
Win32Gui.getwindowrect(@hwnd, rect)
@x, @y, @width, @height = rect[:left], rect[:top], rect[:right]-rect[:left], rect[:bottom]-rect[:top]
@clientwidth = lparam & 0xffff
@clientheight = (lparam >> 16) & 0xffff
@widget.resized_(lparam & 0xffff, (lparam >> 16) & 0xffff) if @widget
redraw
when Win32Gui::WM_WINDOWPOSCHANGING
if @popups.first
# must move popups to top before updating hwndInsertafter
f = Win32Gui::SWP_NOACTIVATE | Win32Gui::SWP_NOMOVE | Win32Gui::SWP_NOSIZE |
Win32Gui::SWP_NOOWNERZORDER | Win32Gui::SWP_NOSENDCHANGING
@popups.each { |pw| Win32Gui.setwindowpos(pw.hwnd, Win32Gui::HWND_TOP, 0, 0, 0, 0, f) }
Win32Gui.memory_write_int(lparam+Win32Gui.cp.typesize[:ptr], @popups.first.hwnd)
end
when Win32Gui::WM_SHOWWINDOW
initialize_visible_
when Win32Gui::WM_KEYDOWN, Win32Gui::WM_SYSKEYDOWN
# SYSKEYDOWN for f10 (default = activate the menu bar)
if key = Keyboard_trad[wparam]
if [?+, ?-, ?/, ?*].include?(key)
# keypad keys generate wm_keydown + wm_char, ignore this one
elsif keyboard_state(:control)
@widget.keypress_ctrl_(key) if @widget
else
@widget.keypress_(key) if @widget
end
end
Win32Gui.defwindowproca(hwnd, msg, wparam, lparam) if key != :f10 # alt+f4 etc
when Win32Gui::WM_CHAR
if keyboard_state(:control) and not keyboard_state(:alt) # altgr+[ returns CTRL on..
if ?a.kind_of?(String)
wparam += (keyboard_state(:shift) ? ?A.ord : ?a.ord) - 1 if wparam < 0x1a
key = wparam.chr
else
wparam += (keyboard_state(:shift) ? ?A : ?a) - 1 if wparam < 0x1a
key = wparam
end
@widget.keypress_ctrl_(key) if @widget
else
key = (?a.kind_of?(String) ? wparam.chr : wparam)
@widget.keypress_(key) if @widget
end
when Win32Gui::WM_DESTROY
destroy_window
when Win32Gui::WM_COMMAND
if a = @control_action[wparam]
protect { a.call }
end
when Win32Gui::WM_DROPFILES
cnt = Win32Gui.dragqueryfilea(wparam, -1, 0, 0)
cnt.times { |i|
buf = [0].pack('C')*1024
len = Win32Gui.dragqueryfilea(wparam, i, buf, buf.length)
protect { @widget.dragdropfile(buf[0, len]) } if @widget and @widget.respond_to? :dragdropfile
}
Win32Gui.dragfinish(wparam)
else return Win32Gui.defwindowproca(hwnd, msg, wparam, lparam)
end
0
end | MSGNAME = Win32Gui.cp.lexer.definition.keys.grep(/WM_/).sort.inject({}) { |h, c| h.update Win32Gui.const_get(c) => c } | windowproc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def find_menu(name, from=@menu)
name = name.gsub('_', '')
if not l = from.find { |e| e.grep(::String).find { |es| es.gsub('_', '') == name } }
l = from.map { |e| e.grep(::Array).map { |ae| find_menu(name, ae) }.compact.first }.compact.first
end
l.grep(::Array).first if l
end | finds a menu by name (recursive)
returns a valid arg for addsubmenu(ret) | find_menu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def addsubmenu(menu, *args, &action)
args << action if action
menu << args
menu.last
end | append stuff to a menu
arglist:
empty = menu separator
string = menu entry display name (use a single '_' keyboard for shortcut, eg 'Sho_rtcut' => 'r')
:check = menu entry is a checkbox type, add a true/false argument to specify initial value
second string = keyboard shortcut (accelerator) - use '^' for Ctrl, and '<up>' for special keys
a menu object = this entry will open a submenu (you must specify a name, and action is ignored)
the method takes a block or a Proc argument that will be run whenever the menu item is selected
use @menu to reference the top-level menu bar
call update_menu when the menu is done | addsubmenu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def update_menu
unuse_menu(@menu)
Win32Gui.destroymenu(@menuhwnd) if @menuhwnd != 0
@menuhwnd = Win32Gui.createmenu()
@menu.each { |e| create_menu_item(@menuhwnd, e) }
Win32Gui.setmenu(@hwnd, @menuhwnd)
end | make the window's MenuBar reflect the content of @menu | update_menu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/win32.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/win32.rb | BSD-3-Clause |
def initialize(target, do_attach=true, &b)
case do_attach
when :create
init_create(target, &b)
when :attach
init_attach(target)
when :dup
raise ArgumentError unless target.kind_of?(PTrace)
@pid = target.pid
tweak_for_pid(@pid, target.tgcpu) # avoid re-parsing /proc/self/exe
when nil, false
@pid = Integer(target)
tweak_for_pid(@pid)
else
t = begin; Integer(target)
rescue ArgumentError, TypeError
end
t ? init_attach(t) : init_create(target, &b)
end
end | creates a ptraced process (target = path)
or opens a running process (target = pid)
values for do_attach:
:create => always fork+traceme+exec+wait
:attach => always attach
false/nil => same as attach, without actually calling PT_ATTACH (useful when the ruby process is already tracing pid)
default/anything else: try to attach if pid is numeric, else create | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def tweak_for_pid(pid=@pid, tgcpu=nil)
# use these for our syscalls PTRACE
@@host_csn ||= LinOS.open_process(::Process.pid).cpu.shortname
case @@host_csn
when 'ia32'
@packint = 'l'
@packuint = 'L'
@host_intsize = 4
@host_syscallnr = SYSCALLNR_I386
@reg_off = REGS_I386
when 'x64'
@packint = 'q'
@packuint = 'Q'
@host_intsize = 8
@host_syscallnr = SYSCALLNR_X86_64
@reg_off = REGS_X86_64
else raise 'unsupported architecture'
end
@tgcpu = tgcpu || LinOS.open_process(pid).cpu
# use these to interpret the child state
case @tgcpu.shortname
when 'ia32'
@syscallreg = 'ORIG_EAX'
@syscallnr = SYSCALLNR_I386
@intsize = 4
when 'x64'
@syscallreg = 'ORIG_RAX'
@syscallnr = SYSCALLNR_X86_64
@intsize = 8
else raise 'unsupported target architecture'
end
# buffer used in ptrace syscalls
@buf = [0].pack(@packint)
@sys_ptrace = @@sys_ptrace[@host_syscallnr['ptrace']] ||= setup_sys_ptrace(@host_syscallnr['ptrace'])
end | setup variables according to the target (ptrace interface, syscall nrs, ...) | tweak_for_pid | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def geteventmsg
sys_ptrace(COMMAND[:GETEVENTMSG], @pid, 0, @buf)
bufval
end | retrieve pid of cld for EVENT_CLONE/FORK, exitcode for EVENT_EXIT | geteventmsg | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def modules
list = []
seen = {}
File.readlines("/proc/#{pid}/maps").each { |l|
# 08048000-08064000 r-xp 000000 08:01 4234 /usr/bin/true
l = l.split
next if l.length < 6 or seen[l[-1]]
seen[l[-1]] = true
m = Module.new
m.addr = l[0].to_i(16)
m.path = l[-1]
list << m
}
list
rescue
[]
end | returns the list of loaded Modules, incl start address & path
read from /proc/pid/maps | modules | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def mappings
list = []
File.readlines("/proc/#{pid}/maps").each { |l|
l = l.split
addrstart, addrend = l[0].split('-').map { |i| i.to_i 16 }
list << [addrstart, addrend-addrstart, l[1], l[5]]
}
list
rescue
[]
end | return a list of [addr_start, length, perms, file] | mappings | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def threads
Dir.entries("/proc/#{pid}/task/").grep(/^\d+$/).map { |tid| tid.to_i }
rescue
# TODO handle pthread stuff (eg 2.4 kernels)
[pid]
end | returns a list of threads sharing this process address space
read from /proc/pid/task/ | threads | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def cmdline
@cmdline ||= File.read("/proc/#{pid}/cmdline") rescue ''
end | return the invocation commandline, from /proc/pid/cmdline
this is manipulable by the target itself | cmdline | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def cpu
e = ELF.load_file("/proc/#{pid}/exe")
# dont decode shdr/phdr, this is 2x faster for repeated debugger spawn
e.decode_header(0, false, false)
e.cpu
end | returns the CPU for the process, by reading /proc/pid/exe | cpu | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def list_processes
Dir.entries('/proc').grep(/^\d+$/).map { |pid| Process.new(pid.to_i) }
end | returns an array of Processes, with pid/module listing | list_processes | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def open_process(pid)
Process.new(pid) if check_process(pid)
end | return a Process for the specified pid if it exists in /proc | open_process | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def initialize(pid, addr_start=0, length=nil, dbg=nil)
@pid = pid
length ||= 1 << (dbg ? dbg.cpu.size : (LinOS.open_process(@pid).addrsz rescue 32))
@readfd = File.open("/proc/#@pid/mem", 'rb') rescue nil
@dbg = dbg if dbg
super(addr_start, length)
end | returns a virtual string proxying the specified process memory range
reads are cached (4096 aligned bytes read at once), from /proc/pid/mem
writes are done directly by ptrace | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def gpr_sub_init
ret = {}
%w[a b c d].each { |r|
b = "e#{r}x".to_sym
ret["#{r}x".to_sym] = [b, 0xffff]
ret["#{r}l".to_sym] = [b, 0xff]
ret["#{r}h".to_sym] = [b, 0xff, 8]
}
%w[sp bp si di].each { |r|
b = "e#{r}".to_sym
ret[r.to_sym] = [b, 0xffff]
}
ret[:orig_rax] = [:orig_eax, 0xffff_ffff]
ret
end | :bh => [:ebx, 0xff, 8]
XXX similar to Reg.symbolic... DRY | gpr_sub_init | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def attach(pid, do_attach=:attach)
pt = PTrace.new(pid, do_attach)
set_context(pt.pid, pt.pid) # swapout+init_newpid
log "attached #@pid"
list_threads.each { |tid| attach_thread(tid) if tid != @pid }
set_tid @pid
end | attach to a running process and all its threads | attach | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def create_process(path, &b)
pt = PTrace.new(path, :create, &b)
# TODO save path, allow restart etc
set_context(pt.pid, pt.pid) # swapout+init_newpid
log "attached #@pid"
end | create a process and debug it
if given a block, the block is run in the context of the ruby subprocess
after the fork() and before exec()ing the target binary
you can use it to eg tweak file descriptors:
tg_stdin_r, tg_stdin_w = IO.pipe
create_process('/bin/cat') { tg_stdin_w.close ; $stdin.reopen(tg_stdin_r) }
tg_stdin_w.write 'lol' | create_process | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def hack_x64_32
log "WARNING: debugging a 64bit process from a 32bit debugger is a very bad idea !"
ia32 = Ia32.new
@cpu.instance_variable_set('@dbg_register_pc', ia32.dbg_register_pc)
@cpu.instance_variable_set('@dbg_register_sp', ia32.dbg_register_sp)
@cpu.instance_variable_set('@dbg_register_flags', ia32.dbg_register_flags)
@cpu.instance_variable_set('@dbg_register_list', ia32.dbg_register_list)
@cpu.instance_variable_set('@dbg_register_size', ia32.dbg_register_size)
end | We're a 32bit process debugging a 64bit target
the ptrace kernel interface we use only allow us a 32bit-like target access
With this we advertize the cpu as having eax..edi registers (the only one we
can access), while still decoding x64 instructions (whose addr < 4G) | hack_x64_32 | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def attach_thread(tid)
set_tid tid
@ptrace.pid = tid
@ptrace.attach
@state = :stopped
# store this waitpid so that we can return it in a future check_target
::Process.waitpid(tid, ::Process::WALL)
# XXX can $? be safely stored?
@cached_waitpid << [tid, $?.dup]
log "attached thread #{tid}"
set_thread_options
rescue Errno::ESRCH
# raced, thread quitted already
del_tid
end | attach a thread of the current process | attach_thread | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def set_thread_options
opts = %w[TRACESYSGOOD TRACECLONE TRACEEXEC TRACEEXIT]
opts += %w[TRACEFORK TRACEVFORK TRACEVFORKDONE] if trace_children
@ptrace.pid = @tid
@ptrace.setoptions(*opts)
end | set the debugee ptrace options (notify clone/exec/exit, and fork/vfork depending on @trace_children) | set_thread_options | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def do_trace_children
each_tid { set_thread_options }
end | update the current pid relative to tracing children (@trace_children only effects newly traced pid/tid) | do_trace_children | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def syscall(arg=nil)
arg = nil if arg and arg.strip == ''
if b = check_breakpoint_cause and b.hash_shared.find { |bb| bb.state == :active }
singlestep_bp(b) {
next if not check_pre_run(:syscall, arg)
@target_syscall = arg
@state = :running
@ptrace.pid = @tid
@ptrace.syscall(@continuesignal)
}
else
return if not check_pre_run(:syscall, arg)
@target_syscall = arg
@state = :running
@ptrace.pid = @tid
@ptrace.syscall(@continuesignal)
end
end | use the PT_SYSCALL to break on next syscall
regexp allowed to wait a specific syscall | syscall | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def singleblock
# record as singlestep to avoid evt_singlestep -> evt_exception
# step or block doesn't matter much here anyway
if b = check_breakpoint_cause and b.hash_shared.find { |bb| bb.state == :active }
singlestep_bp(b) {
next if not check_pre_run(:singlestep)
@state = :running
@ptrace.pid = @tid
@ptrace.singleblock(@continuesignal)
}
else
return if not check_pre_run(:singlestep)
@state = :running
@ptrace.pid = @tid
@ptrace.singleblock(@continuesignal)
end
end | use the PT_SINGLEBLOCK to execute until the next branch | singleblock | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def evt_exec(info={})
@state = :stopped
@info = "#{info[:exec]} execve"
initialize_newpid
# XXX will receive a SIGTRAP, could hide it..
callback_exec[info] if callback_exec
# calling continue() here will loop back to TRAP+INFO_EXEC
end | called during sys_execve in the new process | evt_exec | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def do_enable_bp(b)
super(b)
rescue ::Errno::EIO
if b.type == :bpx
@memory[b.address, 1] # check if we can read
# didn't raise: it's a PaX-style config
@has_pax_mprotect = true
b.del
hwbp(b.address, :x, 1, b.oneshot, b.condition, &b.action)
log 'PaX: bpx->hwbp'
else raise
end
end | handles exceptions from PaX-style mprotect restrictions on bpx,
transmute them to hwbp on the fly | do_enable_bp | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/linux.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/linux.rb | BSD-3-Clause |
def method_missing(m, *args, &b)
if ''.respond_to? m
puts "Using VirtualString.realstring for #{m} from:", caller if $DEBUG
realstring.freeze.send(m, *args, &b)
else
super(m, *args, &b)
end
end | forwards unhandled messages to a frozen realstring | method_missing | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def empty?
length == 0
end | avoid triggering realstring from method_missing if possible | empty? | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def index(chr, base=0)
return if base >= length or base <= -length
if i = self[base, 64].index(chr) or i = self[base, @pagelength].index(chr)
base + i
else
realstring.index(chr, base)
end
end | avoid triggering realstring from method_missing if possible
heavily used in to find 0-terminated strings in ExeFormats | index | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def cache_get_page(addr)
addr &= ~(@pagelength-1)
i = 0
@pagecache.each { |c|
if addr == c[0]
# most recently used first
@pagecache.unshift @pagecache.delete_at(i) if i != 0
return c
end
i += 1
}
@pagecache.pop if @pagecache.length >= @pagecache_len
c = [addr]
p = get_page(addr)
c << p.to_s.ljust(@pagelength, "\0")
c << true if not p
@pagecache.unshift c
c
end | returns the @pagelength-bytes page starting at addr
return nil if the page is invalid/inaccessible
addr is page-aligned by the caller
addr is absolute
def get_page(addr, len=@pagelength)
end
searches the cache for a page containing addr, updates if not found | cache_get_page | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def read_range(from, len)
from += @addr_start
if not len
base, page = cache_get_page(from)
page[from - base]
elsif len <= @pagelength
base, page = cache_get_page(from)
s = page[from - base, len]
if from+len-base > @pagelength # request crosses a page boundary
base, page = cache_get_page(from+len)
s << page[0, from+len-base]
end
s
else
# big request: return a new virtual page
dup(from, len)
end
end | reads a range from the page cache
returns a new VirtualString (using dup) if the request is bigger than @pagelength bytes | read_range | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def write_range(from, content)
invalidate
rewrite_at(from + @addr_start, content)
end | rewrites a segment of data
the length written is the length of the content (a VirtualString cannot grow/shrink) | write_range | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def initialize(fd, addr_start = 0, length = nil)
@fd = fd
if not length
@fd.seek(0, File::SEEK_END)
length = @fd.tell - addr_start
end
super(addr_start, length)
end | creates a new virtual mapping of a section of the file
the file descriptor must be seekable | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def get_page(addr, len=@pagelength)
@fd.pos = addr
@fd.read len
end | reads an aligned page from the file, at file offset addr | get_page | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def realstring
@fd.pos = @addr_start
@fd.read(@length)
end | returns the full content of the file | realstring | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/main.rb | BSD-3-Clause |
def gdb_csum(buf)
'%02x' % (buf.unpack('C*').inject(0) { |cs, c| cs + c } & 0xff)
end | compute the hex checksum used in gdb protocol | gdb_csum | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def gdb_send(cmd, buf='')
buf = cmd + buf
buf = '$' << buf << '#' << gdb_csum(buf)
log "gdb_send #{buf.inspect}" if $DEBUG
5.times {
@io.write buf
out = ''
loop do
break if not IO.select([@io], nil, nil, 0.2)
raise Errno::EPIPE if not ack = @io.read(1)
case ack
when '+'
return true
when '-'
log "gdb_send: ack neg" if $DEBUG
break
when nil
return
else
out << ack
end
end
log "no ack, got #{out.inspect}" if out != ''
}
log "send error #{cmd.inspect} (no ack)"
false
end | send the buffer, waits ack
return true on success | gdb_send | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def gdb_readresp(timeout=nil, outstr=nil)
@recv_ctx ||= {}
@recv_ctx[:state] ||= :nosync
buf = nil
while @recv_ctx
if !@recv_ctx[:rbuf]
return unless IO.select([@io], nil, nil, timeout)
if @io.kind_of?(UDPSocket)
raise Errno::EPIPE if not @recv_ctx[:rbuf] = @io.recvfrom(65536)[0]
else
raise Errno::EPIPE if not c = @io.read(1)
end
end
if @recv_ctx[:rbuf]
c = @recv_ctx[:rbuf].slice!(0, 1)
@recv_ctx.delete :rbuf if @recv_ctx[:rbuf] == ''
end
case @recv_ctx[:state]
when :nosync
if c == '$'
@recv_ctx[:state] = :data
@recv_ctx[:buf] = ''
end
when :data
if c == '#'
@recv_ctx[:state] = :csum1
@recv_ctx[:cs] = ''
else
@recv_ctx[:buf] << c
end
when :csum1
@recv_ctx[:cs] << c
@recv_ctx[:state] = :csum2
when :csum2
cs = @recv_ctx[:cs] << c
buf = @recv_ctx[:buf]
@recv_ctx = nil
if cs.downcase == gdb_csum(buf).downcase
@io.write '+'
else
log "transmit error"
@io.write '-'
return
end
end
end
case buf
when /^E(..)$/
e = $1.to_i(16)
log "error #{e} (#{PTrace::ERRNO.index(e)})"
return
when /^O([0-9a-fA-F]*)$/
if not outstr
first = true
outstr = ''
end
outstr << unhex($1)
ret = gdb_readresp(timeout, outstr)
outstr.split("\n").each { |o| log 'gdb: ' + o } if first
return ret
end
log "gdb_readresp: got #{buf[0, 64].inspect}#{'...' if buf.length > 64}" if $DEBUG
buf
end | return buf, or nil on error / csum error
waits IO.select(timeout) between each char
outstr is used internally only to handle multiline output string | gdb_readresp | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def rle(buf)
buf.gsub(RLE_RE) {
chr, len = $1, $2.length+1
chr + '*' + (len+28).chr
}
end | rle-compress a buffer
a character followed by '*' followed by 'x' is asc(x)-28 repetitions of the char
eg '0* ' => '0' * (asc(' ') - 28) = '0000'
for the count character, it must be 32 <= char < 126 and not be '+' '-' '#' or '$' | rle | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def unhex(buf)
buf = buf[/^[a-fA-F0-9]*/]
buf = '0' + buf if buf.length & 1 == 1
[buf].pack('H*')
end | decode an rle hex-encoded buffer | unhex | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def request_symbol(name)
resp = gdb_msg('qSymbol:', hex(name))
if resp and a = resp.split(':')[1]
@unpack_netint[unhex(a)].first
end
end | use qSymbol to retrieve a symbol value (uint) | request_symbol | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def setup_arch(cpu)
@ptrsz = cpu.size
case cpu.shortname
when /^ia32/
@ptrsz = 32
@gdbregs = GDBREGS_IA32
@regmsgsize = 4 * @gdbregs.length
when 'x64'
@gdbregs = GDBREGS_X64
@regmsgsize = 8 * @gdbregs.length
when 'arm'
@gdbregs = cpu.dbg_register_list
@regmsgsize = 4 * @gdbregs.length
when 'mips'
@gdbregs = cpu.dbg_register_list
@regmsgsize = cpu.size/8 * @gdbregs.length
else
# we can still use readmem/kill and other generic commands
# XXX serverside setregs may fail if we give an incorrect regbuf size
puts "unsupported GdbServer CPU #{cpu.shortname}"
@gdbregs = [*0..32].map { |i| "r#{i}".to_sym }
@regmsgsize = 0
end
# yay life !
# do as if cpu is littleendian, fixup at the end
case @ptrsz
when 16
@pack_netint = lambda { |i| i.pack('n*') }
@unpack_netint = lambda { |s| s.unpack('n*') }
@pack_int = lambda { |i| i.pack('v*') }
@unpack_int = lambda { |s| s.unpack('v*') }
when 32
@pack_netint = lambda { |i| i.pack('N*') }
@unpack_netint = lambda { |s| s.unpack('N*') }
@pack_int = lambda { |i| i.pack('V*') }
@unpack_int = lambda { |s| s.unpack('V*') }
when 64
bswap = lambda { |s| s.scan(/.{8}/m).map { |ss| ss.reverse }.join }
@pack_netint = lambda { |i| i.pack('Q*') }
@unpack_netint = lambda { |s| s.unpack('Q*') }
@pack_int = lambda { |i| bswap[i.pack('Q*')] }
@unpack_int = lambda { |s| bswap[s].unpack('Q*') }
if [1].pack('Q')[0] == ?\1 # ruby interpreter littleendian
@pack_netint, @pack_int = @pack_int, @pack_netint
@unpack_netint, @unpack_int = @unpack_int, @unpack_netint
end
else raise "GdbServer: unsupported cpu size #{@ptrsz}"
end
# if target cpu is bigendian, use netint everywhere
if cpu.endianness == :big
@pack_int = @pack_netint
@unpack_int = @unpack_netint
end
end | setup the various function used to pack ints & the reg list
according to a target CPU | setup_arch | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/remote.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/remote.rb | BSD-3-Clause |
def addrsz
@addrsz ||= if WinAPI.respond_to?(:iswow64process)
byte = 0.chr*8
if WinAPI.iswow64process(handle, byte)
if byte != 0.chr*8
32 # target = wow64
elsif WinAPI.iswow64process(WinAPI.getcurrentprocess, byte) and byte != 0.chr*8
64 # us = wow64, target is not
else
WinAPI.host_cpu.size
end
else
WinAPI.host_cpu.size
end
end
end | returns the memory address size of the target process | addrsz | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def teb_base
@teb_base ||=
if WinAPI.respond_to?(:ntqueryinformationthread)
tinfo = WinAPI.alloc_c_struct('THREAD_BASIC_INFORMATION')
if WinAPI.ntqueryinformationthread(handle, WinAPI::THREADBASICINFORMATION, tinfo, tinfo.sizeof, 0) == 0
tinfo.tebbaseaddress
end
else
fs = context { |c| c[:fs] }
ldte = WinAPI.alloc_c_struct('LDT_ENTRY')
if WinAPI.getthreadselectorentry(handle, fs, ldte)
ldte.baselow | (ldte.basemid << 16) | (ldte.basehi << 24)
end
end
end | return the address of the TEB for the target thread | teb_base | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def suspend
if WinAPI.host_cpu.size == 64 and process and process.addrsz == 32
WinAPI.wow64suspendthread(handle)
else
WinAPI.suspendthread(handle)
end
end | increment the suspend count of the target thread - stop at >0 | suspend | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def context
@context ||= Context.new(self, :all)
if block_given?
suspend
begin
@context.update
yield @context
ensure
resume
end
else
@context
end
end | returns a Context object. Can be reused, refresh the values with #update (target thread must be suspended)
if a block is given, suspend the thread, update the context, yield it, and resume the thread | context | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def update
WinAPI.send(@getcontext, @handle, @context)
end | update the context to reflect the current thread reg values
call only when the thread is suspended | update | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def get_debug_privilege
# TODO use real structs / new_func_c
htok = [0].pack('L')
return if not WinAPI.openprocesstoken(WinAPI.getcurrentprocess(), WinAPI::TOKEN_ADJUST_PRIVILEGES | WinAPI::TOKEN_QUERY, htok)
luid = [0, 0].pack('LL')
return if not WinAPI.lookupprivilegevaluea(nil, WinAPI::SE_DEBUG_NAME, luid)
# priv.PrivilegeCount = 1;
# priv.Privileges[0].Luid = luid;
# priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
priv = luid.unpack('LL').unshift(1).push(WinAPI::SE_PRIVILEGE_ENABLED).pack('LLLL')
return if not WinAPI.adjusttokenprivileges(htok.unpack('L').first, 0, priv, 0, nil, nil)
true
end | try to enable debug privilege in current process | get_debug_privilege | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def list_processes
h = WinAPI.createtoolhelp32snapshot(WinAPI::TH32CS_SNAPPROCESS, 0)
list = []
pe = WinAPI.alloc_c_struct('PROCESSENTRY32', :dwsize => :size)
return if not WinAPI.process32first(h, pe)
loop do
p = Process.new(pe.th32processid)
p.ppid = pe.th32parentprocessid
p.path = pe.szexefile.to_strz
list << p if p.pid != 0
break if WinAPI.process32next(h, pe) == 0
end
WinAPI.closehandle(h)
list
end | returns an array of Processes with pid/ppid/path filled | list_processes | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def list_modules(pid)
h = WinAPI.createtoolhelp32snapshot(WinAPI::TH32CS_SNAPMODULE, pid)
return [] if h == WinAPI::INVALID_HANDLE_VALUE
list = []
me = WinAPI.alloc_c_struct('MODULEENTRY32', :dwsize => :size)
return [] if not WinAPI.module32first(h, me)
loop do
m = Process::Module.new
m.addr = me.modbaseaddr
m.size = me.modbasesize
m.path = me.szexepath.to_strz
list << m
break if WinAPI.module32next(h, me) == 0
end
WinAPI.closehandle(h)
list
end | retrieve the list of Modules for a process with addr/size/path filled | list_modules | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def list_threads(pid=nil)
h = WinAPI.createtoolhelp32snapshot(WinAPI::TH32CS_SNAPTHREAD, 0)
list = []
te = WinAPI.alloc_c_struct('THREADENTRY32', :dwsize => :size)
return [] if not WinAPI.thread32first(h, te)
loop do
list << te.th32threadid if not pid or te.th32ownerprocessid == pid
break if WinAPI.thread32next(h, te) == 0
end
WinAPI.closehandle(h)
list
end | returns the list of thread ids of the system, optionally filtering by pid | list_threads | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def list_heaps(pid)
h = WinAPI.createtoolhelp32snapshot(WinAPI::TH32CS_SNAPHEAPLIST, pid)
return [] if h == WinAPI::INVALID_HANDLE_VALUE
ret = {}
he = WinAPI.alloc_c_struct('HEAPLIST32', :dwsize => :size)
return [] if not WinAPI.heap32listfirst(h, he)
loop do
hash = ret[he.th32heapid] = { :flags => he.dwflags }
hash[:default] = true if hash[:flags] & WinAPI::HF32_DEFAULT == WinAPI::HF32_DEFAULT
hash[:shared] = true if hash[:flags] & WinAPI::HF32_SHARED == WinAPI::HF32_SHARED
# TODO there are lots of other flags in there ! like 0x1000 / 0x8000
break if WinAPI.heap32listnext(h, he) == 0
end
WinAPI.closehandle(h)
ret
end | returns the heaps of the process, from a toolhelp snapshot SNAPHEAPLIST
this is a hash
heap_addr => { :flags => integer (heap flags)
:shared => bool (from flags)
:default => bool (from flags) } | list_heaps | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def inject_shellcode(target, shellcode)
raise 'cannot open target memory' if not remote_mem = target.memory
return if not injectaddr = WinAPI.virtualallocex(target.handle, 0, shellcode.length,
WinAPI::MEM_COMMIT | WinAPI::MEM_RESERVE, WinAPI::PAGE_EXECUTE_READWRITE)
puts 'remote buffer at %x' % injectaddr if $VERBOSE
if shellcode.kind_of? EncodedData
fixup_shellcode_relocs(shellcode, target, remote_mem)
shellcode.fixup! shellcode.binding(injectaddr)
r = shellcode.reloc.values.map { |r_| r_.target }
raise "unresolved shellcode relocs #{r.join(', ')}" if not r.empty?
shellcode = shellcode.data
end
# inject the shellcode
remote_mem[injectaddr, shellcode.length] = shellcode
injectaddr
end | Injects a shellcode into the memory space of targetproc
target is a WinOS::Process
shellcode may be a String (raw shellcode) or an EncodedData
With an EncodedData, unresolved relocations are solved using
exports of modules from the target address space ; also the
shellcode need not be position-independant. | inject_shellcode | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def createthread(target, startaddr)
WinAPI.createremotethread(target.handle, 0, 0, startaddr, 0, 0, 0)
end | creates a new thread in the target process, with the specified start address | createthread | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def open_process_handle(h)
pid = WinAPI.getprocessid(h) rescue 0
Process.new(pid, h)
end | returns a Process associated to the process handle | open_process_handle | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def open_process(pid)
Process.new(pid) if check_process(pid)
end | returns the Process associated to pid if it is alive | open_process | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def check_process(pid)
if h = WinAPI.openprocess(WinAPI::PROCESS_QUERY_INFORMATION, 0, pid)
WinAPI.closehandle(h)
true
end
end | returns true if the process pid exists and we can open it with QUERY_INFORMATION | check_process | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def open_thread(tid)
Thread.new(tid) if check_tid(tid)
end | returns the Thread associated to a tid if it is alive | open_thread | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def check_tid(tid, pid=nil)
if h = WinAPI.openthread(WinAPI::THREAD_QUERY_INFORMATION, 0, tid)
WinAPI.closehandle(h)
not pid or list_threads(pid).include?(tid)
end
end | check if the thread is alive and can be read with QUERY_INFO
and optionally if it belongs to pid | check_tid | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def version
v = WinAPI.getversion
[v & 0xff, (v>>8) & 0xff]
end | returns the [major, minor] version of the windows os | version | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def initialize(handle, addr_start=0, length=nil)
@handle = handle
length ||= 1 << (WinOS.open_process_handle(@handle).addrsz rescue 32)
super(addr_start, length)
end | returns a virtual string proxying the specified process memory range
reads are cached (4096 aligned bytes read at once)
writes are done directly (if handle has appropriate privileges) | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def initialize_osprocess
initialize_cpu
initialize_memory
initialize_disassembler
end | called whenever we receive a handle to a new process being debugged, after initialisation of @os_process | initialize_osprocess | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def del_tid_notid
nil while do_waitfordebug(10) and !@tid
end | do nothing, windows will send us a EXIT_PROCESS event | del_tid_notid | ruby | stephenfewer/grinder | node/lib/metasm/metasm/os/windows.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/os/windows.rb | BSD-3-Clause |
def show(pfx, str)
loop do
if str.length > 79
len = 79 - str[0...79][/\S+$/].to_s.length
len = 79 if len == 0
puts pfx + str[0...len]
str = str[len..-1]
else
puts pfx + str
break
end
end
end | prints the string in 80 cols
with the first column filled with +pfx+ | show | ruby | stephenfewer/grinder | node/lib/metasm/misc/hexdiff.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/hexdiff.rb | BSD-3-Clause |
def scan_for(targets, path='', done={})
done[object_id] = self if done.empty?
if t = targets.find { |t_| self == t_ }
puts "found #{t} at #{path}"
end
scan_iter { |v, p|
case v
when Fixnum, Symbol; next
end
p = path+p
if done[v.object_id]
puts "loop #{p} -> #{done[v.object_id]}" if $VERBOSE
else
done[v.object_id] = p
v.scan_for(targets, p, done)
end
}
end | dumps to stdout the path to find some targets ( array of objects to match with == ) | scan_for | ruby | stephenfewer/grinder | node/lib/metasm/misc/objscan.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/objscan.rb | BSD-3-Clause |
def read(str)
@str = str
@off = 0
readhdr
raise 'bad pdf: no trailer' unless @off = @str.rindex("trailer", @str.length)
readtrailer
self
end | reads a string as a PDF, interpret basic informations (header, trailer, xref table) | read | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def readtrailer
toff = @off
readcmd
@trailer = readhash
readcmd
@xroff = readint
@xoff = {} # [gen] => { id => off }
@xrefs = {} # [gen] => { id => obj }
@off = @xroff
readcmd
readxrtable
off2 = @off
if @off < toff and readcmd == 'trailer' and off = @str.rindex('xref', toff)
@off = off
readcmd
readxrtable
@off = off2
readcmd
@trailer.update readhash
end
end | reads the pdf trailer
XXX the xref table referenced here may be the first of the file, so we suppose the last is just before the 'trailer' command.. | readtrailer | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def readany
case @str[@off, 1]
when nil; return
when '/'; readname
when '+', '-'; readint
when '0'..'9'
i = readint
if ('0'..'9').include?(@str[@off, 1])
poff = @off
g = readint
case readcmd
when 'obj'
@xrefs[g] ||= {}
i = @xrefs[g][i] ||= readany
raise 'no endobj' if readcmd != 'endobj'
when 'R'
i = Ref.new(self, g, i)
else @off = poff
end
end
i
when '['; readarray
when '('; readstr
when '<'
if @str[@off+1, 1] == '<'
h = readhash
if @str[@off, 6] == 'stream' and i = @str.index("\n", @off) # readcmd may eat spaces that are part of the stream
l = h['Length'].to_i
h = newstream(h, @str[i+1, l])
@off = i+1+l
skipspc
raise 'no endstream' if readcmd != 'endstream'
end
h
else readstr
end
else
case c = readcmd
when 'true', 'false', 'null'; c.to_sym
when 'xref'; readxrtable ; (@trailer ||= {}).update readhash if readcmd == 'trailer' ; readint if readcmd == 'startxref' ; :xref
else raise "unknown cmd #{c.inspect}"
end
end
end | reads & returns any pdf object according to its 1st char (almost)
updates @xrefs if the object is indirect | readany | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def deref(obj, depth=1)
if obj.kind_of? Ref
@xrefs[obj.gen] ||= {}
if not nobj = @xrefs[obj.gen][obj.id]
pvoff = @off
raise 'unknown ref off' unless @off = @xoff[obj.gen][obj.id]
puts "deref #{obj.gen} #{obj.id} => #{@off.to_s(16)}" if $DEBUG
nobj = @xrefs[obj.gen][obj.id] = readany || :poil
@off = pvoff
end
obj = nobj
end
depth -= 1
case obj
when Hash; obj = obj.dup ; obj.each { |k, v| obj[k] = deref(v, depth) }
when Array; obj = obj.dup ; obj.each_with_index { |v, i| obj[i] = deref(v, depth) }
end if depth > 0
obj
end | dereference references from the specified root, with the specified depth | deref | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def page_data(ct)
if deref(ct).kind_of? Array
ct.map { |c| c[:data] }.join
else
ct[:data]
end
end | returns the :data field for a Hash or the concatenation of the :data fields of the children for an Array | page_data | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def each_page(h=@trailer['Root']['Pages'])
if h['Kids']
h['Kids'].each { |k| each_page(k, &Proc.new) }
else
yield PSPage.new(page_data(h['Contents']))
end
end | iterates over the PDF pages, yields each PSPage | each_page | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def page(nr, ar=@trailer['Root']['Pages']['Kids'])
ar.each { |kid|
if kid['Count']
break page(nr, kid['Kids']) if nr <= kid['Count']
nr -= kid['Count']
else
nr -= 1
break PSPage.new(page_data(kid['Contents'])) if nr <= 0
end
}
end | returns the nr-th page of the pdf as a PSPage | page | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
def initialize(str, x, y, fontx, fonty, charspc, wordspc)
@raw, @charspc, @wordspc = str, charspc, wordspc
@x, @y, @fontx, @fonty = x, y, fontx, fonty
str = str[1...-1] if str[0] == ?[
@str = ''
bs = char = false
#lastchar = nil
spc = ''
str.each_byte { |b|
if not bs
# special chars (unescaped)
case b
when ?( # new word: honor word spacing
spc = (-spc.to_f/CHARWIDTH).round
if spc > 0 and not @str.empty?
@str << (' '*spc)
elsif spc < 0
@str.chop! while @str[-1] == ?\ and (spc += 1) <= 0# and (lastchar != ?\ or @str[-2] == lastchar)
end
char = true
next
when ?\\ # bs character
bs = true
next
when ?) # end of word
char = false
spc = ''
next
end
end
# octal escape sequence: leave as is (actual char depends on font)
if bs and (?0..?7).include? b; @str << ?\\ end
bs = false
if char
# update current rendered string, honoring charspc
@str << b
@str << (' ' * (charspc*1000/CHARWIDTH).round) if charspc > 0.1
@str << (' ' * (wordspc*1000/CHARWIDTH).round) if b == ?\ and wordspc > 0.1
#lastchar = b
else
# between strings: store word spacing integer
spc << b
end
}
puts "(#{x}, #{y} #{fontx}, #{fonty}) #@str" if $VERBOSE
end | parses a postscript line, returns a line with individual characters at the right place (more or less) | initialize | ruby | stephenfewer/grinder | node/lib/metasm/misc/pdfparse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.