text:
Talk:Algorithms/Ada Implementation

A or B thats here the question.
Right now I want to start an Appendix for Ada implementations. I have allready got some text and working demos ready Ada Programming/Algorithms which I only have to move in here. Of course replacing the header and footer to fit the layout used here.

Since this page is only a "substub" and does not actualy have any real text in it (just instructions on what to put here) I consider replacing it (moving the instructions to the talk page) so the reader has some real text to read - Python programmers can allways start a new Appendix when they are ready and have some demos to put here.

Objections?

 * Go ahead. A for Ada sounds nicer anyway. When I suggested B I guess I figured there was more of a shell for the Python part. But since it's so empty, it makes more sense that A actually has something.

Guideline
implementations should be runnable (have a "main"), complete with some small test cases that demonstrate the use and correctness of the implementation, as well as show how it handles boundary cases. Output of the program should be included

Note 1
For all implementations, note when a library alternative exists. In these cases, show the correctness of the implementation by creating test cases that compare the results to the library answer.

Note 2
Note: The main text should includes links to these specific implementations.

TODO
Translate every program fragment in the text. There are sure to be bugs!

title: Talk:Algorithms/Ada Implementation


text:
X86 Disassembly/Analysis Tools

Debuggers
Debuggers are programs that allow the user to execute a compiled program one step at a time. You can see what instructions are executed in which order, and which sections of the program are treated as code and which are treated as data. Debuggers allow you to analyze the program while it is running, to help you get a better picture of what it is doing.

Advanced debuggers often contain at least a rudimentary disassembler, often times hex editing and reassembly features. Debuggers often allow the user to set breakpoints on instructions, function calls, and even memory locations.

A breakpoint is an instruction to the debugger that allows program execution to be halted when a certain condition is met. For instance, when a program accesses a certain variable, or calls a certain API function, the debugger can pause program execution.

Windows Debuggers

 * SoftICE : A de facto standard for Windows debugging. SoftICE can be used for local kernel debugging, which is a feature that is very rare, and very valuable. SoftICE was taken off the market in April 2006.

 * WinDbg : WinDbg is a free piece of software from Microsoft that can be used for local user-mode debugging, or even remote kernel-mode debugging. WinDbg is not the same as the better-known Visual Studio Debugger, but comes with a nifty GUI nonetheless. Available in 32 and 64-bit versions.
 * https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools

 * IDA Pro : The multi-processor, multi-OS, interactive disassembler by DataRescue.
 * http://www.hex-rays.com/idapro/

 * OllyDbg : OllyDbg is a free and powerful Windows debugger with a built-in disassembly and assembly engine. Very useful for patching, disassembling, and debugging.
 * http://www.ollydbg.de/

 * x64dbg : A set of 32 and 64 bit x86 debuggers. x64dbg is the spiritual successor to the discontinued OllyDbg.

 * Immunity Debugger : Immunity Debugger is a branch of OllyDbg v1.10, with built-in support for Python scripting and much more.
 * http://immunityinc.com/products/debugger/index.html

Linux Debuggers
Many of the open source debuggers on Linux, again, are cross-platform. They may be available on some other Unix(-like) systems, or even Windows. Some of the debuggers may give you better experience than the old and native ones on your system.

 * gdb : The GNU debugger, comes with any normal Linux install. It is quite powerful and even somewhat programmable, though the raw user interface is harsh.

 * lldb: LLVM's debugger.

 * emacs : The GNU editor, can be used as a front-end to gdb. This provides a powerful hex editor and allows full scripting in a LISP-like language.

 * ddd : The Data Display Debugger. It's another front-end to gdb. This provides graphical representations of data structures. For example, a linked list will look just like a textbook illustration.

 * strace, ltrace, and xtrace : Lets you run a program while watching the actions it performs. With strace, you get a log of all the system calls being made. With ltrace, you get a log of all the library calls being made. With xtrace, you get a log of some of the funtion calls being made.

 * valgrind : Executes a program under emulation, performing analysis according to one of the many plug-in modules as desired. You can write your own plug-in module as desired. Newer versions of valgrind also support OS X.

 * NLKD : A kernel debugger.
 * http://forge.novell.com/modules/xfmod/project/?nlkd

 * edb : A fully featured plugin-based debugger inspired by the famous OllyDbg. Project page

 * KDbg : A gdb front-end for KDE. http://kdbg.org

 * RR0D : A Ring-0 Debugger for Linux. RR0D Project Page

 * Radare2
 * A debugger and reversing framework.

 * Winedbg: Wine's debugger. Debugs Windows executables using wine.

Debuggers for Other Systems

 * dbx : The standard Unix debugger on systems derived from AT&T Unix. It is often part of an optional development toolkit package which comes at an extra price.  It uses an interactive command line interface.

 * ladebug : An enhanced debugger on Tru64 Unix systems from HP (originally Digital Equipment Corporation) that handles advanced functionality like threads better than dbx.

 * DTrace : An advanced tool on Solaris that provides functions like profiling and many others on the entire system, including the kernel.

 * mdb : The Modular Debugger (MDB) is a new general purpose debugging tool for the Solaris Operating Environment. Its primary feature is its extensibility. The Solaris Modular Debugger Guide describes how to use MDB to debug complex software systems, with a particular emphasis on the facilities available for debugging the Solaris kernel and associated device drivers and modules. It also includes a complete reference for and discussion of the MDB language syntax, debugger features, and MDB Module Programming API.

Setting Breakpoints
As previously mentioned in the section on disassemblers, a 6-line C program doing something as simple as outputting "Hello, World!" turns into massive amounts of assembly code. Most people don't want to sift through the entire mess to find out the information they want. It can be time consuming just to find the information one desires by just looking through the code. As an alternative, one can choose to set breakpoints to halt the program once it has reached a given point within the program's code.

For instance, let's say that in your program you consistantly experience crashes after one particular event: immediately after closing a message box. You set breakpoints on all calls to MessageBoxA. You run your program with the breakpoints set, and it stops, ready to call MessageBoxA. Executing each line one-by-one thereafter (referred to as stepping) through the code, and watching the program stack, you see that a buffer overflow occurs soon after the call.

Hex Editors
Hex editors are able to directly view and edit the binary of a source file, and are very useful for investigating the structure of proprietary closed-format data files. There are many hex editors in existence. This section will attempt to list some of the best, some of the most popular, or some of the most powerful.

 * HxD (Freeware): For Windows. A fast and powerful free hex, disk and RAM editor
 * http://mh-nexus.de/hxd/

 * Freeware Hex Editor XVI32 : For Windows. A freeware hex editor.
 * http://www.chmaas.handshake.de/delphi/freeware/xvi32/xvi32.htm

 * wxHexEditor (Beta, For Windows and Linux, Free & Open Source): A fast hex editor specially for HUGE files and disk devices, allows up to hexabyte, allow size changes (inject and deletes) without creating temp file, could view files with multiple panes, has built-in disassembler, supports tags for (reverse) engineering big binaries or file systems, could view files thrug XOR encryption.
 * http://wxhexeditor.sourceforge.net/

 * HHD Software Hex Editor Neo : For Windows. A fast file, disk, and memory editor with built-in disassembler and file structure viewer.
 * http://www.hhdsoftware.com/Family/hex-editor.html

 * Catch22 HexEdit : For Windows. his is a powerful hex editor with a slew of features. Has an excellent data structure viewer.
 * http://www.catch22.net/software/hexedit.asp

 * BreakPoint Hex Workshop : For Windows. An excellent and powerful hex-editor, its usefulness is restricted by the fact that it is not free like some of the other options.
 * http://www.bpsoft.com/

 * Tiny Hexer : Free and does statistics. For Windows.
 * http://www.mirkes.de/files/

 * frhed - free hex editor : For Windows. Free and opensource.
 * http://www.kibria.de/frhed.html

 * Cygnus Hex Editor: For Windows. A very fast and easy-to-use hex editor, available in a 'Free Edition'.
 * http://www.softcircuits.com/cygnus/fe/

 * Hexprobe Hex Editor : For Windows. A professional hex editor designed to include all the power to deal with hex data, particularly helpful in the areas of hex-byte editing and byte-pattern analysis.
 * http://www.hexprobe.com/hexprobe/index.htm

 * UltraEdit32 : For Windows. A hex editor/text editor, won "Application of the Year" at 2005 Shareware Industry Awards Conference.
 * http://www.ultraedit.com/

 * Hexinator (For Windows and Linux): lets you edit files of unlimited size (overwrite, insert, delete), displays text with dozens of text encodings, shows variables in little and big endian byte order.
 * https://hexinator.com

 * ICY Hexplorer : For Windows. A lightweight free and open source hex file editor with some nifty features, such as pixel view, structures, and disassembling.
 * http://hexplorer.sourceforge.net/

 * WinHex : For Windows. A powerful hex file and disk editor with advanced abilities for computer forensics and data recovery (used by governments and military).
 * http://www.x-ways.net/index-m.html

 * 010 Editor : For Windows. A very powerful and fast hex editor with extensive support for data structures and scripting. Can be used to edit drives and processes.
 * http://www.sweetscape.com/010editor/

 * 1Fh : For Windows. A free binary/hex editor which is very fast, even while working with large files. It's the only Windows hex editor that allows you to view files in byte code (all 256-characters).
 * http://www.4neurons.com/1Fh/

 * HexEdit : For Windows (Open source) and shareware versions. Powerful and easy to use binary file and disk editor.
 * http://www.hexedit.com/

 * HexToolkit : For Windows. A free hex viewer specifically designed for reverse engineering file formats. Allows data to be viewed in various formats and includes an expression evaluator as well as a binary file comparison tool.
 * http://www.binaryearth.net/HexToolkit

 * FlexHex : For Windows. It Provides full support for NTFS files which are based on a more complex model than FAT32 files. Specifically, FlexHex supports Sparse files and Alternate data streams of files on any NTFS volume. Can be used to edit OLE compound files, flash cards, and other types of physical drives.
 * http://www.heaventools.com/flexhex-hex-editor.htm

 * HT Editor : For Windows. A file editor/viewer/analyzer for executables. Its goal is to combine the low-level functionality of a debugger and the usability of IDEs.
 * http://hte.sourceforge.net/

 * HexEdit : For MacOS. A simple but reliable hex editor wher you to change highlight colours. There is also a port for Apple Classic users.
 * http://hexedit.sourceforge.net/

 * Hex Fiend : For MacOS. A very simple hex editor, but incredibly powerful nonetheless. It's only 346 KB to download and takes files as big as 116 GB.
 * http://ridiculousfish.com/hexfiend/

 * ImHex : For Windows, MacOS and Linux. Displays, decodes and analyzes binary data (+ printable ASCII chars) and allow edition of bytes. Includes data inspector with various decoding (integers, floats, char/wchar, Unicode, dates, RGBA/RGB565 color...), search by hex bytes and string, hex diff, pattern matching, yara rules (for malware pattern detection), hash computations, graphical data statistics, disassemblers, and various extra tools from a "content store". Free and open-source, licensed under GPLv2.
 * https://imhex.werwolv.net/

