Magic number (programming)

In computer programming, the term magic number has multiple meanings. It could refer to one or more of the following:

Format indicator

Magic number origin

The format indicator type of magic number was first found in early Seventh Edition source code of the Unix operating system and, although it has lost its original meaning, the term magic number has become part of computer industry lexicon.

When Unix was ported to one of the first DEC PDP-11/20s it did not have memory protection and, therefore, early versions of Unix used the relocatable memory reference model.[1] Pre-Sixth Edition Unix versions read an executable file into memory and jumped to the first low memory address of the program, relative address zero. With the development of paged versions of Unix, a header was created to describe the executable image components. Also, a branch instruction was inserted as the first word of the header to skip the header and start the program. In this way a program could be run in the older relocatable memory reference (regular) mode or in paged mode. As more executable formats were developed, new constants were added by incrementing the branch offset.[2]

In the Sixth Edition source code of the Unix program loader, the exec() function read the executable (binary) image from the file system. The first 8 bytes of the file was a header containing the sizes of the program (text) and initialized (global) data areas. Also, the first 16-bit word of the header was compared to two constants to determine if the executable image contained relocatable memory references (normal), the newly implemented paged read-only executable image, or the separated instruction and data paged image.[3] There was no mention of the dual role of the header constant, but the high order byte of the constant was, in fact, the operation code for the PDP-11 branch instruction (octal 000407 or hex 0107). Adding seven to the program counter showed that if this constant was executed, it would branch the Unix exec() service over the executable image eight byte header and start the program.

Since the Sixth and Seventh Editions of Unix employed paging code, the dual role of the header constant was hidden. That is, the exec() service read the executable file header (meta) data into a kernel space buffer, but read the executable image into user space, thereby not using the constant's branching feature. Magic number creation was implemented in the Unix linker and loader and magic number branching was probably still used in the suite of stand-alone diagnostic programs that came with the Sixth and Seventh Editions. Thus, the header constant did provide an illusion and met the criteria for magic.

In Version Seven Unix, the header constant was not tested directly, but assigned to a variable labeled ux_mag[4] and subsequently referred to as the magic number. Probably because of its uniqueness, the term magic number came to mean executable format type, then expanded to mean file system type, and expanded again to mean any type of file.

Magic numbers in files

Magic numbers are common in programs across many operating systems. Magic numbers implement strongly typed data and are a form of in-band signaling to the controlling program that reads the data type(s) at program run-time. Many files have such constants that identify the contained data. Detecting such constants in files is a simple and effective way of distinguishing between many file formats and can yield further run-time information.

Examples
Detection

The Unix utility program file can read and interpret magic numbers from files, and the file which is used to parse the information is called magic. The Windows utility TrID has a similar purpose.

Magic numbers in protocols

Examples

Magic numbers in other uses

Examples

Unnamed numerical constants

The term magic number or magic constant also refers to the programming practice of using numbers directly in source code. This has been referred to as breaking one of the oldest rules of programming, dating back to the COBOL, FORTRAN and PL/1 manuals of the 1960s.[8] The use of unnamed magic numbers in code obscures the developers' intent in choosing that number,[9] increases opportunities for subtle errors (e.g. is every digit correct in 3.14159265358979323846 and is this equal to 3.14159?) and makes it more difficult for the program to be adapted and extended in the future.[10] Replacing all significant magic numbers with named constants makes programs easier to read, understand and maintain.[11]

Names chosen to be meaningful in the context of the program can result in code that is more easily understood by a maintainer who is not the original author. An example of a non-intuitively named constant is int EIGHT = 16, while int NUMBER_OF_BITS = 16 is more descriptive.

The problems associated with magic 'numbers' described above are not limited to numerical types and the term is also applied to other data types where declaring a named constant would be more flexible and communicative.[8] Thus, declaring const string testUserName = "John" is better than several occurrences of the 'magic number' "John" in a test suite.

For example, if it is required to randomly shuffle the values in an array representing a standard pack of playing cards, this pseudocode does the job using the Fisher-Yates shuffle algorithm:

   for i from 1 to 52
       j := i + randomInt(53 - i) - 1
       a.swapEntries(i, j)

where a is an array object, the function randomInt(x) chooses a random integer between 1 and x, inclusive, and swapEntries(i, j) swaps the ith and jth entries in the array. In the preceding example, 52 is a magic number. It is considered better programming style to write the following:

   constant int deckSize := 52
   for i from 1 to deckSize
       j := i + randomInt(deckSize + 1 - i) - 1
       a.swapEntries(i, j)

This is preferable for several reasons:

   function shuffle (int deckSize)
      for i from 1 to deckSize
          j := i + randomInt(deckSize + 1 - i) - 1
          a.swapEntries(i, j)

Disadvantages are:

Accepted limited use of magic numbers

In some contexts, the use of unnamed numerical constants is generally accepted (and arguably "not magic"). While such acceptance is subjective, and often depends on individual coding habits, the following are common examples:

