# 魔法数字（编程）

**魔法数字**在编程中有两个截然不同的含义：一是嵌入源代码中、未经解释的字面常量，若无额外上下文则其用途不明；二是位于文件开头或附近的字节序列，也称为文件签名，用于标识文件的格式<sup>[1](https://linfo.org/magic_number.html)</sup>。两种含义同根同源：之所以称其为“魔法”，是因为没有外部知识就无法看出其意义<sup>[1](https://linfo.org/magic_number.html)</sup>。

| 关键事实 | 详情 |
|---|---|
| 两种含义 | 代码中无法解释的常量，以及文件开头或附近的文件格式签名<sup>[1](https://linfo.org/magic_number.html)</sup> |
| 代码中的普遍程度 | 在七个被研究的系统中，近50%的方法（其中一个系统高达73%）至少包含一个字面量；80%的测试方法包含字面量<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup> |
| 真正“魔法”的比例 | 被发现的字面量中近75%被判定为“可接受”而非“魔法”，因此只有约四分之一值得用命名常量替换<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup> |
| 检查工具默认值 | clang-tidy的readability-magic-numbers仅对整数0、1和-1不发出警告，可通过IgnoredIntegerValues配置<sup>[3](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)</sup> |
| 签名长度 | 大多数魔法签名很短，通常为2到15字节，逐字节匹配<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup> |
| 检测逻辑 | 魔法数字检测可以确定地否定一个识别结果，但无法肯定地确认它<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup> |
| ELF签名 | ELF文件的第一个字节必须是0x7f，后跟字符'E'、'L'、'F'<sup>[6](https://www.man7.org/linux/man-pages/man5/elf.5.html)</sup> |

## 定义与两种含义

这两种含义描述的是不同的产物，但具有相同的认知属性。在源代码中，魔法数字是为特定目的使用的常量，若无额外信息则其存在或取值无法解释<sup>[1](https://linfo.org/magic_number.html)</sup>。在文件中，魔法数字是嵌入文件开头或附近、指示其格式的值<sup>[1](https://linfo.org/magic_number.html)</sup>。

代码层面的含义被一些作者拓宽了。2022年一项实证研究引用了罗伯特·马丁的观点，他认为“‘魔法数字’一词并非只适用于数字。它适用于任何取值不能自描述的标记”，因此未加说明的字符串、字符和布尔值也可以是魔法；该研究相应地使用*魔法字面量*一词<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup>。传统用法仍然较窄，clang-tidy检查工具专门检查数字字面量<sup>[3](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)</sup>。两种含义在实践中也有联系：像0xCAFEBABE这样裸露的字面量，正是代码异味文献所针对的那种复杂、未经解释的值<sup>[7](https://refactoring.guru/replace-magic-number-with-symbolic-constant)</sup>。

## 作为代码异味的魔法数字

魔法字面量是使用时不加明确解释其含义的常量值。它的存在损害源代码可读性，降低模块化程度，并助长代码重复<sup>[8](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Delp19b-IWST-MagicLiterals.pdf)</sup>。散布在程序各处的相同值在含义变化时必须全部找到并修改，而读者无法判断两个相同的字面量是用途相同还是偶然巧合。

标准的补救方法是替换为命名常量。马丁·福勒的重构目录列出了**替换魔法字面量**，别名“用符号常量替换魔法数字”，示例是在势能函数中将字面量9.81替换为名为STANDARD_GRAVITY的常量<sup>[9](https://martinfowler.com/refactoring/catalog/replaceMagicNumberWithSymbolicConstant.html)</sup>。具体操作是声明一个常量，找到所有出现位置，并验证每一处确实符合该常量的用途；符号常量还起到活文档的作用，当值复杂且较长时（如3.14159或0xCAFEBABE）这一点尤为重要<sup>[7](https://refactoring.guru/replace-magic-number-with-symbolic-constant)</sup>。

从绝对数量看，这种异味很常见。一项研究挖掘了1988个C#仓库（代码超过4900万行）中的19种设计异味和11种实现异味，发现未利用抽象和魔法数字是C#代码中最常出现的异味<sup>[10](https://dl.acm.org/doi/10.1109/ESEM.2017.57)</sup>。

## 风格指南、检查规则与例外

许多编码指南建议用符号常量替换魔法值以提高可读性，clang-tidy通过readability-magic-numbers检查来执行这一建议<sup>[3](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)</sup>。对于整数字面量，默认只有0和1（以及-1）不会发出警告；例外列表可通过IgnoredIntegerValues选项覆盖<sup>[3](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)</sup>。

并非每个字面量都值得替换。2022年的研究将最好用命名常量替换的**魔法**字面量与可以保持原样的**可接受**字面量进行对比，并将其形式化为五个加一个假设，在真实案例上进行了检验<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup>。被发现的字面量中近75%被认为是可接受的；`circumference := radius * pi * 2`中的值2不言自明，不是魔法<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup>。

## 文件格式签名

操作系统通过将内容与已知字节模式进行比对来识别文件类型。OpenBSD上的file(1)命令在诸多测试中使用“魔法模式”检查来识别文件类型，/etc/magic文件规定了要测试哪些魔法数字<sup>[11](https://man.openbsd.org/man5/magic.5)</sup>。在Linux上，这些模式存放在编译后的数据库magic.mgc中，该数据库规定了要测试哪些模式以及匹配时打印什么消息或MIME类型<sup>[12](https://man7.org/linux/man-pages/man4/magic.4.html)</sup>；上游file项目的文档补充说，该数据库还规定了要从文件中提取的附加信息<sup>[13](https://github.com/file/file/blob/master/doc/magic.man)</sup>。一个庞大而复杂的此类魔法模式数据库经过数十年有机演化而成<sup>[14](https://link.springer.com/chapter/10.1007/978-981-95-0433-6_37)</sup>。

其历史可追溯至早期Unix。魔法数字最初是放在可执行文件开头的PDP-11分支指令，用于跳过头部数据；八进制值0407意为“相对分支16字节”。后来许多其他类型的文件也获得了魔法数字，其中一些是字符串<sup>[15](http://www.catb.org/jargon/html/M/magic-number.html)</sup>。Unix将可执行文件与已知魔法数字进行比对，在某些版本上，格式不正确的可执行文件的错误消息是“魔法数字错误”<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup>。在Linux中，文件系统超级块也带有魔法值：第一个扩展文件系统（ext）在1992年7月的0.96c版本中使用0x137d作为其EXT_SUPER_MAGIC值<sup>[16](https://lwn.net/Articles/915163/)</sup>。

## 著名示例

Linux使用的ELF可执行格式在e_ident字段中定义其魔法：EI_MAG0必须为0x7f，EI_MAG1至EI_MAG3必须为字符'E'、'L'、'F'<sup>[6](https://www.man7.org/linux/man-pages/man5/elf.5.html)</sup>。Microsoft [Windows PE](https://www.edgepedia.org/zh/windows-pe)二进制文件必须以字符串MZ开头，即字节0x4D 0x5A<sup>[17](https://arxiv.org/html/2409.13768)</sup>。

有文档记载的签名偏移包括PDF（偏移0处的25 50 44 46 2D）、PNG（偏移0处的89 50 4E 47 0D 0A 1A 0A）、ZIP（偏移0处的50 4B 03 04）、MP4（偏移4处的66 74 79 70）和DICOM（偏移128处的44 49 43 4D）<sup>[18](https://filesignature.org/guides/magic-bytes-vs-mime-type-vs-extension)</sup>。

内核代码在数据结构内部防御性地使用魔法数字。Linux内核维护一份使用中魔法数字的官方注册文件，开发者向结构体添加魔法数字时被要求将其加入注册表，以使各结构体使用的数字保持唯一<sup>[19](https://docs.kernel.org/5.17/process/magic-number.html)</sup>。目的是运行时检查：魔法数字让内核能够验证结构体是否被破坏，或者是否将错误的结构体传给了某个例程——tty代码在通过void指针传递驱动特定结构体时就使用了这一技术<sup>[19](https://docs.kernel.org/5.17/process/magic-number.html)</sup>。

## 与文件扩展名和MIME类型的比较

文件类型在三个信任程度不同的地方被声明：文件名扩展名，由用户控制；上传时的HTTP Content-Type头，由客户端设置；文件内签名，由生成文件的应用程序写入，在文件被重命名后仍保留为文件字节的一部分<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup>。

关于魔法数字注意事项的IETF草案精确地陈述了逻辑极限：魔法数字有两个用途——猜测未知文件的格式和检查通过其他方式指定的格式——但严格来说，魔法数字不能确证文件的格式；匹配成功提高置信度，但不能证明格式<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup>。

容器格式进一步模糊了信号。DOCX、XLSX、PPTX、APK、JAR、EPUB以及许多其他格式都使用ZIP容器，因此ZIP魔法字节标识的是容器而非确切格式，共享容器需要更深入地检查内部结构<sup>[18](https://filesignature.org/guides/magic-bytes-vs-mime-type-vs-extension)</sup>。

## 安全：欺骗与多格式文件

重命名攻击利用名称与内容之间的差距。将malware.exe重命名为photo.png不会改变内容的任何字节，因此4D 5A（MZ）头仍然存在；双扩展名伎俩依赖用户阅读名称而非字节<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup>。更微妙的是，攻击者构造同时满足两种格式的多格式文件，例如有效的GIF或PNG头后跟完整的ZIP归档或脚本<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup>。IETF草案指出了底层可能性：单个文件可以匹配多种文件格式的魔法数字要求，而协作的格式可以通过使各自的魔法数字要求互不兼容来避免歧义<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup>。

一项对现实世界中多格式文件滥用的调查发现了30个多格式文件样本和15条利用多格式文件的攻击链；多格式文件是在两种或多种格式下均有效的文件，此类文件对依赖格式识别的文件上传和生成式AI网页界面构成问题。现有检测工具无法可靠地检测它们，而ImSan内容净化工具成功净化了100%的受测基于图像的多格式文件——这是最常见的类型<sup>[20](https://www.osti.gov/biblio/2573646)</sup>。2024年的一项研究报告其PolyConv检测工具的精确率-召回率AUC达到0.999，多格式文件检测F1分数为99.20%，文件格式识别F1分数为99.47%，优于所有其他受测工具<sup>[21](https://arxiv.org/pdf/2407.01529v1.pdf)</sup>。

魔法数字还有密码学层面的影响。在加密数据中，出现一段取值恒定的字节——尤其是在数据流开头附近——可能给攻击者提供发动已知明文攻击的机会，而专为抵御此类攻击设计的密码可降低这一危险；出现在明文中的魔法数字同样可能给窃听者提供线索或可供搜索的模式。<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup>

## 用数据说话

代码层面的实证图景比民间传说所暗示的更为宽容。在七个被研究的系统中，字面量出现在近50%的方法中，其中一个系统高达73%，80%的测试方法中也有出现<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup>。然而这些字面量中近75%被判定为可接受，只有约四分之一最好变成命名常量<sup>[2](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)</sup>。

在文件层面，大多数签名很短，通常为2到15字节<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup>，检测工具以精确率和召回率衡量：PolyConv报告的多格式文件检测F1分数99.20%和格式识别F1分数99.47%优于研究中测试的其他工具<sup>[21](https://arxiv.org/pdf/2407.01529v1.pdf)</sup>。

## 近期发展

签名匹配本身正在被重新思考。Google 2024年的Magika论文以字节序列规则的脆弱性为动机提出AI驱动的内容类型检测：扩展名、MIME类型、魔法字节和元数据在文件内容被复制或传输时可能被省略，或被伪造以规避安全系统，而单个空白字符的改动或其他细微的字节修改就可能导致file/libmagic等基于签名的工具检测不准确<sup>[17](https://arxiv.org/html/2409.13768)</sup>。同一篇论文将file命令的历史追溯到五十多年前（约1973年）的贝尔实验室UNIX<sup>[17](https://arxiv.org/html/2409.13768)</sup>。

libmagic数据库持续增加规则；其JavaScript规则包括V8字节码的签名——这是NodeJS v5.7引入的格式——规则强度被调至低于HTML、高于C++，因为[JavaScript](https://www.edgepedia.org/zh/javascript)通常嵌入在HTML文件中<sup>[22](https://github.com/file/file/blob/master/magic/Magdir/javascript)</sup>。在检查工具方面，Extra Clang Tools 21.1.0文档将0、1和-1列为readability-magic-numbers的整数默认值<sup>[3](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)</sup>。

## 最佳实践与正当用途

魔法数字有时是正当的。内核的结构体魔法注册表展示了受认可的模式：中央注册表保持数字唯一，每个数字支持一次运行时完整性检查<sup>[19](https://docs.kernel.org/5.17/process/magic-number.html)</sup>。协议标签和格式签名是类似情况，常量的值本身就是契约；重构指南认为，魔法数字用作类型代码时有时是正当的<sup>[7](https://refactoring.guru/replace-magic-number-with-symbolic-constant)</sup>。

对于上传验证，推荐的防御顺序是先按签名验证，仅将扩展名和MIME类型用作命名或路由的提示<sup>[4](https://filesignature.org/guides/validate-file-type-magic-bytes)</sup>。由于签名匹配成功不能确认格式<sup>[5](https://datatracker.ietf.org/doc/html/draft-main-magic-00)</sup>，且基于ZIP的容器将真实格式隐藏在共享签名之后<sup>[18](https://filesignature.org/guides/magic-bytes-vs-mime-type-vs-extension)</sup>，三个信号之间的不一致应被视为警告或拒绝，并在格式允许时检查容器内部结构<sup>[18](https://filesignature.org/guides/magic-bytes-vs-mime-type-vs-extension)</sup>。

## References

1. [Magic number definition, The Linux Information Project (LINFO)](https://linfo.org/magic_number.html)
2. [What do developers consider magic literals? (Information and Software Technology, 2022)](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Anqu22a-infsof106942-MagicLiterals-Official.pdf)
3. [clang-tidy readability-magic-numbers, Extra Clang Tools 21.1.0 documentation](https://releases.llvm.org/21.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/readability/magic-numbers.html)
4. [Validate File Types by Magic Bytes, filesignature.org](https://filesignature.org/guides/validate-file-type-magic-bytes)
5. [Care and Feeding of Magic Numbers (IETF Internet-Draft, October 2001)](https://datatracker.ietf.org/doc/html/draft-main-magic-00)
6. [elf(5), Linux manual page](https://www.man7.org/linux/man-pages/man5/elf.5.html)
7. [Replace Magic Number with Symbolic Constant, Refactoring.Guru](https://refactoring.guru/replace-magic-number-with-symbolic-constant)
8. [Magic Literals in Pharo (IWST 2019)](https://rmod-files.lille.inria.fr/Team/Texts/Papers/Delp19b-IWST-MagicLiterals.pdf)
9. [Replace Magic Literal, Refactoring catalog, Martin Fowler](https://martinfowler.com/refactoring/catalog/replaceMagicNumberWithSymbolicConstant.html)
10. [House of cards: design and implementation smells in 1988 C# repositories (ESEM 2017)](https://dl.acm.org/doi/10.1109/ESEM.2017.57)
11. [magic(5), OpenBSD manual pages](https://man.openbsd.org/man5/magic.5)
12. [magic(4), Linux manual page](https://man7.org/linux/man-pages/man4/magic.4.html)
13. [doc/magic.man, file project source](https://github.com/file/file/blob/master/doc/magic.man)
14. [Analysis of a File Magic Pattern Language (Springer)](https://link.springer.com/chapter/10.1007/978-981-95-0433-6_37)
15. [magic number, The Jargon File](http://www.catb.org/jargon/html/M/magic-number.html)
16. [Losing the magic, LWN.net](https://lwn.net/Articles/915163/)
17. [Magika: AI-Powered Content-Type Detection (2024)](https://arxiv.org/html/2409.13768)
18. [Magic Bytes vs MIME Type vs File Extension, filesignature.org](https://filesignature.org/guides/magic-bytes-vs-mime-type-vs-extension)
19. [Linux magic numbers, The Linux Kernel documentation](https://docs.kernel.org/5.17/process/magic-number.html)
20. [On the Abuse and Detection of Polyglot Files, OSTI.GOV](https://www.osti.gov/biblio/2573646)
21. [Where the Polyglots Are: How Polyglot Files Enable Cyber Attack Chains and Methods for Detection & Disarmament (2024)](https://arxiv.org/pdf/2407.01529v1.pdf)
22. [file/file magic/Magdir/javascript](https://github.com/file/file/blob/master/magic/Magdir/javascript)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 19, 2026; Sep 30, 2026; Oct 15, 2026 · Edited: Sep 19, 2026; Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/magic-number-programming

English original: https://www.edgepedia.org/magic-number-programming