Linux Hex Editors only

 * bvi: A typical three-pane hex editor, with a vi-like interface.

 * emacs : Along with everything else, emacs also includes a hex editor.

 * joe : Joe's own editor now also supports hex editing.

 * bless : A very capable gtk based hex editor.

 * xxd and any text editor : Produce a hex dump with xxd, freely edit it in your favorite text editor, and then convert it back to a binary file with your changes included.

 * GHex : Hex editor for GNOME.
 * http://directory.fsf.org/All_Packages_in_Directory/ghex.html

 * Okteta : The well-integrated hexeditor from KDE since 4.1. Offers the traditional two-columns layout, one with numeric values (binary, octal, decicmal, hexdecimal) and one with characters (lots of charsets supported). Editing can be done in both columns, with unlimited undo/redo. Small set of tools (searching/replacing, strings, binary filter, and more).
 * http://utils.kde.org/projects/okteta

 * BEYE : A viewer of binary files with built-in editor in binary, hexadecimal and disassembler modes. It uses native Intel syntax for disassembly. Highlight AVR/Java/Athlon64/Pentium 4/K7-Athlon disassembler, Russian codepages converter, full preview of formats - MZ, NE, PE, NLM, coff32, elf partial - a.out, LE, LX, PharLap; code navigator and more over. (
 * http://beye.sourceforge.net/en/beye.html

 * BIEW : A viewer of binary files with built-in editor in binary, hexadecimal and disassembler modes. It uses native Intel syntax for disassembly. Highlight AVR/Java/Athlon64/Pentium 4/K7-Athlon disassembler, Russian codepages converter, full preview of formats - MZ, NE, PE, NLM, coff32, elf partial - a.out, LE, LX, PharLap; code navigator and more over. (PROJECT RENAMED, see BEYE)
 * http://biew.sourceforge.net/en/biew.html

 * hview : A curses based hex editor designed to work with large (600+MB) files with as quickly, and with little overhead, as possible.
 * http://web.archive.org/web/20010306001713/http://tdistortion.esmartdesign.com/Zips/hview.tgz

 * HexCurse : An ncurses-based hex editor written in C that currently supports hex and decimal address output, jumping to specified file locations, searching, ASCII and EBCDIC output, bolded modifications, an undo command, quick keyboard shortcuts, etc.
 * http://www.jewfish.net/description.php?title=HexCurse

 * hexedit : View and edit files in hexadecimal or in ASCII.
 * http://rigaux.org/hexedit.html

 * Data Workshop : An editor to view and modify binary data; provides different views which can be used to edit, analyze and export the binary data.
 * http://www.dataworkshop.de/

 * VCHE: A hex editor which lets you see all 256 characters as found in video ROM, even control and extended ASCII, it uses the /dev/vcsa* devices to do it. It also could edit non-regular files, like hard disks, floppies, CDROMs, ZIPs, RAM, and almost any device. It comes with a ncurses and a raw version for people who work under X or remotely.
 * http://www.grigna.com/diego/linux/vche/

 * DHEX: DHEX is just another Hexeditor with a Diff-mode for ncurses. It makes heavy use of colors and is themeable.
 * http://www.dettus.net/dhex/

Resource Monitors

 * SysInternals Freeware : This page has a large number of excellent utilities, many of which are very useful to security experts, network administrators, and (most importantly to us) reversers. Specifically, check out Process Monitor, FileMon, RegMon, TCPView, and Process Explorer.
 * https://docs.microsoft.com/en-us/sysinternals/

API Monitors

 * SpyStudio Freeware : The Spy Studio software is a tool to hook into windows processes, log windows API call to DLLs, insert breakpoints and change parameters.
 * http://www.nektra.com/products/spystudio/

 * rohitab.com API Monitor : API Monitor is a free software that lets you monitor and control API calls made by applications and services. Features include detailed parameter information, structures, unions, enumerated/flag data types, call stack, call tree, breakpoints, custom DLLs, memory editor, call filtering, COM monitoring, 64-bit. Includes definitions for over 13,000 APIs and 1,300+ COM interfaces.
 * http://www.rohitab.com/apimonitor

PE File Header dumpers

 * Dumpbin : Dumpbin is a program that previously used to be shipped with MS Visual Studio, but recently the functionality of Dumpbin has been incorporated into the Microsoft Linker, link.exe. to access dumpbin, pass /dump as the first parameter to link.exe:

link.exe /dump [options]

 * It is frequently useful to simply create a batch file that handles this conversion:

link.exe /dump %*

'''All examples in this wikibook that use dumpbin will call it in this manner. '''
 * Here is a list of useful features of dumpbin :

dumpbin /EXPORTS        displays a list of functions exported from a library dumpbin /IMPORTS        displays a list of functions imported from other libraries dumpbin /HEADERS        displays PE header information for the executable

 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_dumpbin_reference.asp

 * Depends : Dependency Walker is a GUI tool which will allow you to see exports and imports of binaries. It ships with many Microsoft tools including MS Visual Studio.

GNU Tools
The GNU packages have been ported to many platforms including Windows.

 * GNU BinUtils : The GNU BinUtils package contains several small utilities that are very useful in dealing with binary files. The most important programs in the list are the GNU objdump, readelf, GAS assembler, and the GNU linker, although the reverser might find more use in addr2line, c++filt, nm, and readelf.
 * http://www.gnu.org/software/binutils/

 * objdump : Dumps out information about an executable including symbols and assembly. It comes standard. It can be made to support non-native binary formats.

objdump -p              displays a list of functions imported from other libraries, exported to and miscellaneous file header information

It's useful to check dll dependencies from command line

 * readelf : Like objdump but more specialized for ELF executables.

 * size : Lists the sizes of the segments.

 * nm : Lists the symbols in an ELF file.

 * strings : Prints the strings from a file.

 * file : Tells you what type of file it is.

 * fold : Folds the results of strings into something pageable.

 * kill : Can be used to halt a program with the sig_stop signal.

 * strace : Trace system calls and signals.

Other Tools for Linux

 * oprofile : Can be used the find out what functions and data segments are used

 * subterfugue : A tool for playing odd tricks on an executable as it runs. The tool is scriptable in python. The user can write scripts to take action on events that occur, such as changing the arguments to system calls.
 * http://subterfugue.org/

 * lizard : Lets you run a program backwards.
 * http://lizard.sourceforge.net/

 * dprobes : Lets you work with both kernel and user code.

 * biew : Both a hex editor and a disassembler.

 * ltrace : Displays runtime library call information for dynamically linked executables.

 * asmDIFF : Searches for functions, instructions and memory pointers in different versions of same binary by using code metrics. Supports x86, x86_64 code in PE and ELF files.
 * http://duschkumpane.org/index.php/asmdiff

XCode Tools
XCode contains some extra tools to be used under OS X with the Mach-O format. You can see more of them under.

 * lipo: Manages fat binaries with multiple architectures.

 * otool: Object file displaying tool, works somehow like objdump and readelf.

XCode also packs a lot of Unix tools, with many of them sharing the names (and functions) of the GNU tools. Other tools like nasm/ndisasm, lldb and GNU as can also be found.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: X86 Disassembly/Analysis Tools


text:
X86 Disassembly/Microsoft Windows

Microsoft Windows
The Windows operating system is a popular reverse engineering target for one simple reason: the OS itself (market share, known weaknesses), and most applications for it, are not Open Source or free. Most software on a Windows machine doesn't come bundled with its source code, and most pieces have inadequate, or non-existent documentation. Occasionally, the only way to know precisely what a piece of software does (or for that matter, to determine whether a given piece of software is malicious or legitimate) is to reverse it, and examine the results.

Windows Versions
Windows operating systems can be easily divided into 2 categories: Windows9x, and WindowsNT.

Windows 9x
The Windows9x kernel was originally written to span the 16bit - 32bit divide. Operating Systems based on the 9x kernel are Windows 95, Windows 96, Windows 98, and Windows Me. Windows9x Series operating systems are known to be prone to bugs and system instability. The actual OS itself was a 32 bit extension of MS-DOS, its predecessor. An important issue with the 9x line is that they were all based around using the ANSI format for storing strings, rather than Unicode.

Development on the Windows9x kernel ended with the release of Windows Me.

Windows NT
The WindowsNT kernel series was originally written as enterprise-level server and network software. WindowsNT stresses stability and security far more than Windows9x kernels did (although it can be debated whether that stress was good enough). It also handles all string operations internally in Unicode, giving more flexibility when using different languages. Operating systems based on the WindowsNT kernel are: Windows NT (versions 3.1, 3.11, 3.2, 3.5, 3.51 and 4.0), Windows 2000 (NT 5.0), Windows XP (NT 5.1), Windows Server 2003 (NT 5.2), Windows Vista (NT 6.0), Windows 7 (NT 6.1), Windows 7.1 (NT 6.11), Windows 8 (NT 6.2), Windows 8.1 (NT 6.3), and Windows 10 (NT 10.0).

The Microsoft Xbox and Xbox 360 also run a variant of NT, forked from Windows 2000. Most future Microsoft operating system products are based on NT in some shape or form.

Virtual Memory
Memory is organized into "pages" that are 4096 bytes by default. Pages not in current use by the system or any of the applications may be written to a special section on the hard disk known as the "paging file." Use of the paging file may increase performance on some systems, although high latency for I/O to the HDD can actually reduce performance in some instances.

32-bit Windows NT allows for a maximum of 4 GiB of virtual memory address space per process. This is divided into 2 GiB user memory and 2 GiB kernel memory by default.

In some 32-bit versions and editions, the operating system can be started with the /3GB switch which divides this into 3 GiB user memory and 1 GiB kernel memory. Only 32-bit applications that are compiled with the large memory flag can use up to 3 GiB in this mode. The /3GB switch is not supported in 64-bit Windows, but 32-bit applications with the large memory flag can access up to 4 GiB on 64-bit Windows. 64-bit applications are not restricted in this way.

Starting with the Pentium Pro CPU some 32-bit versions and editions can use Physical Address Extensions (the /PAE switch) to access memory above 4 GiB up to 64 GiB. This memory can be accessed by 32-bit applications that support PAE (i.e. some versions of 32-bit Microsoft SQL Server and 32-bit Microsoft Exchange Server). Special configuration is required, however.

System Architecture
The Windows architecture is heavily layered. Function calls that a programmer makes may be redirected 3 times or more before any action is actually performed. There is an unignorable penalty for calling Win32 functions from a user-mode application. However, the upside is equally unignorable: code written in higher levels of the windows system is much easier to write. Complex operations that involve initializing multiple data structures and calling multiple sub-functions can be performed by calling only a single higher-level function.

The Win32 API comprises 3 modules: KERNEL32, USER32, and GDI32. KERNEL32 is layered on top of NTDLL, and most calls to KERNEL32 functions are simply redirected into NTDLL function calls. USER32 and GDI32 are both based on WIN32K (a kernel-mode module, responsible for the Windows "look and feel"), although USER32 also makes many calls to the more-primitive functions in GDI32. This and NTDLL both provide an interface to the Windows NT kernel, NTOSKRNL (see further below).

NTOSKRNL is also partially layered on HAL (Hardware Abstraction Layer), but this interaction will not be considered much in this book. The purpose of this layering is to allow processor variant issues (such as location of resources) to be made separate from the actual kernel itself. A slightly different system configuration thus requires just a different HAL module, rather than a completely different kernel module.

System calls and interrupts
After filtering through different layers of subroutines, most API calls require interaction with part of the operating system. Services are provided via 'software interrupts', traditionally through the "int 0x2e" instruction. This switches control of execution to the NT executive / kernel, where the request is handled. It should be pointed out here that the stack used in kernel mode is different from the user mode stack. This provides an added layer of protection between kernel and user. Once the function completes, control is returned back to the user application.

Both Intel and AMD provide an extra set of instructions to allow faster system calls, the "SYSENTER" instruction from Intel and the SYSCALL instruction from AMD.

Win32 API
Both WinNT and Win9x systems utilize the Win32 API. However, the WinNT version of the API has more functionality and security constructs, as well as Unicode support. Most of the Win32 API can be broken down into 3 separate components, each performing a separate task.

kernel32.dll
Kernel32.dll, home of the KERNEL subsystem, is where non-graphical functions are implemented. Some of the APIs located in KERNEL are: The Heap API, the Virtual Memory API, File I/O API, the Thread API, the System Object Manager, and other similar system services. Most of the functionality of kernel32.dll is implemented in ntdll.dll, but in undocumented functions. Microsoft prefers to publish documentation for kernel32 and guarantee that these APIs will remain unchanged, and then put most of the work in other libraries, which are then not documented.

gdi32.dll
gdi32.dll is the library that implements the GDI subsystem, where primitive graphical operations are performed. GDI diverts most of its calls into WIN32K, but it does contain a manager for GDI objects, such as pens, brushes and device contexts. The GDI object manager and the KERNEL object manager are completely separate.

user32.dll
The USER subsystem is located in the user32.dll library file. This subsystem controls the creation and manipulation of USER objects, which are common screen items such as windows, menus, cursors, etc... USER will set up the objects to be drawn, but will perform the actual drawing by calling on GDI (which in turn will make many calls to WIN32K) or sometimes even calling WIN32K directly. USER utilizes the GDI Object Manager.

Native API
The native API, hereby referred to as the NTDLL subsystem, is a series of undocumented API function calls that handle most of the work performed by KERNEL32. Microsoft also does not guarantee that the native API will remain the same between different versions, as Windows developers modify the software. This gives the risk of native API calls being removed or changed without warning, breaking software that utilizes it.

ntdll.dll
The NTDLL subsystem is located in ntdll.dll. This library contains many API function calls, that all follow a particular naming scheme. Each function has a prefix: Ldr, Nt, Zw, Csr, Dbg, etc... and all the functions that have a particular prefix all follow particular rules.

The "official" native API is usually limited only to functions whose prefix is Nt or Zw. These calls are in fact the same in user-mode: the relevant Export entries map to the same address in memory. However, in kernel-mode, the Zw* system call stubs set the previous mode to kernel-mode, ensuring that certain parameter validation routines are not performed. The origin of the prefix "Zw" is unknown; this prefix was chosen due to its having no significance at all.

In actual implementation, the system call stubs merely load two registers with values required to describe a native API call, and then execute a software interrupt (or the  instruction).

Most of the other prefixes are obscure, but the known ones are:
 * Rtl stands for "Run Time Library", calls which help functionality at runtime (such as RtlAllocateHeap)
 * Csr is for "Client Server Runtime", which represents the interface to the win32 subsystem located in csrss.exe
 * Dbg functions are present to enable debugging routines and operations
 * Ldr provides the ability to load, manipulate and retrieve data from DLLs and other module resources

User Mode Versus Kernel Mode
Many functions, especially Run-time Library routines, are shared between ntdll.dll and ntoskrnl.exe. Most Native API functions, as well as other kernel-mode only functions exported from the kernel are useful for driver writers. As such, Microsoft provides documentation on many of the native API functions with the Microsoft Server 2003 Platform DDK. The DDK (Driver Development Kit) is available as a free download.

ntoskrnl.exe
This module is the Windows NT "'Executive'", providing all the functionality required by the native API, as well as the kernel itself, which is responsible for maintaining the machine state. By default, all interrupts and kernel calls are channeled through ntoskrnl in some way, making it the single most important program in Windows itself. Many of its functions are exported (all of which with various prefixes, a la NTDLL) for use by device drivers.

Win32K.sys
This module is the "Win32 Kernel" that sits on top of the lower-level, more primitive NTOSKRNL. WIN32K is responsible for the "look and feel" of windows, and many portions of this code have remained largely unchanged since the Win9x versions. This module provides many of the specific instructions that cause USER and GDI to act the way they do. It's responsible for translating the API calls from the USER and GDI libraries into the pictures you see on the monitor.

Win64 API
With the advent of 64-bit processors, 64-bit software is a necessity. As a result, the Win64 API was created to utilize the new hardware. It is important to note that the format of many of the function calls are identical in Win32 and Win64, except for the size of pointers, and other data types that are specific to 64-bit address space.

Windows Vista
Microsoft has released a new version of its Windows operation system, named "Windows Vista." Windows Vista may be better known by its development code-name "Longhorn." Microsoft claims that Vista has been written largely from the ground up, and therefore it can be assumed that there are fundamental differences between the Vista API and system architecture, and the APIs and architectures of previous Windows versions. Windows Vista was released January 30th, 2007.

Windows CE/Mobile, and other versions
Windows CE is the Microsoft offering on small devices. It largely uses the same Win32 API as the desktop systems, although it has a slightly different architecture. Some examples in this book may consider WindowsCE.

"Non-Executable Memory"
Recent windows service packs have attempted to implement a system known as "Non-executable memory" where certain pages can be marked as being "non-executable". The purpose of this system is to prevent some of the most common security holes by not allowing control to pass to code inserted into a memory buffer by an attacker. For instance, a shellcode loaded into an overflowed text buffer cannot be executed, stopping the attack in its tracks. The effectiveness of this mechanism is yet to be seen, however.

COM and Related Technologies
COM, and a whole slew of technologies that are either related to COM or are actually COM with a fancy name, is another factor to consider when reversing Windows binaries. COM, DCOM, COM+, ActiveX, OLE, MTS, and Windows DNA are all names for the same subject, or subjects, so similar that they may all be considered under the same heading. In short, COM is a method to export Object-Oriented Classes in a uniform, cross-platform and cross-language manner. In essence, COM is .NET, version 0 beta. Using COM, components written in many languages can export, import, instantiate, modify, and destroy objects defined in another file, most often a DLL. Although COM provides cross-platform (to some extent) and cross-language facilities, each COM object is compiled to a native binary, rather than an intermediate format such as Java or .NET. As a result, COM does not require a virtual machine to execute such objects.

Due to the way that COM works, a lot of the methods and data structures exported by a COM component are difficult to perceive by simply inspecting the executable file. Matters are made worse if the creating programmer has used a library such as ATL to simplify their programming experience. Unfortunately for a reverse engineer, this reduces the contents of an executable into a "Sea of bits", with pointers and data structures everywhere.

Remote Procedure Calls (RPC)
RPC is a generic term referring to techniques that allow a program running on one machine to make calls that actually execute on another machine. Typically, this is done by marshalling all of the data needed for the procedure including any state information stored on the first machine, and building it into a single data structure, which is then transmitted over some communications method to a second machine. This second machine then performs the requested action, and returns a data packet containing any results and potentially changed state information to the originating machine.

In Windows NT, RPC is typically handled by having two libraries that are similarly named, one which generates RPC requests and accepts RPC returns, as requested by a user-mode program, and one which responds to RPC requests and returns results via RPC. A classic example is the print spooler, which consists of two pieces: the RPC stub spoolss.dll, and the spooler proper and RPC service provider, spoolsv.exe. In most machines, which are stand-alone, it would seem that the use of two modules communicating by means of RPC is overkill; why not simply roll them into a single routine? In networked printing, though, this makes sense, as the RPC service provider can be resident physically on a distant machine, with the remote printer, and the local machine can control the printer on the remote machine in exactly the same way that it controls printers on the local machine.

title: X86 Disassembly/Microsoft Windows


text:
X86 Disassembly/Linux

GNU/Linux
The GNU/Linux operating system is open source, but at the same time there is so much that constitutes "GNU/Linux" that it can be difficult to stay on top of all aspects of the system. Here we will attempt to boil down some of the most important concepts of the GNU/Linux Operating System, especially from a reverser's standpoint

System Architecture
The concept of "GNU/Linux" is mostly a collection of a large number of software components that are based on the GNU tools and the Linux kernel. GNU/Linux is itself broken into a number of variants called "distros" which share some similarities, but may also have distinct peculiarities. In a general sense, all GNU/Linux distros are based on a variant of the Linux kernel. However, since each user may edit and recompile their own kernel at will, and since some distros may make certain edits to their kernels, it is hard to proclaim any one version of any one kernel as "the standard". Linux kernels are generally based on the philosophy that system configuration details should be stored in aptly-named, human-readable (and therefore human-editable) configuration files.

The Linux kernel implements much of the core API, but certainly not all of it. Much API code is stored in external modules (although users have the option of compiling all these modules together into a "Monolithic Kernel").

On top of the kernel generally runs one or more shells. Bash is one of the more popular shells, but many users prefer other shells, especially for different tasks.

Beyond the shell, Linux distros frequently offer a GUI (although many distros do not have a GUI at all, usually for performance reasons).

Since each GUI often supplies its own underlying framework and API, certain graphical applications may run on only one GUI. Some applications may need to be recompiled (and a few completely rewritten) to run on another GUI.

Shells
Here are some popular shells:

 * Bash : An acronym for "Bourne Again SHell."

 * Bourne : A precursor to Bash.

 * Csh : C Shell

 * Ksh : Korn Shell

 * TCsh : A Terminal oriented Csh.

 * Zsh : Z Shell

Desktop Environments
Some of the more popular desktop environments:

 * GNOME : GNU Network Object Modeling Environment

 * KDE : K Desktop Environment

Debuggers

 * gdb : The GNU Debugger. It is available on most Linux distributions, and is primarily used to debug ELF executables. manpage

 * winedbg : A debugger for Wine, used to debug Windows executables under Linux. manpage

 * edb : A fully featured plugin-based debugger inspired by the famous OllyDbg. Project page

File Analyzers

 * strings : Finds printable strings in a file. When, for example, a password is stored in the binary itself (defined statically in the source), the string can then be extracted from the binary without ever needing to execute it. manpage

 * file : Determines a file type, useful for determining whether an executable has been stripped and whether it's been dynamically (or statically) linked. manpage

 * objdump : Disassembles object files, executables and libraries. Can list internal file structure and disassemble specific sections. Supports both Intel and AT&T syntax

 * nm : Lists symbols from executable files. Doesn't work on stripped binaries. Used mostly on debugging version of executables.

title: X86 Disassembly/Linux


text:
X86 Disassembly/Windows Executable Files

MS-DOS COM Files
COM files are loaded into RAM exactly as they appear; no change is made at all from the harddisk image to RAM. This is possible due to the segmented memory model of the early x86 line. Two 16-bit registers determine the actual address used for a memory access, a “segment” register specifying a 64K byte window into the 1M+64K byte space (in 16-byte increments) and an “offset” specifying an offset into that window. The segment register would be set by DOS and the COM file would be expected to respect this setting and not ever change the segment registers. The offset registers, however, were fair game and served (for COM files) the same purpose as a modern 32-bit register. The downside was that the offset registers were only 16-bit and, therefore, since COM files could not change the segment registers, COM files were limited to using 64K of RAM. The good thing about this approach, however, was that no extra work was needed by DOS to load and run a COM file: just load the file, set the segment register, and jump to it. (The programs could perform 'near' jumps by just giving an offset to jump to.)

COM files are loaded into RAM at offset $100. The space before that would be used for passing data to and from DOS (for example, the contents of the command line used to invoke the program).

Note that COM files, by definition, cannot be 32-bit. Windows provides support for COM files via a special CPU mode.

MS-DOS EXE Files
One way MS-DOS compilers got around the 64K memory limitation was with the introduction of memory models. The basic concept is to cleverly set different segment registers in the x86 CPU (CS, DS, ES, SS) to point to the same or different segments, thus allowing varying degrees of access to memory. Typical memory models were:
 * tiny: All memory accesses are 16-bit (segment registers unchanged). Produces a .COM file instead of an .EXE file.
 * small: All memory accesses are 16-bit (segment registers unchanged).
 * compact: Data addresses include both segment and offset, reloading the DS or ES registers on access and allowing up to 1M of data. Code accesses don't change the CS register, allowing 64K of code.
 * medium: Code addresses include the segment address, reloading CS on access and allowing up to 1M of code. Data accesses don't change the DS and ES registers, allowing 64K of data.
 * large: Both code and data addresses are (segment, offset) pairs, always reloading the segment addresses. The whole 1M byte memory space is available for both code and data.
 * huge: Same as the large model, with additional arithmetic being generated by the compiler to allow access to arrays larger than 64K.

When looking at an EXE file, one has to decide which memory model was used to build that file.

PE Files
A Portable Executable (PE) file is the standard binary file format for an Executable or DLL under Windows NT, Windows 95, and Win32. The Win32 SDK contains a file, winnt.h, which declares various structs and variables used in the PE files. Some functions for manipulating PE files are also included in imagehlp.dll. PE files are broken down into various sections which can be examined.

Relative Virtual Addressing (RVA)
In a Windows environment, executable modules can be loaded at any point in memory, and are expected to run without problem. To allow multiple programs to be loaded at seemingly random locations in memory, PE files have adopted a tool called RVA: Relative Virtual Addresses. RVAs assume that the "base address" of where a module is loaded into memory is not known at compile time. So, PE files describe the location of data in memory as an offset from the base address, wherever that may be in memory.

Some processor instructions require the code itself to directly identify where in memory some data is. This is not possible when the location of the module in memory is not known at compile time. The solution to this problem is described in the section on "Relocations".

It is important to remember that the addresses obtained from a disassembly of a module will not always match up to the addresses seen in a debugger as the program is running.

File Format
The PE portable executable file format includes a number of informational headers, and is arranged in the following format:

The basic format of a Microsoft PE file

MS-DOS header
Open any Win32 binary executable in a hex editor, and note what you see: The first 2 letters are always the letters "MZ", the initials of Mark Zbikowski, who created the first linker for DOS. To some people, the first few bytes in a file that determine the type of file are called the "magic number," although there is no rule that states that the "magic number" needs to be a single number. Instead, we will use the term "File ID Tag", or simply, File ID. Sometimes this is also known as File Signature.

After the File ID, the hex editor will show several bytes of either random-looking symbols, or whitespace, before the human-readable string "This program cannot be run in DOS mode".

What is this?

Hex Listing of an MS-DOS file header

What you are looking at is the MS-DOS header of the Win32 PE file. To ensure either a) backwards compatibility, or b) graceful decline of new file types, Microsoft has written a series of machine instructions(an example program is listed below the DOS header structure) into the head of each PE file. When a 32-bit Windows file is run in a 16-bit DOS environment, the program will display the error message: "This program cannot be run in DOS mode.", then terminate.