The constants 1 and 0 are sometimes used to represent the boolean values True and False in programming languages without a boolean type such as older versions of C. Most modern programming languages provide a boolean or bool primitive type and so the use of 0 and 1 is ill-advised.

In C and C++, 0 is sometimes used to represent the null pointer. As with boolean values, the C standard library includes a macro definition NULL whose use is encouraged. Other languages provide a specific null or nil value and when this is the case no alternative should be used. The typed pointer constant nullptr has been introduced with C++11.

Magic GUIDs

It is possible to create or alter globally unique identifiers (GUIDs) so that they are memorable, but this is highly discouraged as it compromises their strength as near-unique identifiers.[12][13] The specifications for generating GUIDs and UUIDs are quite complex, which is what leads to them being guaranteed unique, if properly implemented. They should only be generated by a reputable software tool.

Java uses several GUIDs starting with CAFEEFAC.[14]

In the GUID Partition Table of the GPT partitioning scheme, BIOS Boot partitions use the special GUID {21686148-6449-6E6F-744E-656564454649}[15] which does not follow the GUID definition; instead, it is formed by using the ASCII codes for the string "Hah!IdontNeedEFI" in little endian order.

Magic debug values

Magic debug values are specific values written to memory during allocation or deallocation, so that it will later be possible to tell whether or not they have become corrupted, and to make it obvious when values taken from uninitialized memory are being used. Memory is usually viewed in hexadecimal, so memorable repeating or hexspeak values are common. Numerically odd values may be preferred so that processors without byte addressing will fault when attempting to use them as pointers (which must fall at even addresses). Values should be chosen that are away from likely addresses (the program code, static data, heap data, or the stack). Similarly, they may be chosen so that they are not valid codes in the instruction set for the given architecture.

Since it is very unlikely, although possible, that a 32-bit integer would take this specific value, the appearance of such a number in a debugger or memory dump most likely indicates an error such as a buffer overflow or an uninitialized variable.

Famous and common examples include:

Code Description
..FACADE "Facade", Used by a number of RTOSes
1BADB002 "1 bad boot", Multiboot header magic number[16]
8BADF00D "Ate bad food", Indicates that an Apple iOS application has been terminated because a watchdog timeout occurred.[17]
A5A5A5A5 Used in embedded development because the alternating bit pattern (1010 0101) creates an easily recognized pattern on oscilloscopes and logic analyzers.
A5 Used in FreeBSD's PHK malloc(3) for debugging when /etc/malloc.conf is symlinked to "-J" to initialize all newly allocated memory as this value is not a NULL pointer or ASCII NUL character. (It may be a play on Russian "опять", pronounced "a piat'" which is A5 read aloud, meaning "again")
ABABABAB Used by Microsoft's debug HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory.[18]
ABADBABE "A bad babe", Used by Apple as the "Boot Zero Block" magic number
ABBABABE "ABBA babe", used by Driver Parallel Lines memory heap.
ABADCAFE "A bad cafe", Used to initialize all unallocated memory (Mungwall, AmigaOS)
0DEFACED "Defaced", Required by Microsoft's Hyper-V hypervisor to be used by Linux guests as their "guest signature", after changing from original 0xB16B00B5 ("Big Boobs")
BAADF00D "Bad food", Used by Microsoft's debug HeapAlloc() to mark uninitialized allocated heap memory[18]
BAAAAAAD "Baaaaaad", Indicates that the Apple iOS log is a stackshot of the entire system, not a crash report[17]
BAD22222 "Bad too repeatedly", Indicates that an Apple iOS VoIP application has been terminated because it resumed too frequently[17]
BADBADBADBAD "Bad bad bad bad", Burroughs large systems "uninitialized" memory (48-bit words)
BADC0FFEE0DDF00D "Bad coffee odd food", Used on IBM RS/6000 64-bit systems to indicate uninitialized CPU registers
BADDCAFE "Bad cafe", On Sun Microsystems' Solaris, marks uninitialised kernel memory (KMEM_UNINITIALIZED_PATTERN)
BBADBEEF "Bad beef", Used in WebKit
BEEFCACE "Beef cake", Used by Microsoft .NET as a magic number in resource files
C00010FF "Cool off", Indicates Apple iOS app was killed by the operating system in response to a thermal event[17]
CAFEBABE "Cafe babe", Used by Java for class files
CAFED00D "Cafe dude", Used by Java for their pack200 compression
CAFEFEED "Cafe feed", Used by Sun Microsystems' Solaris debugging kernel to mark kmemfree() memory
CCCCCCCC Used by Microsoft's C++ debugging runtime library and many DOS environments to mark uninitialized stack memory. CC resembles the opcode of the INT 3 debug breakpoint interrupt on x86 processors.
CDCDCDCD Used by Microsoft's C/C++ debug malloc() function to mark uninitialized heap memory, usually returned from HeapAlloc()[18]
D15EA5E "Disease", Used as a flag to indicate regular boot on the Nintendo GameCube and Wii consoles
DDDDDDDD Used by MicroQuill's SmartHeap and Microsoft's C/C++ debug free() function to mark freed heap memory[18]
DEAD10CC "Dead lock", Indicates that an Apple iOS application has been terminated because it held on to a system resource while running in the background[17]
DEADBABE "Dead babe", Used at the start of Silicon Graphics' IRIX arena files
DEADBEEF "Dead beef", Famously used on IBM systems such as the RS/6000, also used in the classic Mac OS operating systems, OPENSTEP Enterprise, and the Commodore Amiga. On Sun Microsystems' Solaris, marks freed kernel memory (KMEM_FREE_PATTERN)
DEADCAFE "Dead cafe", Used by Microsoft .NET as an error number in DLLs
DEADC0DE "Dead code", Used as a marker in OpenWRT firmware to signify the beginning of the to-be created jffs2 file system at the end of the static firmware
DEADFA11 "Dead fail", Indicates that an Apple iOS application has been force quit by the user[17]
DEADF00D "Dead food", Used by Mungwall on the Commodore Amiga to mark allocated but uninitialized memory [19]
DEFEC8ED "Defecated", Used for OpenSolaris core dumps
EBEBEBEB From MicroQuill's SmartHeap
FADEDEAD "Fade dead", Comes at the end to identify every AppleScript script
FDFDFDFD Used by Microsoft's C/C++ debug malloc() function to mark "no man's land" guard bytes before and after allocated heap memory[18]
FEE1DEAD "Feel dead", Used by Linux reboot() syscall
FEEDFACE "Feed face", Seen in PowerPC Mach-O binaries on Apple Inc.'s macOS platform. On Sun Microsystems' Solaris, marks the red zone (KMEM_REDZONE_PATTERN)

