. \"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":"100","title":"Scripting"},"101":{"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":"101","title":"Bindings"},"102":{"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":"102","title":"Command mode"},"103":{"body":"# Create new session.\nscreen # List active session.\nscreen -list # Attach to specific session.\nscreen -r SESSION","breadcrumbs":"Tools » screen » screen(1)","id":"103","title":"screen(1)"},"104":{"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":"104","title":"Options"},"105":{"body":"Ctrl-A d # Detach from session.\nCtrl-A + \\ # Terminate session.\nCtrl-A + : # Open cmand prompt. kill # Kill session.","breadcrumbs":"Tools » screen » Keymaps","id":"105","title":"Keymaps"},"106":{"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":"106","title":"Examples"},"107":{"body":"","breadcrumbs":"Tools » emacs » emacs(1)","id":"107","title":"emacs(1)"},"108":{"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":"108","title":"help"},"109":{"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":"109","title":"package manager"},"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":"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":"110","title":"window"},"111":{"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":"111","title":"minibuffer"},"112":{"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":"112","title":"buffer"},"113":{"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":"113","title":"ibuffer"},"114":{"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":"114","title":"goto navigation"},"115":{"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":"115","title":"isearch"},"116":{"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":"116","title":"occur"},"117":{"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":"117","title":"grep"},"118":{"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":"118","title":"yank/paste"},"119":{"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":"119","title":"register"},"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-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":"120","title":"bookmarks"},"121":{"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":"121","title":"block/rect"},"122":{"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":"122","title":"mass edit"},"123":{"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":"123","title":"narrow"},"124":{"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":"124","title":"org"},"125":{"body":"key fn description\n------------------------------ get doc for completion condidate M- select completion candidate","breadcrumbs":"Tools » emacs » company","id":"127","title":"company"},"128":{"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":"128","title":"tags"},"129":{"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":"129","title":"lisp"},"13":{"body":"","breadcrumbs":"Shells » zsh » Completion","id":"13","title":"Completion"},"130":{"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":"130","title":"ido"},"131":{"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":"131","title":"evil"},"132":{"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":"132","title":"dired"},"133":{"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":"133","title":"info"},"134":{"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":"134","title":"gpg(1)"},"135":{"body":"gpg --full-generate-key","breadcrumbs":"Tools » gpg » Generate new keypair","id":"135","title":"Generate new keypair"},"136":{"body":"gpg -k / --list-key # public keys\ngpg -K / --list-secret-keys # secret keys","breadcrumbs":"Tools » gpg » List keys","id":"136","title":"List keys"},"137":{"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":"137","title":"Edit keys"},"138":{"body":"gpg --export --armor --output \ngpg --export-secret-key --armor --output \ngpg --import ","breadcrumbs":"Tools » gpg » Export & Import Keys","id":"138","title":"Export & Import Keys"},"139":{"body":"gpg --keyserver --send-keys \ngpg --keyserver --search-keys ","breadcrumbs":"Tools » gpg » Search & Send keys","id":"139","title":"Search & Send 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":"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":"140","title":"Encrypt (passphrase)"},"141":{"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":"141","title":"Encrypt (public key)"},"142":{"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":"142","title":"Signing"},"143":{"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":"143","title":"Signing (detached)"},"144":{"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":"144","title":"Abbreviations"},"145":{"body":"http://pgp.mit.edu http://keyserver.ubuntu.com hkps://pgp.mailbox.org","breadcrumbs":"Tools » gpg » Keyservers","id":"145","title":"Keyservers"},"146":{"body":"","breadcrumbs":"Tools » gpg » Examples","id":"146","title":"Examples"},"147":{"body":"gpg --keyid-format 0xlong ","breadcrumbs":"Tools » gpg » List basic key information from file with long keyids","id":"147","title":"List basic key information from file with long keyids"},"148":{"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":"148","title":"Extend expiring key"},"149":{"body":"","breadcrumbs":"Tools » radare2 » radare2(1)","id":"149","title":"radare2(1)"},"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":"pd [@ ] # print disassembly for instructions # with optional temporary seek to ","breadcrumbs":"Tools » radare2 » print","id":"150","title":"print"},"151":{"body":"fs # list flag-spaces fs # select flag-space f # print flags of selected flag-space","breadcrumbs":"Tools » radare2 » flags","id":"151","title":"flags"},"152":{"body":"?*~ # '?*' list all commands and '~' grep for ?*~... # '..' less mode /'...' interactive search","breadcrumbs":"Tools » radare2 » help","id":"152","title":"help"},"153":{"body":"> r2 -B # open mapped to addr oob # reopen current file at ","breadcrumbs":"Tools » radare2 » relocation","id":"153","title":"relocation"},"154":{"body":"","breadcrumbs":"Tools » radare2 » Examples","id":"154","title":"Examples"},"155":{"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":"155","title":"Patch file (alter bytes)"},"156":{"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":"156","title":"Assemble / Disassmble (rasm2)"},"157":{"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":"157","title":"qemu(1)"},"158":{"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":"158","title":"Keybindings"},"159":{"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":"159","title":"VM config snippet"},"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":"# 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":"160","title":"CPU & RAM"},"161":{"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":"161","title":"Graphic & Display"},"162":{"body":"# Enables boot menu to select boot device (enter with `ESC`).\n-boot menu=on","breadcrumbs":"Tools » qemu » Boot Menu","id":"162","title":"Boot Menu"},"163":{"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":"163","title":"Block devices"},"164":{"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":"164","title":"USB"},"165":{"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":"165","title":"Debugging"},"166":{"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":"166","title":"IO redirection"},"167":{"body":"# Redirect host tcp port `1234` to guest port `4321`.\n-nic user,hostfwd=tcp:localhost:1234-:4321","breadcrumbs":"Tools » qemu » Network","id":"167","title":"Network"},"168":{"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":"168","title":"Shared drives"},"169":{"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":"169","title":"Debug logging"},"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":"# 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":"170","title":"Tracing"},"171":{"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":"171","title":"VM snapshots"},"172":{"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":"172","title":"VM Migration"},"173":{"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":"173","title":"Appendix: Direct Kernel boot"},"174":{"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":"174","title":"Appendix: Cheap instruction tracer"},"175":{"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":"175","title":"References"},"176":{"body":"","breadcrumbs":"Tools » pacman » pacman(1)","id":"176","title":"pacman(1)"},"177":{"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":"177","title":"Remote package repositories"},"178":{"body":"pacman -Rsn uninstall package and unneeded deps + config files","breadcrumbs":"Tools » pacman » Remove packages","id":"178","title":"Remove packages"},"179":{"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":"179","title":"Local package database"},"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":"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":"180","title":"Local file database"},"181":{"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":"181","title":"Hacks"},"182":{"body":"Online playground","breadcrumbs":"Tools » dot » dot(1)","id":"182","title":"dot(1)"},"183":{"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":"183","title":"Example dot file to copy & paste from."},"184":{"body":"DOT language Attributes Node shapes Colors User manual","breadcrumbs":"Tools » dot » References","id":"184","title":"References"},"185":{"body":"","breadcrumbs":"Tools » ffmpeg » ffmpeg (1)","id":"185","title":"ffmpeg (1)"},"186":{"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":"186","title":"screen capture specific window (x11)"},"187":{"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":"187","title":"gnuplot (1)"},"188":{"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":"188","title":"Frequently used configuration"},"189":{"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":"189","title":"Plot"},"19":{"body":"","breadcrumbs":"Shells » bash » bash(1)","id":"19","title":"bash(1)"},"190":{"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":"190","title":"Example: Specify range directly during plot"},"191":{"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":"191","title":"Example: multiple data sets in plot"},"192":{"body":"","breadcrumbs":"Tools » restic » restic(1)","id":"192","title":"restic(1)"},"193":{"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":"193","title":"Create new snapshot repository"},"194":{"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":"194","title":"Example: Restore file pattern from latest snapshot"},"195":{"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":"195","title":"Mount snapshots"},"196":{"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":"196","title":"Repository maintenance"},"197":{"body":"restic read the docs sftp","breadcrumbs":"Tools » restic » References","id":"197","title":"References"},"198":{"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":"198","title":"qrencode(1)"},"199":{"body":"lsof pidstat pgrep ps pmap pstack taskset nice","breadcrumbs":"Process management & inspection » Process management & inspection","id":"199","title":"Process management & inspection"},"2":{"body":"","breadcrumbs":"Shells » zsh » zsh(1)","id":"2","title":"zsh(1)"},"20":{"body":"","breadcrumbs":"Shells » bash » Expansion","id":"20","title":"Expansion"},"200":{"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":"200","title":"lsof(8)"},"201":{"body":"","breadcrumbs":"Process management & inspection » lsof » Examples","id":"201","title":"Examples"},"202":{"body":"Show open files with file flags for process: lsof +fg -p ","breadcrumbs":"Process management & inspection » lsof » File flags","id":"202","title":"File flags"},"203":{"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":"203","title":"Open TCP connections"},"204":{"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":"204","title":"Open connection to specific host"},"205":{"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":"205","title":"Open connection to specific port"},"206":{"body":"lsof -i 4TCP -s TCP:ESTABLISHED","breadcrumbs":"Process management & inspection » lsof » IPv4 TCP connections in ESTABLISHED state","id":"206","title":"IPv4 TCP connections in ESTABLISHED state"},"207":{"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":"207","title":"List open files in a mounted directory."},"208":{"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":"208","title":"pidstat(1)"},"209":{"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":"209","title":"Page fault and memory utilization"},"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":"pidstat -d -p [interval] [count]","breadcrumbs":"Process management & inspection » pidstat » I/O statistics","id":"210","title":"I/O statistics"},"211":{"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":"211","title":"pgrep(1)"},"212":{"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":"212","title":"Debug newest process"},"213":{"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":"213","title":"ps(1)"},"214":{"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":"214","title":"Example: Use output for scripting"},"215":{"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":"215","title":"Example: Watch processes by name"},"216":{"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":"216","title":"Example: Show signal information"},"217":{"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":"217","title":"pmap(1)"},"218":{"body":"pstack Dump stack for all threads of process.","breadcrumbs":"Process management & inspection » pstack » pstack(1)","id":"218","title":"pstack(1)"},"219":{"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":"219","title":"taskset(1)"},"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":"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":"220","title":"Example"},"221":{"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":"221","title":"nice(1)"},"222":{"body":"time strace ltrace perf OProfile callgrind valgrind","breadcrumbs":"Trace and Profile » Trace and Profile","id":"222","title":"Trace and Profile"},"223":{"body":"# statistics of process run\n/usr/bin/time -v ","breadcrumbs":"Trace and Profile » time » /usr/bin/time(1)","id":"223","title":"/usr/bin/time(1)"},"224":{"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":"224","title":"strace(1)"},"225":{"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":"225","title":"Examples"},"226":{"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 -x . which symbol table entry points to trace (can be of form sym_pattern@lib_pattern)","breadcrumbs":"Trace and Profile » ltrace » ltrace(1)","id":"226","title":"ltrace(1)"},"227":{"body":"List which program/libs call into libstdc++: ltrace -l '*libstdc++*' -C -o ltrace.log ./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":"227","title":"Example"},"228":{"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":"228","title":"perf(1)"},"229":{"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":"229","title":"Select specific events"},"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":"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":"230","title":"Raw events"},"231":{"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":"231","title":"Find raw performance counter events (intel)"},"232":{"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":"232","title":"Raw events for perfs own symbolic names"},"233":{"body":"","breadcrumbs":"Trace and Profile » perf » Flamegraph","id":"233","title":"Flamegraph"},"234":{"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":"234","title":"Flamegraph with single event trace"},"235":{"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":"235","title":"Flamegraph with multiple event traces"},"236":{"body":"","breadcrumbs":"Trace and Profile » perf » Examples","id":"236","title":"Examples"},"237":{"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":"237","title":"Estimate max instructions per cycle"},"238":{"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":"238","title":"Caller vs callee callstacks"},"239":{"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":"239","title":"References"},"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":"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":"240","title":"OProfile"},"241":{"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":"241","title":"callgrind"},"242":{"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":"242","title":"Trace events"},"243":{"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":"243","title":"Profile specific part of the target"},"244":{"body":"","breadcrumbs":"Trace and Profile » valgrind » valgrind(1)","id":"244","title":"valgrind(1)"},"245":{"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":"245","title":"Memcheck --tool=memcheck"},"246":{"body":"gdb gdbserver","breadcrumbs":"Debug » Debug","id":"246","title":"Debug"},"247":{"body":"","breadcrumbs":"Debug » gdb » gdb(1)","id":"247","title":"gdb(1)"},"248":{"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":"248","title":"CLI"},"249":{"body":"","breadcrumbs":"Debug » gdb » Interactive usage","id":"249","title":"Interactive usage"},"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":"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 [] List shared libraries loaded. Optionally use to filter.","breadcrumbs":"Debug » gdb » Misc","id":"250","title":"Misc"},"251":{"body":"break [-qualified] thread Set a breakpoint only for a specific thread. -qualified: Treat as fully qualified symbol (quiet handy to set breakpoints on C symbols in C++ contexts) break if Set conditional breakpoint (see examples below). delete [] Delete breakpoint either all or one referenced by . info break List breakpoints. cond Make existing breakpoint conditional with . cond Remove condition from breakpoint