The DOS header is also known by some as the EXE header. Here is the DOS header presented as a C data structure:

After the DOS header there is a stub program mentioned in the paragraph above the DOS header structure. Listed below is a commented example of that program, it was taken from a program compiled with GCC.

PE Header
At offset 60 (0x3C) from the beginning of the DOS header is a pointer to the Portable Executable (PE) File header (e_lfanew in MZ structure). DOS will print the error message and terminate, but Windows will follow this pointer to the next batch of information.

Hex Listing of a PE signature, and the pointer to it

The PE header consists only of a File ID signature, with the value "PE\0\0" where each '\0' character is an ASCII NUL character. This signature indicates a) that this file is a legitimate PE file, and b) the byte order of the file. Byte order will not be considered in this chapter, and all PE files are assumed to be in "little endian" format.

The first big chunk of information lies in the COFF header, directly after the PE signature.

COFF Header
The COFF header is present in both COFF object files (before they are linked) and in PE files where it is known as the "File header". The COFF header has some information that is useful to an executable, and some information that is more useful to an object file.

Here is the COFF header, presented as a C data structure:

Here's a list of possible values it can have.
 * Machine : This field determines what machine the file was compiled for. A hex value of 0x14C (332 in decimal) is the code for an Intel 80386.
 * NumberOfSections : The number of sections that are described at the end of the PE headers.
 * TimeDateStamp : 32 bit time at which this header was generated: is used in the process of "Binding", see below.
 * SizeOfOptionalHeader : this field shows how long the "PE Optional Header" is that follows the COFF header.
 * Characteristics : This is a field of bit flags, that show some characteristics of the file.