Used by VLC player and some IP cameras in RTP/RTCP protocol, VLC player sends four bytes in the order of the endianness of the system. Some IP cameras expecting that the player sends this magic number and do not start the stream if no magic number received.

FEEEFEEE "Fee fee", Used by Microsoft's debug HeapFree() to mark freed heap memory. Some nearby internal bookkeeping values may have the high word set to FEEE as well.[18]

Note that most of these are each 32 bits long — the word size of most 32-bit architecture computers.

The prevalence of these values in Microsoft technology is no coincidence; they are discussed in detail in Steve Maguire's book Writing Solid Code from Microsoft Press. He gives a variety of criteria for these values, such as:

Since they were often used to mark areas of memory that were essentially empty, some of these terms came to be used in phrases meaning "gone, aborted, flushed from memory"; e.g. "Your program is DEADBEEF".

See also

References

  1. Odd Comments and Strange Doings in Unix
  2. Personal communication with Dennis M. Ritchie
  3. "The Unix Tree". tuhs.org.
  4. "The Unix Tree". tuhs.org.
  5. "PNG Specification: Rationale". libpng.org.
  6. "What's the difference between the COM and EXE extensions?". blogs.msdn.microsoft.com.
  7. "Does anyone know if the following configurations can be done with MCP CLI Tool? - WiLink™ WiFi + Bluetooth Forum - Wireless Connectivity - TI E2E Community". ti.com.
  8. 1 2 3 Martin, Robert C, (2009). "Chapter 17: Smells and Heuristics - G25 Replace Magic Numbers with Named Constants". Clean Code - A handbook of agile software craftsmanship. Boston: Prentice Hall. p. 300. ISBN 0-13-235088-2.
  9. Martin, Robert C, (2009). "Chapter 17: Smells and Heuristics - G16 Obscured Intent". Clean Code - A handbook of agile software craftsmanship. Boston: Prentice Hall. p. 295. ISBN 0-13-235088-2.
  10. Datamation.com, "Bjarne Stroustrup on Educating Software Developers" http://www.datamation.com/columns/article.php/3789981/Bjarne-Stroustrup-on-Educating-Software-Developers.htm
  11. IBM Developer, "Six ways to write more comprehensible code" http://www.ibm.com/developerworks/linux/library/l-clear-code/?ca=dgr-FClnxw01linuxcodetips
  12. 'flounder'. "Guaranteeing uniqueness". Message Management. Developer Fusion. Retrieved 2007-11-16.
  13. Larry Osterman (July 21, 2005). "UUIDs are only unique if you generate them...". Larry Osterman's WebLog - Confessions of an Old Fogey. MSDN. Retrieved 2007-11-16.
  14. "Java SE 6 Release Notes.". Retrieved 2010-06-18.
  15. "GNU GRUB Installation, Section 3.4: BIOS installation". gnu.org. Retrieved 2014-06-26.
  16. http://ftp.lyx.org/pub/mach/mach4/multiboot/multiboot-archive
  17. 1 2 3 4 5 6 https://developer.apple.com/library/ios/technotes/tn2151/_index.html
  18. 1 2 3 4 5 6 "Win32 Debug CRT Heap Internals". nobugs.org.
  19. http://cataclysm.cx/random/amiga/reference/AmigaMail_Vol2_guide/node0053.html
This article is issued from Wikipedia - version of the 10/26/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.