. \"ls\" C-m send cmds/keys to pane\ntmux run -t
run shell command in background and report output on pane -t For example cycle through all panes in all windows in all sessions: # bash\nfor s in $(tmux list-sessions -F '#S'); do for w in $(tmux list-windows -F '#I' -t $s); do for p in $(tmux list-panes -F '#P' -t $s:$w); do echo $s:$w.$p done done\ndone","breadcrumbs":"Tools » tmux » Scripting","id":"102","title":"Scripting"},"103":{"body":"prefix d detach from current session\nprefix c create new window\nprefix w open window list\nprefix $ rename session\nprefix , rename window\nprefix . move current window Following bindings are specific to my tmux.conf : C-s prefix # Panes\nprefix s horizontal split\nprefix v vertical split\nprefix f toggle maximize/minimize current pane # Movement\nprefix Tab toggle between window prefix h move to pane left\nprefix j move to pane down\nprefix k move to pane up\nprefix l move to pane right # Resize\nprefix C-h resize pane left\nprefix C-j resize pane down\nprefix C-k resize pane up\nprefix C-l resize pane right # Copy/Paste\nprefix C-v enter copy mode\nprefix C-p paste yanked text\nprefix C-b open copy-buffer list # In Copy Mode\nv enable visual mode\ny yank selected text","breadcrumbs":"Tools » tmux » Bindings","id":"103","title":"Bindings"},"104":{"body":"To enter command mode prefix :. Some useful commands are: setw synchronize-panes on/off enables/disables synchronized input to all panes\nlist-keys -t vi-copy list keymaps for vi-copy mode","breadcrumbs":"Tools » tmux » Command mode","id":"104","title":"Command mode"},"105":{"body":"# Create new session.\nscreen # List active session.\nscreen -list # Attach to specific session.\nscreen -r SESSION","breadcrumbs":"Tools » screen » screen(1)","id":"105","title":"screen(1)"},"106":{"body":"# Enable logfile, default name screenlog.0.\nscreen -L\n# Enable log and set logfile name.\nscreen -L -Logfile out.txt","breadcrumbs":"Tools » screen » Options","id":"106","title":"Options"},"107":{"body":"Ctrl-A d # Detach from session.\nCtrl-A + \\ # Terminate session.\nCtrl-A + : # Open cmand prompt. kill # Kill session.","breadcrumbs":"Tools » screen » Keymaps","id":"107","title":"Keymaps"},"108":{"body":"USB serial console. # 1500000 -> baudrate\n# cs8 -> 8 data bits\n# -cstopb -> 1 stop bit\n# -parenb -> no parity bit\n# see stty(1) for all settings.\nscreen /dev/ttyUSB0 1500000,cs8,-cstopb,-parenb # Print current tty settings.\nsudo stty -F /dev/ttyUSB0 -a","breadcrumbs":"Tools » screen » Examples","id":"108","title":"Examples"},"109":{"body":"","breadcrumbs":"Tools » emacs » emacs(1)","id":"109","title":"emacs(1)"},"11":{"body":"Zsh supports regular expression matching with the binary operator =~. The match results can be accessed via the $MATCH variable and $match indexed array: $MATCH contains the full match $match[1] contains match of the first capture group INPUT='title foo : 1234'\nREGEX='^title (.+) : ([0-9]+)$'\nif [[ $INPUT =~ $REGEX ]]; then echo \"$MATCH\" # title foo : 1234 echo \"$match[1]\" # foo echo \"$match[2]\" # 1234\nfi","breadcrumbs":"Shells » zsh » Regular Expressions","id":"11","title":"Regular Expressions"},"110":{"body":"C-h ? list available help modes C-h e show message output (`*Messages*` buffer) C-h f describe function C-h v describe variable C-h w describe which key invoke function (where-is) C-h c print command bound to C-h k describe command bound to C-h b list buffer local key-bindings C-h list possible key-bindings with eg C-x C-h -> list key-bindings beginning with C-x","breadcrumbs":"Tools » emacs » help","id":"110","title":"help"},"111":{"body":"key fn description\n------------------------------------------------ package-refresh-contents refresh package list package-list-packages list available/installed packages `U x` to mark packages for Upgrade & eXecute","breadcrumbs":"Tools » emacs » package manager","id":"111","title":"package manager"},"112":{"body":"key fn description\n---------------------------------------------- C-x 0 delete-window kill focused window C-x 1 delete-other-windows kill all other windows C-x 2 split-window-below split horizontal C-x 3 split-window-right split vertical C-x o other-window other window (cycle)","breadcrumbs":"Tools » emacs » window","id":"112","title":"window"},"113":{"body":"key description\n---------------------------- M-e enter edit minibuffer edit mode M-up focus previous completion M-down focus next completion M-ret select focused completion","breadcrumbs":"Tools » emacs » minibuffer","id":"113","title":"minibuffer"},"114":{"body":"key fn description\n--------------------------------------------- C-x C-q read-only-mode toggle read-only mode for buffer C-x k kill-buffer kill buffer C-x s save-some-buffers save buffer C-x w write-file write buffer (save as) C-x b switch-to-buffer switch buffer C-x C-b list-buffers buffer list","breadcrumbs":"Tools » emacs » buffer","id":"114","title":"buffer"},"115":{"body":"Builtin advanced buffer selection mode key fn description\n-------------------------------------- ibuffer enter buffer selection h ibuffer help o open buffer in other window C-o open buffer in other window keep focus in ibuffer s a sort by buffer name s f sort by file name s v sort by last viewed s v sort by major mode , cycle sorting mode = compare buffer against file on disk (if file is dirty `*`) /m filter by major mode /n filter by buffer name /f filter by file name // remove all filter /g create filter group /\\ remove all filter groups","breadcrumbs":"Tools » emacs » ibuffer","id":"115","title":"ibuffer"},"116":{"body":"key fn description\n---------------------------------------- M-g g goto-line go to line M-g M-n next-error go to next error (grep, xref, compilation, ...) M-g M-p previous-error go to previous error M-g i imenu go to place in buffer (symbol, ...)","breadcrumbs":"Tools » emacs » goto navigation","id":"116","title":"goto navigation"},"117":{"body":"key fn description\n------------------------------------------------- C-s isearch-forward search forward from current position (C-s to go to next match) C-r isearch-backward search backwards from current position (C-r to go to next match) C-w isearch-yank-word-or-char feed next word to current search (extend) M-p isearch-ring-advance previous search input M-n isearch-ring-retreat next search input M-e isearch-edit-string edit search string again M-s o occur open search string in occur","breadcrumbs":"Tools » emacs » isearch","id":"117","title":"isearch"},"118":{"body":"key fn description\n----------------------------------- M-s o occur get matches for regexp in buffer use during `isearch` to use current search term e enter occur edit mode (C-c C-c to quit) n move to next entry and keep focus in occur buffer p move to previous entry and keep focus in occur buffer C-n goto next line C-p goto previous line o open match in other window C-o open match in other window keep focus in ibuffer key fn description\n--------------------------------------------------------- multi-occur-in-matching-buffers run occur in buffers matching regexp","breadcrumbs":"Tools » emacs » occur","id":"118","title":"occur"},"119":{"body":"key fn description\n----------------------------------- rgrep recursive grep find-grep run find-grep result in *grep* buffer n/p navigate next/previous match in *grep* buffer q quit *grep* buffer","breadcrumbs":"Tools » emacs » grep","id":"119","title":"grep"},"12":{"body":"trap \"\" /EXIT # Show current trap handler.\ntrap -p\n# List signal names.\ntrap -l Example: Run handler only on error exit trap 'test $? -ne 0 && echo \"run exit trap\"' EXIT # -> no print\nexit 0\n# -> print\nexit 1 Example: Mutex in shell script For example if a script is triggered in unsynchronized, we may want to ensure that a single script instance runs. # open file=LOCK with fd=100\nexec 100>LOCK\n# take exclusive lock, wait maximal for 3600s\nflock -w 3600 -x 100 || { echo \"flock timeout\"; exit 1; } # eg automatically release lock when script exits\ntrap \"flock -u 100\" EXIT","breadcrumbs":"Shells » zsh » Trap Handling","id":"12","title":"Trap Handling"},"120":{"body":"key fn description\n--------------------------------------------- C- set-mark-command set start mark to select text M-w kill-ring-save copy selected text C-w kill-region kill selected text C-y yank paste selected text M-y yank-pop cycle through kill-ring (only after paste)","breadcrumbs":"Tools » emacs » yank/paste","id":"120","title":"yank/paste"},"121":{"body":"key fn description\n------------------------------------------------ C-x r s copy-to-register save region in register C-x r i insert-register insert content of register ","breadcrumbs":"Tools » emacs » register","id":"121","title":"register"},"122":{"body":"key fn description\n------------------------------------------- C-x r m bookmark-set set a bookmark C-x r b bookmark-jump jump to a bookmark C-x r l bookmark-bmenu-list list all bookmarks","breadcrumbs":"Tools » emacs » bookmarks","id":"122","title":"bookmarks"},"123":{"body":"key fn description\n------------------------------------------------ C-x rectangle-mark-mode activate rectangle-mark-mode string-rectangle insert text in marked rect","breadcrumbs":"Tools » emacs » block/rect","id":"123","title":"block/rect"},"124":{"body":"key fn description\n------------------------------------------------ C-x h mark-whole-buffer mark whole buffer delete-matching-line delete lines matching regex replace-string replace unconditional M-% query-replace search & replace C-M-% query-replace-regexp search & replace regex","breadcrumbs":"Tools » emacs » mass edit","id":"124","title":"mass edit"},"125":{"body":"key fn description\n--------------------------------------------- C-x n n narrow-to-region show only focused region (narrow) C-x n w widen show whole buffer (wide)","breadcrumbs":"Tools » emacs » narrow","id":"125","title":"narrow"},"126":{"body":"key fn description\n------------------------------------ M-up/M-down re-arrange items in same hierarchy M-left/M-right change item hierarchy C-RET create new item below current C-S-RET create new TODO item below current S-left/S-right cycle TODO states","breadcrumbs":"Tools » emacs » org","id":"126","title":"org"},"127":{"body":"key fn description\n------------------------------ get doc for completion condidate M- select completion candidate","breadcrumbs":"Tools » emacs » company","id":"129","title":"company"},"13":{"body":"","breadcrumbs":"Shells » zsh » Completion","id":"13","title":"Completion"},"130":{"body":"To generate etags using ctags ctags -R -e . generate emacs tag file (important `-e`) Navigate using tags key fn description\n----------------------------------------------- M-. xref-find-definitions find definition of tag (C-u prefix to enter symbol manually) xref-find-apropos find symbols matching regexp M-? xref-find-references find references of tag","breadcrumbs":"Tools » emacs » tags","id":"130","title":"tags"},"131":{"body":"key fn description\n------------------------------ ielm open interactive elips shell In lisp-interaction-mode (*scratch* buffer by defult) key fn description\n----------------------------------------------------------- C-j eval-print-last-sexp evaluate & print preceeding lisp expr C-x C-e eval-last-sexp evaluate lisp expr C-u C-x C-e eval-last-sexp evaluate & print C-c C-e elisp-eval-region-or-buffer eval buffer or region (elisp mode)","breadcrumbs":"Tools » emacs » lisp","id":"131","title":"lisp"},"132":{"body":"Builtin fuzzy completion mode (eg buffer select, dired, ...). key fn description\n------------------------------------------ ido-mode toggle ido mode / cycle through available competions select completion There is also fido, which is the successor of ido, which also supports fido-vertical-mode in case vertical mode is preferred.","breadcrumbs":"Tools » emacs » ido","id":"132","title":"ido"},"133":{"body":"key fn description\n-------------------------- C-z toggle emacs/evil mode C-^ toggle between previous and current buffer C-p after paste cycle kill-ring back C-n after paste cycle kill-ring forward","breadcrumbs":"Tools » emacs » evil","id":"133","title":"evil"},"134":{"body":"key fn description\n-------------------------- i open sub-dir in same buffer + create new directory C copy file/dir R move file/dir (rename) S absolute symbolic link Y relative symbolic link d mark for deletion m mark file/dir u un-mark file/dir U un-mark all x execute marked actions q quit","breadcrumbs":"Tools » emacs » dired","id":"134","title":"dired"},"135":{"body":"key fn description\n--------------------------------------- n Info-next next page p Info-prev previous page l Info-history-back history go back r Info-history-forward history go forward ^ Info-Up up in info node tree m Info-menu goto menu (by minibuf completion) s Info-search search info g Info-goto-node goto info node (by minibuf completion) Info-history open info history in buffer","breadcrumbs":"Tools » emacs » info","id":"135","title":"info"},"136":{"body":"key fn description\n--------------------------------------------- M-! shell-command run shell command synchronously M-& async-shell-command run shell command asynchronously M-| shell-command-on-region run shell command on region; prefix with C-u to replace region with output of the command","breadcrumbs":"Tools » emacs » shell commands","id":"136","title":"shell commands"},"137":{"body":"gpg -o|--output Specify output file -a|--armor Create ascii output -u|--local-user Specify key for signing -r|--recipient Encrypt for user","breadcrumbs":"Tools » gpg » gpg(1)","id":"137","title":"gpg(1)"},"138":{"body":"gpg --full-generate-key","breadcrumbs":"Tools » gpg » Generate new keypair","id":"138","title":"Generate new keypair"},"139":{"body":"gpg -k / --list-key # public keys\ngpg -K / --list-secret-keys # secret keys","breadcrumbs":"Tools » gpg » List keys","id":"139","title":"List keys"},"14":{"body":"Completion functions are provided via files and need to be placed in a location covered by $fpath. By convention the completion files are names as _. A completion skeleton for the command foo, stored in _foo #compdef _foo foo function _foo() { ...\n} Alternatively one can install a completion function explicitly by calling compdef .","breadcrumbs":"Shells » zsh » Installation","id":"14","title":"Installation"},"140":{"body":"gpg --edit-key Gives prompt to modify KEY ID, common commands: help show help\nsave save & quit list list keys and user IDs\nkey select subkey \nuid select user ID expire change expiration of selected key adduid add user ID\ndeluid delete selected user ID addkey add subkey\ndelkey delete selected subkey","breadcrumbs":"Tools » gpg » Edit keys","id":"140","title":"Edit keys"},"141":{"body":"gpg --export --armor --output \ngpg --export-secret-key --armor --output \ngpg --import ","breadcrumbs":"Tools » gpg » Export & Import Keys","id":"141","title":"Export & Import Keys"},"142":{"body":"gpg --keyserver --send-keys \ngpg --keyserver --search-keys ","breadcrumbs":"Tools » gpg » Search & Send keys","id":"142","title":"Search & Send keys"},"143":{"body":"Encrypt file using passphrase and write encrypted data to .gpg. gpg --symmetric # Decrypt using passphrase\ngpg -o --decrypt .gpg","breadcrumbs":"Tools » gpg » Encrypt (passphrase)","id":"143","title":"Encrypt (passphrase)"},"144":{"body":"Encrypt file with public key of specified recipient and write encrypted data to .gpg. gpg --encrypt -r foo@bar.de # Decrypt at foos side (private key required)\ngpg -o --decrypt .gpg","breadcrumbs":"Tools » gpg » Encrypt (public key)","id":"144","title":"Encrypt (public key)"},"145":{"body":"Generate a signed file and write to .gpg. # Sign with private key of foo@bar.de\ngpg --sign -u foor@bar.de # Verify with public key of foo@bar.de\ngpg --verify # Extract content from signed file\ngpg -o --decrypt .gpg Without -u use first private key in list gpg -K for signing. Files can also be signed and encrypted at once, gpg will first sign the file and then encrypt it. gpg --sign --encrypt -r ","breadcrumbs":"Tools » gpg » Signing","id":"145","title":"Signing"},"146":{"body":"Generate a detached signature and write to .asc. Send .asc along with when distributing. gpg --detach-sign --armor -u foor@bar.de # Verify\ngpg --verify .asc Without -u use first private key in list gpg -K for signing.","breadcrumbs":"Tools » gpg » Signing (detached)","id":"146","title":"Signing (detached)"},"147":{"body":"sec secret key ssb secret subkey pub public key sub public subkey Key usage flags: [S] signing [C] create certificates [E] encrypting [A] authentication","breadcrumbs":"Tools » gpg » Abbreviations","id":"147","title":"Abbreviations"},"148":{"body":"http://pgp.mit.edu http://keyserver.ubuntu.com hkps://pgp.mailbox.org","breadcrumbs":"Tools » gpg » Keyservers","id":"148","title":"Keyservers"},"149":{"body":"","breadcrumbs":"Tools » gpg » Examples","id":"149","title":"Examples"},"15":{"body":"Following variables are available in Completion functions: $words # array with command line in words\n$#words # number words\n$CURRENT # index into $words for cursor position\n$words[CURRENT-1] # previous word (relative to cursor position)","breadcrumbs":"Shells » zsh » Completion Variables","id":"15","title":"Completion Variables"},"150":{"body":"gpg --keyid-format 0xlong ","breadcrumbs":"Tools » gpg » List basic key information from file with long keyids","id":"150","title":"List basic key information from file with long keyids"},"151":{"body":"gpg --edit-key # By default we are on the primary key, can switch to sub key.\ngpg> key 1 # Update the expire date.\ngpg> expire gpg> save # Update keyserver(s) and/or export new pub keyfile.","breadcrumbs":"Tools » gpg » Extend expiring key","id":"151","title":"Extend expiring key"},"152":{"body":"","breadcrumbs":"Tools » radare2 » radare2(1)","id":"152","title":"radare2(1)"},"153":{"body":"pd [@ ] # print disassembly for instructions # with optional temporary seek to ","breadcrumbs":"Tools » radare2 » print","id":"153","title":"print"},"154":{"body":"fs # list flag-spaces fs # select flag-space f # print flags of selected flag-space","breadcrumbs":"Tools » radare2 » flags","id":"154","title":"flags"},"155":{"body":"?*~ # '?*' list all commands and '~' grep for ?*~... # '..' less mode /'...' interactive search","breadcrumbs":"Tools » radare2 » help","id":"155","title":"help"},"156":{"body":"> r2 -B # open mapped to addr oob # reopen current file at ","breadcrumbs":"Tools » radare2 » relocation","id":"156","title":"relocation"},"157":{"body":"","breadcrumbs":"Tools » radare2 » Examples","id":"157","title":"Examples"},"158":{"body":"> r2 [-w] oo+ # re-open for write if -w was not passed s # seek to position wv # write 4 byte (dword)","breadcrumbs":"Tools » radare2 » Patch file (alter bytes)","id":"158","title":"Patch file (alter bytes)"},"159":{"body":"rasm2 -L # list supported archs > rasm2 -a x86 'mov eax, 0xdeadbeef' b8efbeadde > rasm2 -a x86 -d \"b8efbeadde\" mov eax, 0xdeadbeef","breadcrumbs":"Tools » radare2 » Assemble / Disassmble (rasm2)","id":"159","title":"Assemble / Disassmble (rasm2)"},"16":{"body":"_describe simple completion, just words + description _arguments sophisticated completion, allow to specify actions Completion with _describe _describe MSG COMP MSG simple string with header message COMP array of completions where each entry is \"opt:description\" function _foo() { local -a opts opts=('bla:desc for bla' 'blu:desc for blu') _describe 'foo-msg' opts\n}\ncompdef _foo foo foo -- foo-msg --\nbla -- desc for bla\nblu -- desc for blu Completion with _arguments _arguments SPEC [SPEC...] where SPEC can have one of the following forms: OPT[DESC]:MSG:ACTION for option flags N:MSG:ACTION for positional arguments Available actions (op1 op2) list possible matches\n->VAL set $state=VAL and continue, `$state` can be checked later in switch case\nFUNC call func to generate matches\n{STR} evaluate `STR` to generate matches","breadcrumbs":"Shells » zsh » Completion Functions","id":"16","title":"Completion Functions"},"160":{"body":"All the examples & notes use qemu-system-x86_64 but in most cases this can be swapped with the system emulator for other architectures.","breadcrumbs":"Tools » qemu » qemu(1)","id":"160","title":"qemu(1)"},"161":{"body":"Graphic mode: Ctrl+Alt+g release mouse capture from VM Ctrl+Alt+1 switch to display of VM\nCtrl+Alt+2 switch to qemu monitor No graphic mode: Ctrl+a h print help\nCtrl+a x exit emulator\nCtrl+a c switch between monitor and console","breadcrumbs":"Tools » qemu » Keybindings","id":"161","title":"Keybindings"},"162":{"body":"Following command-line gives a good starting point to assemble a VM: qemu-system-x86_64 \\ -cpu host -enable-kvm -smp 4 \\ -m 8G \\ -vga virtio -display sdl,gl=on \\ -boot menu=on \\ -cdrom \\ -hda \\ -device qemu-xhci,id=xhci \\ -device usb-host,bus=xhci.0,vendorid=0x05e1,productid=0x0408,id=capture-card","breadcrumbs":"Tools » qemu » VM config snippet","id":"162","title":"VM config snippet"},"163":{"body":"# Emulate host CPU in guest VM, enabling all supported host featured (requires KVM).\n# List available CPUs `qemu-system-x86_64 -cpu help`.\n-cpu host # Enable KVM instead software emulation.\n-enable-kvm # Configure number of guest CPUs.\n-smp # Configure size of guest RAM.\n-m 8G","breadcrumbs":"Tools » qemu » CPU & RAM","id":"163","title":"CPU & RAM"},"164":{"body":"# Use sdl window as display and enable openGL context.\n-display sdl,gl=on # Use vnc server as display (eg on display `:42` here).\n-display vnc=localhost:42 # Confifure virtio as 3D video graphic accelerator (requires virgl in guest).\n-vga virtio","breadcrumbs":"Tools » qemu » Graphic & Display","id":"164","title":"Graphic & Display"},"165":{"body":"# Enables boot menu to select boot device (enter with `ESC`).\n-boot menu=on","breadcrumbs":"Tools » qemu » Boot Menu","id":"165","title":"Boot Menu"},"166":{"body":"# Attach cdrom drive with iso to a VM.\n-cdrom # Attach disk drive to a VM.\n-hda # Generic way to configure & attach a drive to a VM.\n-drive file=,format=qcow2 Create a disk with qemu-img To create a qcow2 disk (qemu copy-on-write) of size 10G: qemu-img create -f qcow2 disk.qcow2 10G The disk does not contain any partitions or a partition table. We can format the disk from within the guest as following example: # Create `gpt` partition table.\nsudo parted /dev/sda mktable gpt # Create two equally sized primary partitions.\nsudo parted /dev/sda mkpart primary 0% 50%\nsudo parted /dev/sda mkpart primary 50% 100% # Create filesystem on each partition.\nsudo mkfs.ext3 /dev/sda1\nsudo mkfs.ext4 /dev/sda2 lsblk -f /dev/sda NAME FSTYPE LABEL UUID FSAVAIL FSUSE% MOUNTPOINT sda ├─sda1 ext3 .... └─sda2 ext4 ....","breadcrumbs":"Tools » qemu » Block devices","id":"166","title":"Block devices"},"167":{"body":"Host Controller # Add XHCI USB controller to the VM (supports USB 3.0, 2.0, 1.1).\n# `id=xhci` creates a usb bus named `xhci`.\n-device qemu-xhci,id=xhci USB Device # Pass-through USB device from host identified by vendorid & productid and\n# attach to usb bus `xhci.0` (defined with controller `id`).\n-device usb-host,bus=xhci.0,vendorid=0x05e1,productid=0x0408","breadcrumbs":"Tools » qemu » USB","id":"167","title":"USB"},"168":{"body":"# Open gdbstub on tcp `` (`-s` shorthand for `-gdb tcp::1234`).\n-gdb tcp:: # Freeze guest CPU at startup and wait for debugger connection.\n-S","breadcrumbs":"Tools » qemu » Debugging","id":"168","title":"Debugging"},"169":{"body":"# Create raw tcp server for `serial IO` and wait until a client connects\n# before executing the guest.\n-serial tcp:localhost:12345,server,wait # Create telnet server for `serial IO` and wait until a client connects\n# before executing the guest.\n-serial telnet:localhost:12345,server,wait # Configure redirection for the QEMU `mointor`, arguments similar to `-serial`\n# above.\n-monitor ... In server mode use nowait to execute guest without waiting for a client connection.","breadcrumbs":"Tools » qemu » IO redirection","id":"169","title":"IO redirection"},"17":{"body":"Skeleton to copy/paste for writing simple completions. Assume a program foo with the following interface: foo -c green|red|blue -s low|high -f -d -h The completion handler could be implemented as follows in a file called _foo: #compdef _foo foo function _foo_color() { local colors=() colors+=('green:green color') colors+=('red:red color') colors+=('blue:blue color') _describe \"color\" colors\n} function _foo() { _arguments \\ \"-c[define color]:color:->s_color\" \\ \"-s[select sound]:sound:(low high)\" \\ \"-f[select file]:file:_files\" \\ \"-d[select dir]:dir:_files -/\" \\ \"-h[help]\" case $state in s_color) _foo_color;; esac\n}","breadcrumbs":"Shells » zsh » Example","id":"17","title":"Example"},"170":{"body":"# Redirect host tcp port `1234` to guest port `4321`.\n-nic user,hostfwd=tcp:localhost:1234-:4321","breadcrumbs":"Tools » qemu » Network","id":"170","title":"Network"},"171":{"body":"# Attach a `virtio-9p-pci` device to the VM.\n# The guest requires 9p support and can mount the shared drive as:\n# mount -t 9p -o trans=virtio someName /mnt\n-virtfs local,id=someName,path=,mount_tag=someName,security_model=none","breadcrumbs":"Tools » qemu » Shared drives","id":"171","title":"Shared drives"},"172":{"body":"# List debug items.\n-d help # Write debug log to file instead stderr.\n-D # Examples\n-d in_asm Log executed guest instructions.","breadcrumbs":"Tools » qemu » Debug logging","id":"172","title":"Debug logging"},"173":{"body":"# List name of all trace points.\n-trace help # Enable trace points matching pattern and optionally write trace to file.\n-trace [,file=] # Enable trace points for all events listed in the file.\n# File must contain one event/pattern per line.\n-trace events=","breadcrumbs":"Tools » qemu » Tracing","id":"173","title":"Tracing"},"174":{"body":"VM snapshots require that there is at least on qcow2 disk attached to the VM ( VM Snapshots ). Commands for qemu Monitor or QMP : # List available snapshots.\ninfo snapshots # Create/Load/Delete snapshot with name .\nsavevm \nloadvm \ndelvm The snapshot can also be directly specified when invoking qemu as: qemu-system-x86_64 \\ -loadvm \\ ...","breadcrumbs":"Tools » qemu » VM snapshots","id":"174","title":"VM snapshots"},"175":{"body":"Online migration example: # Start machine 1 on host ABC.\nqemu-system-x86_64 -monitor stdio -cdrom # Prepare machine 2 on host DEF as migration target.\n# Listen for any connection on port 12345.\nqemu-system-x86_64 -monitor stdio -incoming tcp:0.0.0.0:12345 # Start migration from the machine 1 monitor console.\n(qemu) migrate tcp:DEF:12345 Save to external file example: ```bash\n# Start machine 1.\nqemu-system-x86_64 -monitor stdio -cdrom # Save VM state to file.\n(qemu) migrate \"exec:gzip -c > vm.gz\" # Load VM from file.\nqemu-system-x86_64 -monitor stdio -incoming \"exec: gzip -d -c vm.gz\" The migration source machine and the migration target machine should be launched with the same parameters.","breadcrumbs":"Tools » qemu » VM Migration","id":"175","title":"VM Migration"},"176":{"body":"Example command line to directly boot a Kernel with an initrd ramdisk. qemu-system-x86_64 \\ -cpu host \\ -enable-kvm \\ -kernel /arch/x86/boot/bzImage \\ -append \"earlyprintk=ttyS0 console=ttyS0 nokaslr init=/init debug\" \\ -initrd /initramfs.cpio.gz \\ ... Instructions to build a minimal Kernel and initrd .","breadcrumbs":"Tools » qemu » Appendix: Direct Kernel boot","id":"176","title":"Appendix: Direct Kernel boot"},"177":{"body":"test: test.s as -o test.o test.s ld -o test test.o testc.o trace: test qemu-x86_64 -singlestep -d nochain,cpu ./test 2>&1 | awk '/RIP/ { print $$1; }' clean: $(RM) test test-bin test.o .section .text, \"ax\" .global _start\n_start: xor %rax, %rax mov $0x8, %rax\n1: cmp $0, %rax je 2f dec %rax jmp 1b\n2: # x86-64 exit(2) syscall mov $0, %rdi mov $60, %rax syscall","breadcrumbs":"Tools » qemu » Appendix: Cheap instruction tracer","id":"177","title":"Appendix: Cheap instruction tracer"},"178":{"body":"QEMU USB QEMU IMG QEMU Tools QEMU System QEMU Invocation (command line args) QEMU Monitor QEMU machine protocol (QMP) QEMU VM Snapshots","breadcrumbs":"Tools » qemu » References","id":"178","title":"References"},"179":{"body":"","breadcrumbs":"Tools » pacman » pacman(1)","id":"179","title":"pacman(1)"},"18":{"body":"For this example we assume that the command foo takes at least three optional arguments such as foo arg1 arg2 arg3 [argN..] function _foo() { _arguments \\ \"1:opt 1:(a b c)\" \\ \":opt next:(d e f)\" \\ \"*:opt all:(u v w)\"\n} Explanation: 1:MSG:ACTION sets completion for the first optional argument :MSG:ACTION sets completion for the next optional argument *:MSG:ACTION sets completion for the optional argument where none of the previous rules apply, so in our example for arg3, argN... _files is a zsh builtin utility function to complete files/dirs see zsh completion functions zsh completion utility functions","breadcrumbs":"Shells » zsh » Example with optional arguments","id":"18","title":"Example with optional arguments"},"180":{"body":"pacman -Sy refresh package database\npacman -S install pkg\npacman -Ss search remote package database\npacman -Si get info for pkg\npacman -Su upgrade installed packages\npacman -Sc clean local package cache","breadcrumbs":"Tools » pacman » Remote package repositories","id":"180","title":"Remote package repositories"},"181":{"body":"pacman -Rsn uninstall package and unneeded deps + config files","breadcrumbs":"Tools » pacman » Remove packages","id":"181","title":"Remove packages"},"182":{"body":"Local package database of installed packages. pacman -Q list all installed packages\npacman -Qs search local package database\npacman -Ql list files installed by pkg\npacman -Qo query package that owns file\npacman -Qe only list explicitly installed packages","breadcrumbs":"Tools » pacman » Local package database","id":"182","title":"Local package database"},"183":{"body":"Local file database which allows to search packages owning certain files. Also searches non installed packages, but database must be synced. pacman -Fy refresh file database\npacman -Fl list files in pkg (must not be installed)\npacman -Fx search","breadcrumbs":"Tools » pacman » Local file database","id":"183","title":"Local file database"},"184":{"body":"Uninstall all orphaned packages (including config files) that were installed as dependencies. pacman -Rsn $(pacman -Qtdq) List explicitly installed packages that are not required as dependency by any package and sort by size. pacman -Qetq | xargs pacman -Qi | awk '/Name/ { name=$3 } /Installed Size/ { printf \"%8.2f%s %s\\n\", $4, $5, name }' | sort -h Install package into different root directory but keep using the default database. pacman --root abc --dbpath /var/lib/pacman -S mingw-w64-gcc","breadcrumbs":"Tools » pacman » Hacks","id":"184","title":"Hacks"},"185":{"body":"Online playground","breadcrumbs":"Tools » dot » dot(1)","id":"185","title":"dot(1)"},"186":{"body":"Can be rendered to svg with the following command. dot -T svg -o g.svg g.dot Example dot file. // file: g.dot\ndigraph { // Render ranks from left to right. rankdir=LR // Make background transparent. bgcolor=transparent // Global node attributes. node [shape=box] // Global edge attributes. edge [style=dotted,color=red] // Add nodes & edge. stage1 -> stage2 // Add multiple edges at once. stage2 -> { stage3_1, stage3_2 } // Add edge with custom attributes. stage3_2 -> stage4 [label=\"some text\"] // Set custom attributes for specific node. stage4 [color=green,fillcolor=lightgray,style=\"filled,dashed\",label=\"s4\"] // Create a subgraph. This can be used to group nodes/edges or as scope for // global node/edge attributes. // If the name starts with 'cluster' a border is drawn. subgraph cluster_1 { stage5_1 stage5_2 } // Add some edges to subgraph nodes. stage3_1 -> { stage5_1, stage5_2 }\n} Rendered svg file. g.svg","breadcrumbs":"Tools » dot » Example dot file to copy & paste from.","id":"186","title":"Example dot file to copy & paste from."},"187":{"body":"DOT language Attributes Node shapes Colors User manual","breadcrumbs":"Tools » dot » References","id":"187","title":"References"},"188":{"body":"","breadcrumbs":"Tools » ffmpeg » ffmpeg (1)","id":"188","title":"ffmpeg (1)"},"189":{"body":"Following snippet allows to select a window which is then captured. #!/bin/bash echo \"Click on window to record ..\"\n# Extract window size and x,y offset.\nvideo_args=$(xwininfo \\ | awk '/Absolute upper-left X:/ { xoff = $4 } /Absolute upper-left Y:/ { yoff=$4 } /Width:/ { if ($2 % 2 == 1) { width=$2-1; } else { width=$2; } } /Height:/ { if ($2 % 2 == 1) { height=$2-1; } else { height=$2; } } END { printf \"-video_size %dx%d -i :0.0+%d,%d\", width, height, xoff, yoff }') ffmpeg -framerate 25 -f x11grab $video_args -pix_fmt yuv420p $@ output.mp4 Use yuv420p pixel format if video is played on the web ( ref ) The input -i 0,0+xoff,yoff means to capture $DISPLAY=0.0 starting at the coordinate (xoff, yoff), which is the left-upper corner, and the size of the capture is defined by the -video_size argument.","breadcrumbs":"Tools » ffmpeg » screen capture specific window (x11)","id":"189","title":"screen capture specific window (x11)"},"19":{"body":"","breadcrumbs":"Shells » bash » bash(1)","id":"19","title":"bash(1)"},"190":{"body":"# Launch interactive shell.\ngnuplot # Launch interactive shell.\ngnuplot [opt] opt: -p ................ persist plot window -c ......... run script file -e \"; ..\" ... run cmd(s)","breadcrumbs":"Tools » gnuplot » gnuplot (1)","id":"190","title":"gnuplot (1)"},"191":{"body":"# Plot title.\nset title \"the plot\" # Labels.\nset xlabel \"abc\"\nset ylabel \"def\" # Grid.\nset grind # Output format, 'help set term' for all output formats.\nset term svg\n# Output file.\nset output \"out.svg\" # Make axis logarithmic to given base.\nset logscale x 2 # Change separator, default is whitespace.\nset datafile separator \",\"","breadcrumbs":"Tools » gnuplot » Frequently used configuration","id":"191","title":"Frequently used configuration"},"192":{"body":"# With specific style (eg lines, linespoint, boxes, steps, impulses, ..).\nplot \"\" with > cat data.txt\n1 1 3\n2 2 2\n3 3 1\n4 2 2 # Plot specific column.\nplot \"data.txt\" using 1:2, \"data.txt\" using 1:3\n# Equivalent using the special file \"\", which re-uses the previous input file.\nplot \"data.txt\" using 1:2, \"\" using 1:3 # Plot piped data.\nplot \"< head -n2 data.txt\" # Plot with alternate title.\nplot \"data.txt\" title \"moose\"","breadcrumbs":"Tools » gnuplot » Plot","id":"192","title":"Plot"},"193":{"body":"# Plot two functions in the range 0-10.\nplot [0:10] 10*x, 20*x","breadcrumbs":"Tools » gnuplot » Example: Specify range directly during plot","id":"193","title":"Example: Specify range directly during plot"},"194":{"body":"# file: mem_lat.plot set title \"memory latency (different strides)\"\nset xlabel \"array in KB\"\nset ylabel \"cycles / access\" set logscale x 2 plot \"stride_32.txt\" title \"32\" with linespoints, \\ \"stride_64.txt\" title \"64\" with linespoints, \\ \"stride_128.txt\" title \"128\" with linespoints, \\ \"stride_256.txt\" title \"256\" with linespoints, \\ \"stride_512.txt\" title \"512\" with linespoints On Linux x86_64, mem_lat.c provides an example which can be run as follows. gcc -o mem_lat mem_lat.c -g -O3 -Wall -Werror for stride in 32 64 128 256 512; do \\ taskset -c 1 ./mem_lat 128 $stride | tee stride_$stride.txt ; \\\ndone gnuplot -p -c mem_lat.plot","breadcrumbs":"Tools » gnuplot » Example: multiple data sets in plot","id":"194","title":"Example: multiple data sets in plot"},"195":{"body":"","breadcrumbs":"Tools » restic » restic(1)","id":"195","title":"restic(1)"},"196":{"body":"# Create a local backup repository.\nrestic -r init # Create a backup repository on a remote host.\nrestic -r sftp:user@host: init","breadcrumbs":"Tools » restic » Create new snapshot repository","id":"196","title":"Create new snapshot repository"},"197":{"body":"Restore files matching from the latest snapshot (pseudo snapshot ID) into . restic -r restore -i --target latest","breadcrumbs":"Tools » restic » Example: Restore file pattern from latest snapshot","id":"197","title":"Example: Restore file pattern from latest snapshot"},"198":{"body":"Mount snapshots as user filesystem (fuse) to given mount point. restic -r mount # Mounted snapshots can be limited by host.\nrestic -r mount --host # Mounted snapshots can be limited by path (abs path).\nrestic -r mount --path ","breadcrumbs":"Tools » restic » Mount snapshots","id":"198","title":"Mount snapshots"},"199":{"body":"Check the repository for errors and report them. restic -r check Check the repository for non-referenced data and remove it. restic -r prune","breadcrumbs":"Tools » restic » Repository maintenance","id":"199","title":"Repository maintenance"},"2":{"body":"","breadcrumbs":"Shells » zsh » zsh(1)","id":"2","title":"zsh(1)"},"20":{"body":"","breadcrumbs":"Shells » bash » Expansion","id":"20","title":"Expansion"},"200":{"body":"restic read the docs sftp","breadcrumbs":"Tools » restic » References","id":"200","title":"References"},"201":{"body":"Generate wifi qr code for WPA2 secured network. # Generate on terminal.\nqrencode -t ansiutf8 'WIFI:S:;T:WPA2;P:;;' # Generate picture for printing.\nqrencode -t png -o wifi.png 'WIFI:S:;T:WPA2;P:;;'","breadcrumbs":"Tools » qrencode » qrencode(1)","id":"201","title":"qrencode(1)"},"202":{"body":"lsof pidstat pgrep ps pmap pstack taskset nice","breadcrumbs":"Process management & inspection » Process management & inspection","id":"202","title":"Process management & inspection"},"203":{"body":"lsof -r ..... repeatedly execute command ervery seconds -a ......... AND slection filters instead ORing (OR: default) -p ... filter by +fg ........ show file flags for file descripros -n ......... don't convert network addr to hostnames -P ......... don't convert network port to service names -i <@h[:p]>. show connections to h (hostname|ip addr) with optional port p -s ... in conjunction with '-i' filter for protocol in state -U ......... show unix domain sockets ('@' indicates abstract sock name, see unix(7)) file flags: R/W/RW ..... read/write/read-write CR ......... create AP ......... append TR ......... truncate -s protocols TCP, UDP -s states (TCP) CLOSED, IDLE, BOUND, LISTEN, ESTABLISHED, SYN_SENT, SYN_RCDV, ESTABLISHED, CLOSE_WAIT, FIN_WAIT1, CLOSING, LAST_ACK, FIN_WAIT_2, TIME_WAIT -s states (UDP) Unbound, Idle","breadcrumbs":"Process management & inspection » lsof » lsof(8)","id":"203","title":"lsof(8)"},"204":{"body":"","breadcrumbs":"Process management & inspection » lsof » Examples","id":"204","title":"Examples"},"205":{"body":"Show open files with file flags for process: lsof +fg -p ","breadcrumbs":"Process management & inspection » lsof » File flags","id":"205","title":"File flags"},"206":{"body":"Show open tcp connections for $USER: lsof -a -u $USER -i TCP Note : -a ands the results. If -a is not given all open files matching $USER and all tcp connections are listed ( ored ).","breadcrumbs":"Process management & inspection » lsof » Open TCP connections","id":"206","title":"Open TCP connections"},"207":{"body":"Show open connections to localhost for $USER: lsof -a -u $USER -i @localhost","breadcrumbs":"Process management & inspection » lsof » Open connection to specific host","id":"207","title":"Open connection to specific host"},"208":{"body":"Show open connections to port :1234 for $USER: lsof -a -u $USER -i :1234","breadcrumbs":"Process management & inspection » lsof » Open connection to specific port","id":"208","title":"Open connection to specific port"},"209":{"body":"lsof -i 4TCP -s TCP:ESTABLISHED","breadcrumbs":"Process management & inspection » lsof » IPv4 TCP connections in ESTABLISHED state","id":"209","title":"IPv4 TCP connections in ESTABLISHED state"},"21":{"body":"# generate sequence from n to m\n{n..m}\n# generate sequence from n to m step by s\n{n..m..s} # expand cartesian product\n{a,b}{c,d}","breadcrumbs":"Shells » bash » Generator","id":"21","title":"Generator"},"210":{"body":"This may help to find which processes keep devices busy when trying to unmount and the device is currently busy. # Assuming /proc is a mount point.\nlsof /proc","breadcrumbs":"Process management & inspection » lsof » List open files in a mounted directory.","id":"210","title":"List open files in a mounted directory."},"211":{"body":"pidstat [opt] [interval] [cont] -U [user] show username instead UID, optionally only show for user -r memory statistics -d I/O statistics -h single line per process and no lines with average","breadcrumbs":"Process management & inspection » pidstat » pidstat(1)","id":"211","title":"pidstat(1)"},"212":{"body":"pidstat -r -p [interval] [count] minor_pagefault: Happens when the page needed is already in memory but not allocated to the faulting process, in that case the kernel only has to create a new page-table entry pointing to the shared physical page (not required to load a memory page from disk). major_pagefault: Happens when the page needed is NOT in memory, the kernel has to create a new page-table entry and populate the physical page (required to load a memory page from disk).","breadcrumbs":"Process management & inspection » pidstat » Page fault and memory utilization","id":"212","title":"Page fault and memory utilization"},"213":{"body":"pidstat -d -p [interval] [count]","breadcrumbs":"Process management & inspection » pidstat » I/O statistics","id":"213","title":"I/O statistics"},"214":{"body":"pgrep [opts] -n only list newest matching process -u only show matching for user -l additionally list command -a additionally list command + arguments -x match exactly","breadcrumbs":"Process management & inspection » pgrep » pgrep(1)","id":"214","title":"pgrep(1)"},"215":{"body":"For example attach gdb to newest zsh process from $USER. gdb -p $(pgrep -n -u $USER zsh)","breadcrumbs":"Process management & inspection » pgrep » Debug newest process","id":"215","title":"Debug newest process"},"216":{"body":"ps [opt] opt: --no-header .... do not print column header -o ....... comma separated list of output columns -p ....... only show pid -C ...... only show processes matching name -T ............. list threads --signames ..... use short signames instead bitmasks Set PS_FORMAT env variable to setup default output columns. Frequently used output columns pid process id\nppid parent process id\npgid process group id\ntid thread id comm name of process\ncmd name of process + args (full) etime elapsed time (since process started)\nuser user owning process\nthcount thread count of process\nnice nice value (-20 highest priority to 19 lowest) pcpu cpu utilization (percent)\npmem physical resident set (rss) (percent)\nrss physical memory (in kb)\nvsz virtual memory (in kb) sig mask of pending signals\nsigcatch mask of caught signals\nsigignore mask of ignored signals\nsigmask mask of blocked signals","breadcrumbs":"Process management & inspection » ps » ps(1)","id":"216","title":"ps(1)"},"217":{"body":"# Print the cpu affinity for each thread of process 31084.\nfor tid in $(ps -o tid --no-header -T -p 31084); do taskset -c -p $tid;\ndone","breadcrumbs":"Process management & inspection » ps » Example: Use output for scripting","id":"217","title":"Example: Use output for scripting"},"218":{"body":"watch -n1 ps -o pid,pcpu,pmem,rss,vsz,state,user,comm -C fish","breadcrumbs":"Process management & inspection » ps » Example: Watch processes by name","id":"218","title":"Example: Watch processes by name"},"219":{"body":"# With signal masks.\nps -o pid,user,sig,sigcatch,sigignore,sigmask,comm -p 66570 # With signal names.\nps --signames -o pid,user,sig,sigcatch,sigignore,sigmask,comm -p 66570","breadcrumbs":"Process management & inspection » ps » Example: Show signal information","id":"219","title":"Example: Show signal information"},"22":{"body":"# default value\nbar=${foo:-some_val} # if $foo set, then bar=$foo else bar=some_val # alternate value\nbar=${foo:+bla $foo} # if $foo set, then bar=\"bla $foo\" else bar=\"\" # check param set\nbar=${foo:?msg} # if $foo set, then bar=$foo else exit and print msg # indirect\nFOO=foo\nBAR=FOO\nbar=${!BAR} # deref value of BAR -> bar=$FOO # prefix\n${foo#prefix} # remove prefix when expanding $foo\n# suffix\n${foo%suffix} # remove suffix when expanding $foo # substitute\n${foo/pattern/string} # replace pattern with string when expanding foo\n# pattern starts with\n# '/' replace all occurences of pattern\n# '#' pattern match at beginning\n# '%' pattern match at end # set programmatically with priintf builtin\nprintf -v \"VAR1\" \"abc\"\nNAME=VAR2\nprintf -v \"$NAME\" \"%s\" \"def\" Note: prefix/suffix/pattern are expanded as pathnames .","breadcrumbs":"Shells » bash » Parameter","id":"22","title":"Parameter"},"220":{"body":"pmap [opts] Dump virtual memory map of process. Compared to /proc//maps it shows the size of the mappings.\nopts: -p show full path in the mapping -x show details (eg RSS usage of each segment)","breadcrumbs":"Process management & inspection » pmap » pmap(1)","id":"220","title":"pmap(1)"},"221":{"body":"pstack Dump stack for all threads of process.","breadcrumbs":"Process management & inspection » pstack » pstack(1)","id":"221","title":"pstack(1)"},"222":{"body":"Set cpu affinity for new processes or already running ones. # Pin all (-a) tasks of new command on cores 0,1,2,4.\ntaskset -ac 0-2,4 CMD [ARGS] # Pin all tasks of running PID onto cores 0,2,4.\ntaskset -ac 0-5:2 -p PID","breadcrumbs":"Process management & inspection » taskset » taskset(1)","id":"222","title":"taskset(1)"},"223":{"body":"Utility script to extract cpu lists grouped by the last-level-cache. import subprocess res = subprocess.run([\"lscpu\", \"-p=cpu,cache\"], capture_output=True, check=True) LLC2CPU = dict() for line in res.stdout.decode().splitlines(): if line.startswith(\"#\"): continue cpu, cache = line.split(\",\") llc = cache.split(\":\")[-1] LLC2CPU.setdefault(llc, list()).append(int(cpu)) LLC2RANGE = dict() for llc, cpus in LLC2CPU.items(): first_cpu = cpus[0] prev_cpu = cpus[0] for cpu in cpus[1:]: if cpu != prev_cpu + 1: LLC2RANGE.setdefault(llc, list()).append(f\"{first_cpu}-{prev_cpu}\") # New range begins. first_cpu = cpu prev_cpu = cpu # Trailing range. LLC2RANGE.setdefault(llc, list()).append(f\"{first_cpu}-{prev_cpu}\") print(LLC2RANGE)","breadcrumbs":"Process management & inspection » taskset » Example","id":"223","title":"Example"},"224":{"body":"Adjust niceness of a new command or running process. Niceness influences the scheduling priority and ranges between: -20 most favorable 19 least favorable # Adjust niceness +5 for the launched process.\nnice -n 5 yes # Adjust niceness of running process.\nrenice -n 5 -p PID","breadcrumbs":"Process management & inspection » nice » nice(1)","id":"224","title":"nice(1)"},"225":{"body":"time strace ltrace perf OProfile callgrind valgrind","breadcrumbs":"Trace and Profile » Trace and Profile","id":"225","title":"Trace and Profile"},"226":{"body":"# statistics of process run\n/usr/bin/time -v ","breadcrumbs":"Trace and Profile » time » /usr/bin/time(1)","id":"226","title":"/usr/bin/time(1)"},"227":{"body":"strace [opts] [prg] -f .......... follow child processes on fork(2) -ff ......... follow fork and separate output file per child -p .... attach to running process -s ... max string size, truncate of longer (default: 32) -e ... expression for trace filtering -o ... log output into -c .......... dump syscall statitics at the end -C .......... like -c but dump regular ouput as well -k .......... dump stack trace for each syscall -P ... only trace syscall accesing path -y .......... print paths for FDs -tt ......... print absolute timestamp (with us precision) -r .......... print relative timestamp -z .......... log only successful syscalls -Z .......... log only failed syscalls -n .......... print syscall numbers -y .......... translate fds (eg file path, socket) -yy ......... translate fds with all information (eg IP) -x .......... print non-ASCII chars as hex string -v .......... print all arguments (non-abbreviated) : trace=syscall[,syscall] .... trace only syscall listed trace=file ................. trace all syscall that take a filename as arg trace=process .............. trace process management related syscalls trace=signal ............... trace signal related syscalls signal ..................... trace signals delivered to the process","breadcrumbs":"Trace and Profile » strace » strace(1)","id":"227","title":"strace(1)"},"228":{"body":"Trace open(2) & socket(2) syscalls for a running process + child processes: strace -f -e trace=open,socket -p Trace signals delivered to a running process: strace -e signal -e 'trace=!all' -p Show successful calls to perf_event_open((2) without abbreviating arguments. strace -v -z -e trace=perf_event_open perf stat -e cycles ls","breadcrumbs":"Trace and Profile » strace » Examples","id":"228","title":"Examples"},"229":{"body":"ltrace [opts] [prg] -f .......... follow child processes on fork(2) -p .... attach to running process -o ... log output into -l . show who calls into lib matched by -C .......... demangle -e . show calls symbols matched by -x . which symbol table entry points to trace (can be of form sym_pattern@lib_pattern) -n number of spaces to indent nested calls","breadcrumbs":"Trace and Profile » ltrace » ltrace(1)","id":"229","title":"ltrace(1)"},"23":{"body":"* match any string\n? match any single char\n\\\\ match backslash\n[abc] match any char of 'a' 'b' 'c'\n[a-z] match any char between 'a' - 'z'\n[^ab] negate, match all not 'a' 'b'\n[:class:] match any char in class, available: alnum,alpha,ascii,blank,cntrl,digit,graph,lower, print,punct,space,upper,word,xdigit With extglob shell option enabled it is possible to have more powerful patterns. In the following pattern-list is one ore more patterns separated by | char. ?(pattern-list) matches zero or one occurrence of the given patterns\n*(pattern-list) matches zero or more occurrences of the given patterns\n+(pattern-list) matches one or more occurrences of the given patterns\n@(pattern-list) matches one of the given patterns\n!(pattern-list) matches anything except one of the given patterns Note: shopt -s extglob/shopt -u extglob to enable/disable extglob option.","breadcrumbs":"Shells » bash » Pathname","id":"23","title":"Pathname"},"230":{"body":"List which program/libs call into libstdc++: ltrace -l '*libstdc++*' -C -o ltrace.log ./main List calls to specific symbols: ltrace -e malloc -e free ./main Trace symbols from dlopen(3)ed libraries. # Assume libfoo.so would be dynamically loaded via dlopen.\nltrace -x '@libfoo.so' # Trace all dlopened symbols.\nltrace -x '*'\n# Trace all symbols from dlopened libraries which name match the\n# pattern \"liby*\".\nltrace -x '@liby*'\n# Trace symbol \"foo\" from all dlopened libraries matching the pattern.\nltrace -x 'foo@liby*'","breadcrumbs":"Trace and Profile » ltrace » Example","id":"230","title":"Example"},"231":{"body":"perf list show supported hw/sw events & metrics -v ........ print longer event descriptions --details . print information on the perf event names and expressions used internally by events perf stat -p ..... show stats for running process -o .... write output to file (default stderr) -I ...... show stats periodically over interval -e ...... select event(s) -M ..... print metric(s), this adds the metric events --all-user ... configure all selected events for user space --all-kernel . configure all selected events for kernel space perf top -p .. show stats for running process -F ... sampling frequency -K ........ hide kernel threads perf record -p ............... record stats for running process -o .............. write output to file (default perf.data) -F ................ sampling frequency --call-graph .. [fp, dwarf, lbr] method how to caputre backtrace fp : use frame-pointer, need to compile with -fno-omit-frame-pointer dwarf: use .cfi debug information lbr : use hardware last branch record facility -g ..................... short-hand for --call-graph fp -e ................ select event(s) --all-user ............. configure all selected events for user space --all-kernel ........... configure all selected events for kernel space -M intel ............... use intel disassembly in annotate perf report -n .................... annotate symbols with nr of samples --stdio ............... report to stdio, if not presen tui mode -g graph,0.5,callee ... show callee based call chains with value >0.5 Useful : page-faults minor-faults major-faults cpu-cycles` task-clock","breadcrumbs":"Trace and Profile » perf » perf(1)","id":"231","title":"perf(1)"},"232":{"body":"Events to sample are specified with the -e option, either pass a comma separated list or pass -e multiple times. Events are specified in the following form name[:modifier]. The list and description of the modifier can be found in the perf-list(1) manpage under EVENT MODIFIERS. # L1 i$ misses in user space\n# L2 i$ stats in user/kernel space mixed\n# Sample specified events.\nperf stat -e L1-icache-load-misses:u \\ -e l2_rqsts.all_code_rd:uk,l2_rqsts.code_rd_hit:k,l2_rqsts.code_rd_miss:k \\ -- stress -c 2 The --all-user and --all-kernel options append a :u and :k modifier to all specified events. Therefore the following two command lines are equivalent. # 1)\nperf stat -e cycles:u,instructions:u -- ls # 2)\nperf stat --all-user -e cycles,instructions -- ls","breadcrumbs":"Trace and Profile » perf » Select specific events","id":"232","title":"Select specific events"},"233":{"body":"In case perf does not provide a symbolic name for an event, the event can be specified in a raw form as r + UMask + EventCode. The following is an example for the L2_RQSTS.CODE_RD_HIT event with EventCode=0x24 and UMask=0x10 on my laptop with a sandybridge uarch. perf stat -e l2_rqsts.code_rd_hit -e r1024 -- ls\n# Performance counter stats for 'ls':\n#\n# 33.942 l2_rqsts.code_rd_hit\n# 33.942 r1024","breadcrumbs":"Trace and Profile » perf » Raw events","id":"233","title":"Raw events"},"234":{"body":"The intel/perfmon repository provides a performance event databases for the different intel uarchs. The table in mapfile.csv can be used to lookup the corresponding uarch, just grab the family model from the procfs. cat /proc/cpuinfo | awk '/^vendor_id/ { V=$3 } /^cpu family/ { F=$4 } /^model\\s*:/ { printf \"%s-%d-%x\\n\",V,F,$3 }' The table in performance monitoring events describes how events are sorted into the different files.","breadcrumbs":"Trace and Profile » perf » Find raw performance counter events (intel)","id":"234","title":"Find raw performance counter events (intel)"},"235":{"body":"Perf also defines some own symbolic names for events. An example is the cache-references event. The perf_event_open(2) manpage gives the following description. perf_event_open(2) PERF_COUNT_HW_CACHE_REFERENCES Cache accesses. Usually this indicates Last Level Cache accesses but this may vary depending on your CPU. This may include prefetches and coherency messages; again this depends on the design of your CPU. The sysfs can be consulted to get the concrete performance counter on the given system. cat /sys/devices/cpu/events/cache-misses\n# event=0x2e,umask=0x41","breadcrumbs":"Trace and Profile » perf » Raw events for perfs own symbolic names","id":"235","title":"Raw events for perfs own symbolic names"},"236":{"body":"","breadcrumbs":"Trace and Profile » perf » Flamegraph","id":"236","title":"Flamegraph"},"237":{"body":"perf record -g -e cpu-cycles -p \nperf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > cycles-flamegraph.svg","breadcrumbs":"Trace and Profile » perf » Flamegraph with single event trace","id":"237","title":"Flamegraph with single event trace"},"238":{"body":"perf record -g -e cpu-cycles,page-faults -p \nperf script --per-event-dump\n# fold & generate as above","breadcrumbs":"Trace and Profile » perf » Flamegraph with multiple event traces","id":"238","title":"Flamegraph with multiple event traces"},"239":{"body":"","breadcrumbs":"Trace and Profile » perf » Examples","id":"239","title":"Examples"},"24":{"body":"Note: The trick with bash I/O redirection is to interpret from left-to-right. # stdout & stderr to file\ncommand >file 2>&1\n# equivalent\ncommand &>file # stderr to stdout & stdout to file\ncommand 2>&1 >file The article Bash One-Liners Explained, Part III: All about redirections contains some nice visualization to explain bash redirections.","breadcrumbs":"Shells » bash » I/O redirection","id":"24","title":"I/O redirection"},"240":{"body":"#define NOP4 \"nop\\nnop\\nnop\\nnop\\n\"\n#define NOP32 NOP4 NOP4 NOP4 NOP4 NOP4 NOP4 NOP4 NOP4\n#define NOP256 NOP32 NOP32 NOP32 NOP32 NOP32 NOP32 NOP32 NOP32\n#define NOP2048 NOP256 NOP256 NOP256 NOP256 NOP256 NOP256 NOP256 NOP256 int main() { for (unsigned i = 0; i < 2000000; ++i) { asm volatile(NOP2048); }\n} perf stat -e cycles,instructions ./noploop\n# Performance counter stats for './noploop':\n#\n# 1.031.075.940 cycles\n# 4.103.534.341 instructions # 3,98 insn per cycle","breadcrumbs":"Trace and Profile » perf » Estimate max instructions per cycle","id":"240","title":"Estimate max instructions per cycle"},"241":{"body":"The following gives an example for a scenario where we have the following calls main -> do_foo() -> do_work() main -> do_bar() -> do_work() perf report --stdio -g graph,caller # Children Self Command Shared Object Symbols\n# ........ ........ ....... .................... .................\n#\n# 49.71% 49.66% bench bench [.] do_work\n# |\n# --49.66%--_start <- callstack bottom\n# __libc_start_main\n# 0x7ff366c62ccf\n# main\n# |\n# |--25.13%--do_bar\n# | do_work <- callstack top\n# |\n# --24.53%--do_foo\n# do_work perf report --stdio -g graph,callee # Children Self Command Shared Object Symbols\n# ........ ........ ....... .................... .................\n#\n# 49.71% 49.66% bench bench [.] do_work\n# |\n# ---do_work <- callstack top\n# |\n# |--25.15%--do_bar\n# | main\n# | 0x7ff366c62ccf\n# | __libc_start_main\n# | _start <- callstack bottom\n# |\n# --24.55%--do_foo\n# main\n# 0x7ff366c62ccf\n# __libc_start_main\n# _start <- callstack bottom","breadcrumbs":"Trace and Profile » perf » Caller vs callee callstacks","id":"241","title":"Caller vs callee callstacks"},"242":{"body":"intel/perfmon - intel PMU event database per uarch intel/perfmon-html - a html rendered version of the PMU events with search intel/perfmon/mapfile.csv - processor family to uarch mapping linux/perf/events - x86 PMU events known to perf tools linux/arch/events - x86 PMU events linux kernel wikichip - computer architecture wiki perf-list(1) - manpage perf_event_open(2) - manpage intel/sdm - intel software developer manuals (eg Optimization Reference Manual)","breadcrumbs":"Trace and Profile » perf » References","id":"242","title":"References"},"243":{"body":"operf -g -p -g ...... caputre call-graph information opreport [opt] FILE show time spent per binary image -l ...... show time spent per symbol -c ...... show callgraph information (see below) -a ...... add column with time spent accumulated over child nodes ophelp show supported hw/sw events","breadcrumbs":"Trace and Profile » OProfile » OProfile","id":"243","title":"OProfile"},"244":{"body":"Callgrind is a tracing profiler which records the function call history of a target program and collects the number of executed instructions. It is part of the valgrind tool suite. Profiling data is collected by instrumentation rather than sampling of the target program. Callgrind does not capture the actual time spent in a function but computes the inclusive & exclusive cost of a function based on the instructions fetched (Ir = Instruction read). This provides reproducibility and high-precision and is a major difference to sampling profilers like perf or vtune. Therefore effects like slow IO are not reflected, which should be kept in mind when analyzing callgrind results. By default the profiler data is dumped when the target process is terminating, but callgrind_control allows for interactive control of callgrind. # Run a program under callgrind.\nvalgrind --tool=callgrind -- [] # Interactive control of callgrind.\ncallgrind_control [opts] opts: -b ............. show current backtrace -e ............. show current event counters -s ............. show current stats --dump[=file] .. dump current collection -i=on|off ...... turn instrumentation on|off Results can be analyzed by using one of the following tools callgrind_annotate (cli) # Show only specific trace events (default is all).\ncallgrind_annotate --show=Ir,Dr,Dw [callgrind_out_file] kcachegrind (ui) The following is a collection of frequently used callgrind options. valgrind --tool=callgrind [opts] -- opts: --callgrind-out-file= .... output file, rather than callgrind.out. --dump-instr= .......... annotation on instrucion level, allows for asm annotations --instr-atstart= ....... control if instrumentation is enabled from beginning of the program --separate-threads= .... create separate output files per thread, appends - to the output file --cache-sim= ........... control if cache simulation is enabled","breadcrumbs":"Trace and Profile » callgrind » callgrind","id":"244","title":"callgrind"},"245":{"body":"By default callgrind collects following events: Ir: Instruction read Callgrind also provides a functional cache simulation with their own model, which is enabled by passing --cache-sim=yes. This simulates a 2-level cache hierarchy with separate L1 instruction and data caches (L1i/ L1d) and a unified last level (LL) cache. When enabled, this collects the following additional events: I1mr: L1 cache miss on instruction read ILmr: LL cache miss on instruction read Dr: Data reads access D1mr: L1 cache miss on data read DLmr: LL cache miss on data read Dw: Data write access D1mw: L1 cache miss on data write DLmw: LL cache miss on data write","breadcrumbs":"Trace and Profile » callgrind » Trace events","id":"245","title":"Trace events"},"246":{"body":"Programmatically enable/disable instrumentation using the macros defined in the callgrind header. #include int main() { // init .. CALLGRIND_START_INSTRUMENTATION; compute(); CALLGRIND_STOP_INSTRUMENTATION; // shutdown ..\n} In this case, callgrind should be launched with --instr-atstart=no. Alternatively instrumentation can be controlled with callgrind_control -i on/off. The files cg_example.cc and Makefile provide a full example.","breadcrumbs":"Trace and Profile » callgrind » Profile specific part of the target","id":"246","title":"Profile specific part of the target"},"247":{"body":"","breadcrumbs":"Trace and Profile » valgrind » valgrind(1)","id":"247","title":"valgrind(1)"},"248":{"body":"Is the default tool when invoking valgrind without explicitly specifying --tool. Memory checker used to identify: memory leaks out of bound accesses uninitialized reads valgrind [OPTIONS] PROGRAM [ARGS] --log-file=FILE Write valgrind output to FILE. --leak-check=full Enable full leak check. --track-origins=yes Show origins of undefined values. --keep-debuginfo=no|yes Keep symbols etc for unloaded code. --gen-suppressions=yes Generate suppressions file from the run. --suppressions=FILE Load suppressions file.","breadcrumbs":"Trace and Profile » valgrind » Memcheck --tool=memcheck","id":"248","title":"Memcheck --tool=memcheck"},"249":{"body":"gdb gdbserver","breadcrumbs":"Debug » Debug","id":"249","title":"Debug"},"25":{"body":"j>&i Duplicate fd i to fd j, making j a copy of i. See dup2(2) . Example: command 2>&1 >file duplicate fd 1 to fd 2, effectively redirecting stderr to stdout redirect stdout to file","breadcrumbs":"Shells » bash » Explanation","id":"25","title":"Explanation"},"250":{"body":"","breadcrumbs":"Debug » gdb » gdb(1)","id":"250","title":"gdb(1)"},"251":{"body":"gdb [opts] [prg [-c coredump | -p pid]] gdb [opts] --args prg opts: -p attach to pid -c use -x execute script before prompt -ex execute command before prompt --tty set I/O tty for debugee --batch run in batch mode, exit after processing options (eg used for scripting) --batch-silent link --batch, but surpress gdb stdout","breadcrumbs":"Debug » gdb » CLI","id":"251","title":"CLI"},"252":{"body":"","breadcrumbs":"Debug » gdb » Interactive usage","id":"252","title":"Interactive usage"},"253":{"body":"apropos Search commands matching regex. tty Set as tty for debugee. Make sure nobody reads from target tty, easiest is to spawn a shell and run following in target tty: > while true; do sleep 1024; done sharedlibrary [] Load symbols of shared libs loaded by debugee. Optionally use to filter libs for symbol loading. display [/FMT] Print every time debugee stops. Eg print next instr, see examples below. undisplay [] Delete display expressions either all or one referenced by . info display List display expressions. info sharedlibrary [