PE Optional Header
The "PE Optional Header" is not "optional" per se, because it is required in Executable files, but not in COFF object files. There are two different versions of the optional header depending on whether or not the file is 64 bit or 32 bit. The Optional header includes lots and lots of information that can be used to pick apart the file structure, and obtain some useful information about it.

The PE Optional Header occurs directly after the COFF header, and some sources even show the two headers as being part of the same structure. This wikibook separates them out for convenience.

Here is the 64 bit PE Optional Header presented as a C data structure:

This is the 32 bit version of the PE Optional Header presented as a C data structure:

This is the data_directory(also known as IMAGE_DATA_DIRECTORY) structure as found in the two structures above:

 * Signature : Contains a signature that identifies the image.
 * MajorLinkerVersion : The major version number of the linker.
 * MinorLinkerVersion : The minor version number of the linker.
 * SizeOfCode : The size of the code section, in bytes, or the sum of all such sections if there are multiple code sections.
 * SizeOfInitializedData : The size of the initialized data section, in bytes, or the sum of all such sections if there are multiple initialized data sections.
 * SizeOfUninitializedData : The size of the uninitialized data section, in bytes, or the sum of all such sections if there are multiple uninitialized data sections.
 * AddressOfEntryPoint : A pointer to the entry point function, relative to the image base address. For executable files, this is the starting address. For device drivers, this is the address of the initialization function. The entry point function is optional for DLLs. When no entry point is present, this member is zero.
 * BaseOfCode : A pointer to the beginning of the code section, relative to the image base.
 * BaseOfData : A pointer to the beginning of the data section, relative to the image base.
 * ImageBase : The preferred address of the first byte of the image when it is loaded in memory. This value is a multiple of 64K bytes. The default value for DLLs is 0x10000000. The default value for applications is 0x00400000, except on Windows CE where it is 0x00010000.
 * SectionAlignment : The alignment of sections loaded in memory, in bytes. This value must be greater than or equal to the FileAlignment member. The default value is the page size for the system.
 * FileAlignment : The alignment of the raw data of sections in the image file, in bytes. The value should be a power of 2 between 512 and 64K (inclusive). The default is 512. If the SectionAlignment member is less than the system page size, this member must be the same as SectionAlignment.
 * MajorOSVersion : The major version number of the required operating system.
 * MinorOSVersion : The minor version number of the required operating system.
 * MajorImageVersion : The major version number of the image.
 * MinorImageVersion :The minor version number of the image.
 * MajorSubsystemVersion : The major version number of the subsystem.
 * MinorSubsystemVersion : The minor version number of the subsystem.
 * Win32VersionValue : This member is reserved and must be 0.
 * SizeOfImage : The size of the image, in bytes, including all headers. Must be a multiple of SectionAlignment.
 * SizeOfHeaders : The combined size of the following items, rounded to a multiple of the value specified in the FileAlignment member.
 * e_lfanew member of DOS_Header
 * 4 byte signature
 * size of COFFHeader
 * size of optional header
 * size of all section headers
 * CheckSum : The image file checksum. The following files are validated at load time: all drivers, any DLL loaded at boot time, and any DLL loaded into a critical system process.
 * Subsystem : The Subsystem that will be invoked to run the executable
 * DLLCharacteristics : The DLL characteristics of the image
 * SizeOfStackReserve : The number of bytes to reserve for the stack. Only the memory specified by the SizeOfStackCommit member is committed at load time; the rest is made available one page at a time until this reserve size is reached.
 * SizeOfStackCommit : The number of bytes to commit for the stack.
 * SizeOfHeapReserve :The number of bytes to reserve for the local heap. Only the memory specified by the SizeOfHeapCommit member is committed at load time; the rest is made available one page at a time until this reserve size is reached.
 * SizeOfHeapCommit : The number of bytes to commit for the local heap.
 * LoaderFlags : This member is obsolete.
 * NumberOfRvaAndSizes : The number of directory entries in the remainder of the optional header. Each entry describes a location and size.
 * DataDirectory : Possibly the most interesting member of this structure. Provides RVAs and sizes which locate various data structures, which are used for setting up the execution environment of a module. The data structures that the array of DataDirectory points to can be found in the various sections of the file as pointed to by the Section Table. The details of what these structures do exist in other sections of this page. The most interesting entries in DataDirectory are as follows: Export Directory, Import Directory, Resource Directory, and the Bound Import directory. The .NET descriptor table (CLI Header) contains the metadata of the .NET assembly, the table is an IMAGE_COR20_HEADER structure, which is defined in winnt.h. Note that the offsets in bytes are relative to the beginning of the optional header.

Section Table
Immediately after the PE Optional Header we find a section table. The section table consists of an array of IMAGE_SECTION_HEADER structures. The number of structures that we find in the file are determined by the member NumberOfSections in the COFF Header. Each structure is 40 bytes in length. Pictured below is a hex dump from a program I am writing depicting the section table:

The outlined areas correlate to the Name member of three IMAGE_SECTION_HEADER structures

The IMAGE_SECTION_HEADER defined as a C structure is as follows:

 * Name : 8-byte null-padded UTF-8 string(the string may not be null terminated if all 8 characters are used). For longer names, this member will contain '/' followed by an ASCII representation of a decimal number that is an offset into the string table. Executable images do not use a string table and do not support section names greater than 8 characters.

 * Misc : PhysicalAddress - The file address.
 * VirtualSize - The total size of the section when loaded into memory, in bytes. If this value is greater than the SizeOfRawData member, the section is filled with zeroes. This field is valid only for executable images and should be set to 0 for object files.
 * The Misc member should be considered unreliable unless the linker and the behavior of the linker that was used is known.

 * VirtualAddress : The address of the first byte of the section when loaded into memory, relative to the image base. For object files, this is the address of the first byte before relocation is applied.

 * SizeOfRawData : The size of the initialized data on disk, in bytes. This value must be a multiple of the FileAlignment member of the PE Optional Header structure. If this value is less than the VirtualSize member, the remainder of the section is filled with zeroes. If the section contains only uninitialized data, the value is 0.

 * PointerToRawData : A file pointer relative to the beginning of the file to the first page within the COFF file. This value must be a multiple of the FileAlignment member of the PE Optional Header structure. If a section contains only uninitialized data this value should be 0.

 * PointerToRelocations : A file pointer to the beginning of the relocation entries for the section. If there are no relocations, this value is 0.

 * PointerToLinenumbers : A file pointer to the beginning of the line-number entries for the section. If there are no COFF line numbers, this value is 0.

 * NumberOfRelocations : The number of relocation entries for the section. This value is 0 for executable images.

 * NumberOfLinenumbers : The number of line-number entries for the section.

The table below defines the possible 32-bit mask values for this member:
 * Characteristics : The characteristics of the image.

A PE loader will place the sections of the executable image at the locations specified by these section descriptors (relative to the base address) and usually the alignment is 0x1000, which matches the size of pages on the x86.

Common sections are:
 * 1) .text/.code/CODE/TEXT  - Contains executable code (machine instructions)
 * 2) .textbss/TEXTBSS       - Present if Incremental Linking is enabled
 * 3) .data/.idata/DATA/IDATA - Contains initialised data
 * 4) .bss/BSS               - Contains uninitialised data
 * 5) .rsrc                  - Contains resource data

What is linking?
Whenever a developer writes a program, there are a number of subroutines and functions which are expected to be implemented already, saving the writer the hassle of having to write out more code or work with complex data structures. Instead, the coder need only declare one call to the subroutine, and the linker will decide what happens next.

There are two types of linking that can be used: static and dynamic. Static uses a library of precompiled functions. This precompiled code can be inserted into the final executable to implement a function, saving the programmer a lot of time. In contrast, dynamic linking allows subroutine code to reside in a different file (or module), which is loaded at runtime by the operating system. This is also known as a "Dynamically linked library", or DLL. A library is a module containing a series of functions or values that can be exported. This is different from the term executable, which imports things from libraries to do what it wants. From here on, "module" means any file of PE format, and a "Library" is any module which exports and imports functions and values.

Dynamically linking has the following benefits: This section discusses how this is achieved using the PE file format. An important point to note at this point is that anything can be imported or exported between modules, including variables as well as subroutines.
 * It saves disk space, if more than one executable links to the library module
 * Allows instant updating of routines, without providing new executables for all applications
 * Can save space in memory by mapping the code of a library into more than one process
 * Increases abstraction of implementation. The method by which an action is achieved can be modified without the need for reprogramming of applications. This is extremely useful for backward compatibility with operating systems.

Loading
The downside of dynamically linking modules together is that, at runtime, the software which is initialising an executable must link these modules together. For various reasons, you cannot declare that "The function in this dynamic library will always exist in memory here". If that memory address is unavailable or the library is updated, the function will no longer exist there, and the application trying to use it will break. Instead, each module (library or executable) must declare what functions or values it exports to other modules, and also what it wishes to import from other modules.

As said above, a module cannot declare where in memory it expects a function or value to be. Instead, it declares where in its own memory it expects to find a pointer to the value it wishes to import. This permits the module to address any imported value, wherever it turns up in memory.

Exports
Exports are functions and values in one module that have been declared to be shared with other modules. This is done through the use of the "Export Directory", which is used to translate between the name of an export (or "Ordinal", see below), and a location in memory where the code or data can be found. The start of the export directory is identified by the IMAGE_DIRECTORY_ENTRY_EXPORT entry of the resource directory. All export data must exist in the same section. The directory is headed by the following structure: The "Characteristics" value is generally unused, TimeDateStamp describes the time the export directory was generated, MajorVersion and MinorVersion should describe the version details of the directory, but their nature is undefined. These values have little or no impact on the actual exports themselves. The "Name" value is an RVA to a zero terminated ASCII string, the name of this library name, or module.

Names and Ordinals
Each exported value has both a name and an "ordinal" (a kind of index). The actual exports themselves are described through AddressOfFunctions, which is an RVA to an array of RVAs, each pointing to a different function or value to be exported. The size of this array is in the value NumberOfFunctions. Each of these functions has an ordinal. The "Base" value is used as the ordinal of the first export, and the next RVA in the array is Base+1, and so forth.

Each entry in the AddressOfFunctions array is identified by a name, found through the RVA AddressOfNames. The data where AddressOfNames points to is an array of RVAs, of the size NumberOfNames. Each RVA points to a zero terminated ASCII string, each being the name of an export. There is also a second array, pointed to by the RVA in AddressOfNameOrdinals. This is also of size NumberOfNames, but each value is a 16 bit word, each value being an ordinal. These two arrays are parallel and are used to get an export value from AddressOfFunctions. To find an export by name, search the AddressOfNames array for the correct string and then take the corresponding value from the AddressOfNameOrdinals array. This value is then used as index to AddressOfFunctions (yes, it's 0-based index actually, NOT base-biased ordinal, as the official documentation suggests!).

Forwarding
As well as being able to export functions and values in a module, the export directory can forward an export to another library. This allows more flexibility when re-organising libraries: perhaps some functionality has branched into another module. If so, an export can be forwarded to that library, instead of messy reorganising inside the original module.

Forwarding is achieved by making an RVA in the AddressOfFunctions array point into the section which contains the export directory, something that normal exports should not do. At that location, there should be a zero terminated ASCII string of format "LibraryName.ExportName" for the appropriate place to forward this export to.

Imports
The other half of dynamic linking is importing functions and values into an executable or other module. Before runtime, compilers and linkers do not know where in memory a value that needs to be imported could exist. The import table solves this by creating an array of pointers at runtime, each one pointing to the memory location of an imported value. This array of pointers exists inside of the module at a defined RVA location. In this way, the linker can use addresses inside of the module to access values outside of it.

The Import directory
The start of the import directory is pointed to by both the IMAGE_DIRECTORY_ENTRY_IAT and IMAGE_DIRECTORY_ENTRY_IMPORT entries of the resource directory (the reason for this is uncertain). At that location, there is an array of IMAGE_IMPORT_DESCRIPTOR structures. Each of these identify a library or module that has a value we need to import. The array continues until an entry where all the values are zero. The structure is as follows: The TimeDateStamp is relevant to the act of "Binding", see below. The Name value is an RVA to an ASCII string, naming the library to import. ForwarderChain will be explained later. The only thing of interest at this point, are the RVAs OriginalFirstThunk and FirstThunk. Both these values point to arrays of RVAs, each of which point to a IMAGE_IMPORT_BY_NAMES struct. The arrays are terminated with an entry that is equal to zero. These two arrays are parallel and point to the same structure, in the same order. The reason for this will become apparent shortly.

Each of these IMAGE_IMPORT_BY_NAMES structs has the following form: "Name" is an ASCII string of any size that names the value to be imported. This is used when looking up a value in the export directory (see above) through the AddressOfNames array. The "Hint" value is an index into the AddressOfNames array; to save searching for a string, the loader first checks the AddressOfNames entry corresponding to "Hint".

To summarise: The import table consists of a large array of IMAGE_IMPORT_DESCRIPTORs, terminated by an all-zero entry. These descriptors identify a library to import things from. There are then two parallel RVA arrays, each pointing at IMAGE_IMPORT_BY_NAME structures, which identify a specific value to be imported.

Imports at runtime
Using the above import directory at runtime, the loader finds the appropriate modules, loads them into memory, and seeks the correct export. However, to be able to use the export, a pointer to it must be stored somewhere in the importing module's memory. This is why there are two parallel arrays, OriginalFirstThunk and FirstThunk, identifying IMAGE_IMPORT_BY_NAME structures. Once an imported value has been resolved, the pointer to it is stored in the FirstThunk array. It can then be used at runtime to address imported values.

Bound imports
The PE file format also supports a peculiar feature known as "binding". The process of loading and resolving import addresses can be time consuming, and in some situations this is to be avoided. If a developer is fairly certain that a library is not going to be updated or changed, then the addresses in memory of imported values will not change each time the application is loaded. So, the import address can be precomputed and stored in the FirstThunk array before runtime, allowing the loader to skip resolving the imports - the imports are "bound" to a particular memory location. However, if the versions numbers between modules do not match, or the imported library needs to be relocated, the loader will assume the bound addresses are invalid, and resolve the imports anyway.

The "TimeDateStamp" member of the import directory entry for a module controls binding; if it is set to zero, then the import directory is not bound. If it is non-zero, then it is bound to another module. However, the TimeDateStamp in the import table must match the TimeDateStamp in the bound module's FileHeader, otherwise the bound values will be discarded by the loader.

Forwarding and binding
Binding can of course be a problem if the bound library / module forwards its exports to another module. In these cases, the non-forwarded imports can be bound, but the values which get forwarded must be identified so the loader can resolve them. This is done through the ForwarderChain member of the import descriptor. The value of "ForwarderChain" is an index into the FirstThunk and OriginalFirstThunk arrays. The OriginalFirstThunk for that index identifies the IMAGE_IMPORT_BY_NAME structure for a import that needs to be resolved, and the FirstThunk for that index is the index of another entry that needs to be resolved. This continues until the FirstThunk value is -1, indicating no more forwarded values to import.

Resources
Resources are data items in modules which are difficult to be stored or described using the chosen programming language. This requires a separate compiler or resource builder, allowing insertion of dialog boxes, icons, menus, images, and other types of resources, including arbitrary binary data. Although a number of Resource API calls can be used to retrieve resources from a PE file, we are going to look at the resources without the use of those APIs.

Locating the Resource Section
The first thing we need to do when we want to manually manipulate a file's resources is to find the resource section. To do this we need some information found in the DataDirectory array and the Section Table. We need the RVA stored in the VirtualAddress member of the DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] structure found in the PE Optional Header. Once the RVA is known we can then lookup that RVA in the Section Table by comparing the VirtualAddress member of the DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] structure with the VirtualAddress member of an IMAGE_SECTION_HEADER. Except in rare cases, the VirtualAddress member of the DataDirectory structure will equal the value of the VirtualAddress member of an IMAGE_SECTION_HEADER. The name member of that particular IMAGE_SECTION_HEADER will except in rare cases be named, '.rsrc'. Once the correct IMAGE_SECTION_HEADER structure is found the PointerToRawData member can be used to locate the resource section. The PointerToRawData member contains an offset from the beginning of the file that will lead you to the first byte of the resource section. The picture below depicts an example of a DataDirectory array on the left with an IMAGE_SECTION_HEADER on the right populated with the information for the resource section. We can see the highlighted line underneath of Directory Information '2 RVA: 20480 Size: 3512' has a VirtualAddress(RVA) of 20480, this corresponds to the VirtualAddress of 20480 for the .rsrc(resource) section. You can also see that the value of PointerToRawData is equal to 7168. In this particular PE file we will find the resource section starting at offset 7168 from the beginning of the file.

Once the resource section is found we can start looking at the structures and data contained in that section.

Resource structures
The IMAGE_RESOURCE_DIRECTORY is the very first structure we come across and it starts at the 1st byte of the resource section.

IMAGE_RESOURCE_DIRECTORY structure: Characteristics is unused, and TimeDateStamp is normally the time of creation, although it doesn't matter if it's set or not. MajorVersion and MinorVersion relate to the versioning info of the resources: the fields have no defined values. Immediately following the IMAGE_RESOURCE_DIRECTORY structure is a series of IMAGE_RESOURCE_DIRECTORY_ENTRYs, the number of which are defined by the total of NumberOfNamedEntries and NumberOfIdEntries. The first portion of these entries are for named resources, the latter for ID resources, depending on the values in the IMAGE_RESOURCE_DIRECTORY struct. The actual shape of the resource entry structure is as follows: The NameId value has dual purpose: if the most significant bit (or sign bit) is clear, then the lower 16 bits are an ID number of the resource. Alternately, if the top bit is set, then the lower 31 bits make up an offset from the start of the resource data to the name string of this particular resource. The Data value also has a dual purpose: if the most significant bit is set, the remaining 31 bits form an offset from the start of the resource data to another IMAGE_RESOURCE_DIRECTORY (i.e. this entry is an interior node of the resource tree). Otherwise, this is a leaf node, and Data contains the offset from the start of the resource data to a structure which describes the specifics of the resource data itself (which can be considered to be an ordered stream of bytes): The Data value contains an RVA to the actual resource data, Size is self-explanatory, and CodePage contains the Unicode codepage to be used for decoding Unicode-encoded strings in the resource (if any). Reserved should be set to 0.

Layout
The above system of resource directory and entries allows simple storage of resources, by name or ID number. However, this can get very complicated very quickly. Different types of resources, the resources themselves, and instances of resources in other languages can become muddled in just one directory of resources. For this reason, the resource directory has been given a structure to work by, allowing separation of the different resources.

For this purpose, the "Data" value of resource entries points at another IMAGE_RESOURCE_DIRECTORY structure, forming a tree-diagram like organisation of resources. The first level of resource entries identifies the type of the resource: cursors, bitmaps, icons and similar. They use the ID method of identifying the resource entries, of which there are twelve defined values in total. More user defined resource types can be added. Each of these resource entries points at a resource directory, naming the actual resources themselves. These can be of any name or value. These point at yet another resource directory, which uses ID numbers to distinguish languages, allowing different specific resources for systems using a different language. Finally, the entries in the language directory actually provide the offset to the resource data itself, the format of which is not defined by the PE specification and can be treated as an arbitrary stream of bytes.

Windows DLL Files
Windows DLL files are a brand of PE file with a few key differences:

 * A .DLL file extension
 * A  entry point, instead of a WinMain or main.
 * The DLL flag set in the PE header.

DLLs may be loaded in one of two ways, a) at load-time, or b) by calling the LoadModule Win32 API function.

Function Exports
Functions are exported from a DLL file by using the following syntax:

The "__declspec" keyword here is not a C language standard, but is implemented by many compilers to set extendable, compiler-specific options for functions and variables. Microsoft C Compiler and GCC versions that run on windows allow for the __declspec keyword, and the dllexport property.

Functions may also be exported from regular .exe files, and .exe files with exported functions may be called dynamically in a similar manner to .dll files. This is a rare occurrence, however.

Identifying DLL Exports
There are several ways to determine which functions are exported by a DLL. A common approach is to use dumpbin in the following manner:

dumpbin /EXPORTS

This will post a list of the function exports, along with their ordinal and RVA to the console.

Function Imports
In a similar manner to function exports, a program may import a function from an external DLL file. The dll file will load into the process memory when the program is started, and the function will be used like a local function. DLL imports need to be prototyped in the following manner, for the compiler and linker to recognize that the function is coming from an external library:

Identifying DLL Imports
If is often useful to determine which functions are imported from external libraries when examining a program. To list import files to the console, use dumpbin in the following manner:

dumpbin /IMPORTS

You can also use depends.exe to list imported and exported functions. Depends is a a GUI tool and comes with Microsoft Platform SDK.


text:
X86 Disassembly/Calling Conventions

Calling Conventions
Calling conventions are a standardized method for functions to be implemented and called by the machine. A calling convention specifies the method that a compiler sets up to access a subroutine. In theory, code from any compiler can be interfaced together, so long as the functions all have the same calling conventions. In practice however, this is not always the case.

Calling conventions specify how arguments are passed to a function, how return values are passed back out of a function, how the function is called, and how the function manages the stack and its stack frame. In short, the calling convention specifies how a function call in C or C++ is converted into assembly language. Needless to say, there are many ways for this translation to occur, which is why it's so important to specify certain standard methods. If these standard conventions did not exist, it would be nearly impossible for programs created using different compilers to communicate and interact with one another.

There are three major calling conventions that are used with the C language on 32-bit x86 processors: STDCALL, CDECL, and FASTCALL. In addition, there is another calling convention typically used with C++: THISCALL. There are other calling conventions as well, including PASCAL and FORTRAN conventions, among others.

Other processors, such as AMD64 processors (also called x86-64 processors), each have their own calling convention.

Notes on Terminology
There are a few terms that we are going to be using which are mostly common sense, but which are worthy of stating directly:

 * Passing arguments : "passing arguments" is a way of saying that the calling function is writing data in the place where the called function will look for them. Arguments are passed before the call instruction is executed.

 * Right-to-Left and Left-to-Right : These describe the manner in which arguments are passed to the subroutine, in terms of the High-level code. For instance, the following C function call:

will generate the following code if passed Left-to-Right:

and will generate the following code if passed Right-to-Left:

 * Return value : Some functions return a value, and that value must be received reliably by the function's caller. The called function places its return value in a place where the calling function can get it when execution returns. The called function stores the return value before executing the ret instruction.

 * Cleaning the stack : When arguments are pushed onto the stack, eventually they must be popped back off again. Whichever function, the caller or the callee, is responsible for cleaning the stack must reset the stack pointer to eliminate the passed arguments.

 * Calling function (the caller): The "parent" function that calls the subroutine. Execution resumes in the calling function directly after the subroutine call, unless the program terminates inside the subroutine.

 * Called function (the callee): The "child" function that gets called by the "parent."

 * Name Decoration : When C code is translated to assembly code, the compiler will often "decorate" the function name by adding extra information that the linker will use to find and link to the correct functions. For most calling conventions, the decoration is very simple (often only an extra symbol or two to denote the calling convention), but in some extreme cases (notably C++ "thiscall" convention), the names are "mangled" severely.

 * Entry sequence (the function prologue): a few instructions at the beginning of a function, which prepare the stack and registers for use within the function.

 * Exit sequence (the function epilogue): a few instructions at the end of a function, which restore the stack and registers to the state expected by the caller, and return to the caller. Some calling conventions clean the stack in the exit sequence.

 * Call sequence: a few instructions in the middle of a function (the caller) which pass the arguments and call the called function. After the called function has returned, some calling conventions have one more instruction in the call sequence to clean the stack.

Standard C Calling Conventions
The C language, by default, uses the CDECL calling convention, but most compilers allow the programmer to specify another convention via a specifier keyword. These keywords are not part of the ISO-ANSI C standard, so you should always check with your compiler documentation about implementation specifics.

If a calling convention other than CDECL is to be used, or if CDECL is not the default for your compiler, and you want to manually use it, you must specify the calling convention keyword in the function declaration itself, and in any prototypes for the function. This is important because both the calling function and the called function need to know the calling convention.

CDECL
In the CDECL calling convention the following holds:
 * Arguments are passed on the stack in Right-to-Left order, and return values are passed in eax.
 * The calling function cleans the stack. This allows CDECL functions to have variable-length argument lists (aka variadic functions). For this reason the number of arguments is not appended to the name of the function by the compiler, and the assembler and the linker are therefore unable to determine if an incorrect number of arguments is used.

Variadic functions usually have special entry code, generated by the va_start, va_arg C pseudo-functions.

Consider the following C instructions:

and the following function call:

These would produce the following assembly listings, respectively:

and

When translated to assembly code, CDECL functions are almost always prepended with an underscore (that's why all previous examples have used "_" in the assembly code).

STDCALL
STDCALL, also known as "WINAPI" (and a few other names, depending on where you are reading it) is used almost exclusively by Microsoft as the standard calling convention for the Win32 API. Since STDCALL is strictly defined by Microsoft, all compilers that implement it do it the same way.

 * STDCALL passes arguments right-to-left, and returns the value in eax. (The Microsoft documentation erroneously claimed that arguments are passed left-to-right, but this is not the case.)
 * The called function cleans the stack, unlike CDECL. This means that STDCALL doesn't allow variable-length argument lists.

Consider the following C function:

and the calling instruction:

These will produce the following respective assembly code fragments:

and

There are a few important points to note here:

 * 1) In the function body, the ret instruction has an (optional) argument that indicates how many bytes to pop off the stack when the function returns.
 * 2) STDCALL functions are name-decorated with a leading underscore, followed by an @, and then the number (in bytes) of arguments passed on the stack. This number will always be a multiple of 4, on a 32-bit aligned machine.

FASTCALL
The FASTCALL calling convention is not completely standard across all compilers, so it should be used with caution. In FASTCALL, the first 2 or 3 32-bit (or smaller) arguments are passed in registers, with the most commonly used registers being edx, eax, and ecx. Additional arguments, or arguments larger than 4-bytes are passed on the stack, often in Right-to-Left order (similar to CDECL). The calling function most frequently is responsible for cleaning the stack, if needed.

Because of the ambiguities, it is recommended that FASTCALL be used only in situations with 1, 2, or 3 32-bit arguments, where speed is essential.

The following C function:

and the following C function call:

Will produce the following assembly code fragments for the called, and the calling functions, respectively:

and

The name decoration for FASTCALL prepends an @ to the function name, and follows the function name with @x, where x is the number (in bytes) of arguments passed to the function.

Many compilers still produce a stack frame for FASTCALL functions, especially in situations where the FASTCALL function itself calls another subroutine. However, if a FASTCALL function doesn't need a stack frame, optimizing compilers are free to omit it.

Commonly gcc and Windows FASTCALL convention pushes parameters one and two into ecx and edx, respectively, before pushing any remaining parameters onto the stack. Calling MyFunction3 using this standard would look like:

C++ Calling Convention
C++ requires that non-static methods of a class be called by an instance of the class. Therefore it uses its own standard calling convention to ensure that pointers to the object are passed to the function: THISCALL.

THISCALL
In THISCALL, the pointer to the class object is passed in ecx, the arguments are passed Right-to-Left on the stack, and the return value is passed in eax.

For instance, the following C++ instruction:

Would form the following asm code:

At least, it would look like the assembly code above if it weren't for name mangling.

Name Mangling
Because of the complexities inherent in function overloading, C++ functions are heavily name-decorated to the point that people often refer to the process as "Name Mangling." Unfortunately C++ compilers are free to do the name-mangling differently since the standard does not enforce a convention. Additionally, other issues such as exception handling are also not standardized.

Since every compiler does the name-mangling differently, this book will not spend too much time discussing the specifics of the algorithm. Notice that in many cases, it's possible to determine which compiler created the executable by examining the specifics of the name-mangling format. We will not cover this topic in this much depth in this book, however.

Here are a few general remarks about THISCALL name-mangled functions:

 * They are recognizable on sight because of their complexity when compared to CDECL, FASTCALL, and STDCALL function name decorations
 * They sometimes include the name of that function's class.
 * They almost always include the number and type of the arguments, so that overloaded functions can be differentiated by the arguments passed to it.

Here is an example of a C++ class and function declaration:

And here is the resultant mangled name:

?MyFunction@MyClass@@QAEHH@Z

Extern "C"
In a C++ source file, functions placed in an  block are guaranteed not to be mangled. This is done frequently when libraries are written in C++, and the functions need to be exported without being mangled. Even though the program is written in C++ and compiled with a C++ compiler, some of the functions might therefore not be mangled and will use one of the ordinary C calling conventions (typically CDECL).

Note on Name Decorations
We've been discussing name decorations in this chapter, but the fact is that in pure disassembled code there typically are no names whatsoever, especially not names with fancy decorations. The assembly stage removes all these readable identifiers, and replaces them with the binary locations instead. Function names really only appear in two places:

 * 1) Listing files produced during compilation
 * 2) In export tables, if functions are exported

When disassembling raw machine code, there will be no function names and no name decorations to examine. For this reason, you will need to pay more attention to the way parameters are passed, the way the stack is cleaned, and other similar details.

While we haven't covered optimizations yet, suffice it to say that optimizing compilers can even make a mess out of these details. Functions which are not exported do not necessarily need to maintain standard interfaces, and if it is determined that a particular function does not need to follow a standard convention, some of the details will be optimized away. In these cases, it can be difficult to determine what calling conventions were used (if any), and it is even difficult to determine where a function begins and ends. This book cannot account for all possibilities, so we try to show as much information as possible, with the knowledge that much of the information provided here will not be available in a true disassembly situation.

title: X86 Disassembly/Calling Conventions


text:
User:Danny~enwikibooks

Danny is hereby awarded this printing press for pressing so hard to get Wikijunior Solar System to print.

title: User:Danny~enwikibooks


text:
X86 Disassembly/Functions and Stack Frames

Functions and Stack Frames
In the execution environment, functions are frequently set up with a "stack frame" to allow access to both function parameters, and automatic local function variables. The idea behind a stack frame is that each subroutine can act independently of its location on the stack, and each subroutine can act as if it is the top of the stack.

When a function is called, a new stack frame is created at the current esp location. A stack frame acts like a partition on the stack. All items from previous functions are higher up on the stack, and should not be modified. Each current function has access to the remainder of the stack, from the stack frame until the end of the stack page. The current function always has access to the "top" of the stack, and so functions do not need to take account of the memory usage of other functions or programs.

Standard Entry Sequence
For many compilers, the standard function entry sequence is the following piece of code (X is the total size, in bytes, of all automatic local variables used in the function):

For example, here is a C function code fragment and the resulting assembly instructions (the code generated with ABI standards won't have "sub esp, 12" instruction due to red zones):

This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:

This all seems well and good, but what is the purpose of ebp in this setup? Why save the old value of ebp and then point ebp to the top of the stack, only to change the value of esp with the next instruction? The answer is function parameters.

Consider the following C function declaration:

It produces the following assembly code:

Which is exactly as one would expect. So, what exactly does ebp do, and where are the function parameters stored? The answer is found when we call the function.

Consider the following C function call:

This will create the following assembly code (using a Right-to-Left calling convention called CDECL, explained later):

Note: Remember that the call x86 instruction is basically equivalent to

It turns out that the function arguments are all passed on the stack! Therefore, when we move the current value of the stack pointer (esp) into ebp, we are pointing ebp directly at the function arguments. As the function code pushes and pops values, ebp is not affected by esp. Remember that pushing basically does this:

This means that first the return address and then the old value of ebp are put on the stack. Therefore [ebp] points to the location of the old value of ebp, [ebp + 4] points to the return address, and [ebp + 8] points to the first function argument. Here is a (crude) representation of the stack at this point:

| 5 | [ebp + 12] (2nd argument) | 10 | [ebp + 8] (1st argument) | RA | [ebp + 4] (return address) | FP | [ebp]     (old ebp value) |   | [ebp - 4]  (1st local variable) :   : :    : |    | [ebp - X]  (esp - the current stack pointer. The use of push / pop is valid now)

The stack pointer value may change during the execution of the current function. In particular this happens when:
 * parameters are passed to another function;
 * the pseudo-function "alloca" is used.

[FIXME: When parameters are passed into another function the esp changing is not an issue. When that function returns the esp will be back to its old value. So why does ebp help there. This needs better explanation. (The real explanation is here, ESP is not really needed: https://learn.microsoft.com/en-us/archive/blogs/larryosterman/fpo)] This means that the value of esp cannot be reliably used to determine (using the appropriate offset) the memory location of a specific local variable. To solve this problem, many compilers access local variables using negative offsets from the ebp registers. This allows us to assume that the same offset is always used to access the same variable (or parameter). For this reason, the ebp register is called the frame pointer, or FP.

Standard Exit Sequence
The Standard Exit Sequence must undo the things that the Standard Entry Sequence does. To this effect, the Standard Exit Sequence must perform the following tasks, in the following order:

 * 1) Remove space for local variables, by reverting esp to its old value.
 * 2) Restore the old value of ebp to its old value, which is on top of the stack.
 * 3) Return to the calling function with a ret command.

As an example, the following C code:

Will create the following assembly code:

Non-Standard Stack Frames
Frequently, reversers will come across a subroutine that doesn't set up a standard stack frame. Here are some things to consider when looking at a subroutine that does not start with a standard sequence:

Using Uninitialized Registers
When a subroutine starts using data in an uninitialized register, that means that the subroutine expects external functions to put data into that register before it gets called. Some calling conventions pass arguments in registers, but sometimes a compiler will not use a standard calling convention.

"static" Functions
In C, functions may optionally be declared with the static keyword, as such:

The static keyword causes a function to have only local scope, meaning it may not be accessed by any external functions (it is strictly internal to the given code file). When an optimizing compiler sees a static function that is only referenced by calls (no references through function pointers), it "knows" that external functions cannot possibly interface with the static function (the compiler controls all access to the function), so the compiler doesn't bother making it standard.

Hot Patch Prologue
Some Windows functions set up a regular stack frame as explained above, but start out with the apparently non-sensical line This instruction is assembled into 2 bytes which serve as a placeholder for future function patches. Taken as a whole such a function might look like this: If such a function needs to be replaced without reloading the application (or restarting the machine in case of kernel patches) it can be achieved by inserting a jump to the replacement function. A short jump instruction (which can jump +/- 127 bytes) requires 2 bytes of storage space - just the amount that the "mov edi,edi" placeholder provides. A jump to any memory location, in this case to our replacement function, requires 5 bytes. These are provided by the 5 no-operation bytes just preceding the function. If a function thus patched gets called it will first jump back by 5 bytes and then do a long jump to the replacement function. After the patch the memory might look like this The reason for using a 2-byte mov instruction at the beginning instead of putting 5 nops there directly, is to prevent corruption during the patching process. There would be a risk with replacing 5 individual instructions if the instruction pointer is currently pointing at any one of them. Using a single mov instruction as placeholder on the other hand guarantees that the patching can be completed as an atomic transaction.

Local Static Variables
Local static variables cannot be created on the stack, since the value of the variable is preserved across function calls. We'll discuss local static variables and other types of variables in a later chapter.


text:
Talk:Quantum Mechanics/Operators and Commutators

Schroedinger mistake
Hi, There's a mistake in SE, SE is a second order PDE and your hamiltonian operator has only first order differential... to cut a long story short. You have: $$ i \hbar \frac{\partial}{\partial t}\Psi = - \frac{\hbar^2}{2m} \frac{\partial}{\partial x} \Psi + V(x)\Psi $$ should be: $$ i \hbar \frac{\partial}{\partial t}\Psi = - \frac{\hbar^2}{2m} \frac{{\partial}^2}{{\partial x}^2} \Psi + V(x)\Psi $$ This error persists over the entire page. Dkronst 17:19, 8 September 2005 (UTC)

 * I think I got them all

Operator mistake
Also x has to be considered as an operator. It acts as multiplication with x:

$$ \hat x \Psi(x) = x \Psi(x) $$

This also extends to the potential energy V(x). It is a function of the position operator, and thus, it acts as multiplication with V(x) :

$$ V(\hat x) \Psi(x) = V(x) \Psi(x) $$

If one does not consider position operators here, the reader has no chance to understand the basic commutation rules for momentum and position operators.

IIIHIII (discuss • contribs) 17:14, 18 December 2016 (UTC)


text:
User:Fastfission~enwikibooks

I am a user of the English Wikipedia. Please see my page there if you want to leave me a message or ask any questions. Thanks.

Worklist

 * The Descent of Man
 * How to write a research paper in History

To write someday

 * Fair use in U.S. copyright law
 * Copyleft licensing
 * Drawing simple scientific diagrams with Inkscape

title: User:Fastfission~enwikibooks


text:
User talk:Fastfission~enwikibooks

I am a user of the English Wikipedia. Please see my page there if you want to leave me a message or ask any questions. Thanks.

Your account will be renamed
Hello,

The developer team at Wikimedia is making some changes to how accounts work, as part of our on-going efforts to provide new and better tools for our users like cross-wiki notifications. These changes will mean you have the same account name everywhere. This will let us give you new features that will help you edit and discuss better, and allow more flexible user permissions for tools. One of the side-effects of this is that user accounts will now have to be unique across all 900 Wikimedia wikis. See the announcement for more information.

Unfortunately, your account clashes with another account also called Fastfission. To make sure that both of you can use all Wikimedia projects in future, we have reserved the name Fastfission~enwikibooks that only you will have. If you like it, you don't have to do anything. If you do not like it, you can pick out a different name.

Your account will still work as before, and you will be credited for all your edits made so far, but you will have to use the new account name when you log in.

Sorry for the inconvenience.

Yours, Keegan Peterzell Community Liaison, Wikimedia Foundation 23:09, 17 March 2015 (UTC)

Renamed
 This account has been renamed as part of single-user login finalisation. If you own this account you can |log in using your previous username and password for more information. If you do not like this account's new name, you can choose your own using this form after logging in: . -- Keegan (WMF) (talk) 04:59, 19 April 2015 (UTC)

title: User talk:Fastfission~enwikibooks


text:
How to Write a Research Paper in History

Many people who have not written a research paper in the genre of History often have difficulty with understanding where to start. This Wikibook is an attempt to outline some of the basics for writing a research paper in History, ideally at the collegiate or graduate level.

Table of contents

 * /Picking a topic/
 * /Finding sources/
 * /Doing research/
 * /Organizing your work/
 * /Thinking on your own/
 * /Writing the paper/
 * /Citing your sources/
 * /Additional resources/