WasmObjectFile.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  1. //===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ADT/ArrayRef.h"
  9. #include "llvm/ADT/DenseSet.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallSet.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/ADT/StringSet.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/BinaryFormat/Wasm.h"
  17. #include "llvm/MC/SubtargetFeature.h"
  18. #include "llvm/Object/Binary.h"
  19. #include "llvm/Object/Error.h"
  20. #include "llvm/Object/ObjectFile.h"
  21. #include "llvm/Object/SymbolicFile.h"
  22. #include "llvm/Object/Wasm.h"
  23. #include "llvm/Support/Endian.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/LEB128.h"
  27. #include "llvm/Support/ScopedPrinter.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cstdint>
  31. #include <cstring>
  32. #include <system_error>
  33. #define DEBUG_TYPE "wasm-object"
  34. using namespace llvm;
  35. using namespace object;
  36. void WasmSymbol::print(raw_ostream &Out) const {
  37. Out << "Name=" << Info.Name
  38. << ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind))
  39. << ", Flags=" << Info.Flags;
  40. if (!isTypeData()) {
  41. Out << ", ElemIndex=" << Info.ElementIndex;
  42. } else if (isDefined()) {
  43. Out << ", Segment=" << Info.DataRef.Segment;
  44. Out << ", Offset=" << Info.DataRef.Offset;
  45. Out << ", Size=" << Info.DataRef.Size;
  46. }
  47. }
  48. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  49. LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }
  50. #endif
  51. Expected<std::unique_ptr<WasmObjectFile>>
  52. ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {
  53. Error Err = Error::success();
  54. auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err);
  55. if (Err)
  56. return std::move(Err);
  57. return std::move(ObjectFile);
  58. }
  59. #define VARINT7_MAX ((1 << 7) - 1)
  60. #define VARINT7_MIN (-(1 << 7))
  61. #define VARUINT7_MAX (1 << 7)
  62. #define VARUINT1_MAX (1)
  63. static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {
  64. if (Ctx.Ptr == Ctx.End)
  65. report_fatal_error("EOF while reading uint8");
  66. return *Ctx.Ptr++;
  67. }
  68. static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {
  69. if (Ctx.Ptr + 4 > Ctx.End)
  70. report_fatal_error("EOF while reading uint32");
  71. uint32_t Result = support::endian::read32le(Ctx.Ptr);
  72. Ctx.Ptr += 4;
  73. return Result;
  74. }
  75. static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {
  76. if (Ctx.Ptr + 4 > Ctx.End)
  77. report_fatal_error("EOF while reading float64");
  78. int32_t Result = 0;
  79. memcpy(&Result, Ctx.Ptr, sizeof(Result));
  80. Ctx.Ptr += sizeof(Result);
  81. return Result;
  82. }
  83. static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {
  84. if (Ctx.Ptr + 8 > Ctx.End)
  85. report_fatal_error("EOF while reading float64");
  86. int64_t Result = 0;
  87. memcpy(&Result, Ctx.Ptr, sizeof(Result));
  88. Ctx.Ptr += sizeof(Result);
  89. return Result;
  90. }
  91. static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {
  92. unsigned Count;
  93. const char *Error = nullptr;
  94. uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
  95. if (Error)
  96. report_fatal_error(Error);
  97. Ctx.Ptr += Count;
  98. return Result;
  99. }
  100. static StringRef readString(WasmObjectFile::ReadContext &Ctx) {
  101. uint32_t StringLen = readULEB128(Ctx);
  102. if (Ctx.Ptr + StringLen > Ctx.End)
  103. report_fatal_error("EOF while reading string");
  104. StringRef Return =
  105. StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);
  106. Ctx.Ptr += StringLen;
  107. return Return;
  108. }
  109. static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {
  110. unsigned Count;
  111. const char *Error = nullptr;
  112. uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
  113. if (Error)
  114. report_fatal_error(Error);
  115. Ctx.Ptr += Count;
  116. return Result;
  117. }
  118. static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {
  119. int64_t Result = readLEB128(Ctx);
  120. if (Result > VARUINT1_MAX || Result < 0)
  121. report_fatal_error("LEB is outside Varuint1 range");
  122. return Result;
  123. }
  124. static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {
  125. int64_t Result = readLEB128(Ctx);
  126. if (Result > INT32_MAX || Result < INT32_MIN)
  127. report_fatal_error("LEB is outside Varint32 range");
  128. return Result;
  129. }
  130. static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {
  131. uint64_t Result = readULEB128(Ctx);
  132. if (Result > UINT32_MAX)
  133. report_fatal_error("LEB is outside Varuint32 range");
  134. return Result;
  135. }
  136. static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {
  137. return readLEB128(Ctx);
  138. }
  139. static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) {
  140. return readULEB128(Ctx);
  141. }
  142. static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {
  143. return readUint8(Ctx);
  144. }
  145. static Error readInitExpr(wasm::WasmInitExpr &Expr,
  146. WasmObjectFile::ReadContext &Ctx) {
  147. Expr.Opcode = readOpcode(Ctx);
  148. switch (Expr.Opcode) {
  149. case wasm::WASM_OPCODE_I32_CONST:
  150. Expr.Value.Int32 = readVarint32(Ctx);
  151. break;
  152. case wasm::WASM_OPCODE_I64_CONST:
  153. Expr.Value.Int64 = readVarint64(Ctx);
  154. break;
  155. case wasm::WASM_OPCODE_F32_CONST:
  156. Expr.Value.Float32 = readFloat32(Ctx);
  157. break;
  158. case wasm::WASM_OPCODE_F64_CONST:
  159. Expr.Value.Float64 = readFloat64(Ctx);
  160. break;
  161. case wasm::WASM_OPCODE_GLOBAL_GET:
  162. Expr.Value.Global = readULEB128(Ctx);
  163. break;
  164. case wasm::WASM_OPCODE_REF_NULL: {
  165. wasm::ValType Ty = static_cast<wasm::ValType>(readULEB128(Ctx));
  166. if (Ty != wasm::ValType::EXTERNREF) {
  167. return make_error<GenericBinaryError>("invalid type for ref.null",
  168. object_error::parse_failed);
  169. }
  170. break;
  171. }
  172. default:
  173. return make_error<GenericBinaryError>("invalid opcode in init_expr",
  174. object_error::parse_failed);
  175. }
  176. uint8_t EndOpcode = readOpcode(Ctx);
  177. if (EndOpcode != wasm::WASM_OPCODE_END) {
  178. return make_error<GenericBinaryError>("invalid init_expr",
  179. object_error::parse_failed);
  180. }
  181. return Error::success();
  182. }
  183. static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {
  184. wasm::WasmLimits Result;
  185. Result.Flags = readVaruint32(Ctx);
  186. Result.Initial = readVaruint64(Ctx);
  187. if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
  188. Result.Maximum = readVaruint64(Ctx);
  189. return Result;
  190. }
  191. static wasm::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) {
  192. wasm::WasmTableType TableType;
  193. TableType.ElemType = readUint8(Ctx);
  194. TableType.Limits = readLimits(Ctx);
  195. return TableType;
  196. }
  197. static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx,
  198. WasmSectionOrderChecker &Checker) {
  199. Section.Offset = Ctx.Ptr - Ctx.Start;
  200. Section.Type = readUint8(Ctx);
  201. LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");
  202. uint32_t Size = readVaruint32(Ctx);
  203. if (Size == 0)
  204. return make_error<StringError>("zero length section",
  205. object_error::parse_failed);
  206. if (Ctx.Ptr + Size > Ctx.End)
  207. return make_error<StringError>("section too large",
  208. object_error::parse_failed);
  209. if (Section.Type == wasm::WASM_SEC_CUSTOM) {
  210. WasmObjectFile::ReadContext SectionCtx;
  211. SectionCtx.Start = Ctx.Ptr;
  212. SectionCtx.Ptr = Ctx.Ptr;
  213. SectionCtx.End = Ctx.Ptr + Size;
  214. Section.Name = readString(SectionCtx);
  215. uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;
  216. Ctx.Ptr += SectionNameSize;
  217. Size -= SectionNameSize;
  218. }
  219. if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) {
  220. return make_error<StringError>("out of order section type: " +
  221. llvm::to_string(Section.Type),
  222. object_error::parse_failed);
  223. }
  224. Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
  225. Ctx.Ptr += Size;
  226. return Error::success();
  227. }
  228. WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
  229. : ObjectFile(Binary::ID_Wasm, Buffer) {
  230. ErrorAsOutParameter ErrAsOutParam(&Err);
  231. Header.Magic = getData().substr(0, 4);
  232. if (Header.Magic != StringRef("\0asm", 4)) {
  233. Err = make_error<StringError>("invalid magic number",
  234. object_error::parse_failed);
  235. return;
  236. }
  237. ReadContext Ctx;
  238. Ctx.Start = getData().bytes_begin();
  239. Ctx.Ptr = Ctx.Start + 4;
  240. Ctx.End = Ctx.Start + getData().size();
  241. if (Ctx.Ptr + 4 > Ctx.End) {
  242. Err = make_error<StringError>("missing version number",
  243. object_error::parse_failed);
  244. return;
  245. }
  246. Header.Version = readUint32(Ctx);
  247. if (Header.Version != wasm::WasmVersion) {
  248. Err = make_error<StringError>("invalid version number: " +
  249. Twine(Header.Version),
  250. object_error::parse_failed);
  251. return;
  252. }
  253. WasmSection Sec;
  254. WasmSectionOrderChecker Checker;
  255. while (Ctx.Ptr < Ctx.End) {
  256. if ((Err = readSection(Sec, Ctx, Checker)))
  257. return;
  258. if ((Err = parseSection(Sec)))
  259. return;
  260. Sections.push_back(Sec);
  261. }
  262. }
  263. Error WasmObjectFile::parseSection(WasmSection &Sec) {
  264. ReadContext Ctx;
  265. Ctx.Start = Sec.Content.data();
  266. Ctx.End = Ctx.Start + Sec.Content.size();
  267. Ctx.Ptr = Ctx.Start;
  268. switch (Sec.Type) {
  269. case wasm::WASM_SEC_CUSTOM:
  270. return parseCustomSection(Sec, Ctx);
  271. case wasm::WASM_SEC_TYPE:
  272. return parseTypeSection(Ctx);
  273. case wasm::WASM_SEC_IMPORT:
  274. return parseImportSection(Ctx);
  275. case wasm::WASM_SEC_FUNCTION:
  276. return parseFunctionSection(Ctx);
  277. case wasm::WASM_SEC_TABLE:
  278. return parseTableSection(Ctx);
  279. case wasm::WASM_SEC_MEMORY:
  280. return parseMemorySection(Ctx);
  281. case wasm::WASM_SEC_EVENT:
  282. return parseEventSection(Ctx);
  283. case wasm::WASM_SEC_GLOBAL:
  284. return parseGlobalSection(Ctx);
  285. case wasm::WASM_SEC_EXPORT:
  286. return parseExportSection(Ctx);
  287. case wasm::WASM_SEC_START:
  288. return parseStartSection(Ctx);
  289. case wasm::WASM_SEC_ELEM:
  290. return parseElemSection(Ctx);
  291. case wasm::WASM_SEC_CODE:
  292. return parseCodeSection(Ctx);
  293. case wasm::WASM_SEC_DATA:
  294. return parseDataSection(Ctx);
  295. case wasm::WASM_SEC_DATACOUNT:
  296. return parseDataCountSection(Ctx);
  297. default:
  298. return make_error<GenericBinaryError>(
  299. "invalid section type: " + Twine(Sec.Type), object_error::parse_failed);
  300. }
  301. }
  302. Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) {
  303. // See https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
  304. HasDylinkSection = true;
  305. DylinkInfo.MemorySize = readVaruint32(Ctx);
  306. DylinkInfo.MemoryAlignment = readVaruint32(Ctx);
  307. DylinkInfo.TableSize = readVaruint32(Ctx);
  308. DylinkInfo.TableAlignment = readVaruint32(Ctx);
  309. uint32_t Count = readVaruint32(Ctx);
  310. while (Count--) {
  311. DylinkInfo.Needed.push_back(readString(Ctx));
  312. }
  313. if (Ctx.Ptr != Ctx.End)
  314. return make_error<GenericBinaryError>("dylink section ended prematurely",
  315. object_error::parse_failed);
  316. return Error::success();
  317. }
  318. Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {
  319. llvm::DenseSet<uint64_t> SeenFunctions;
  320. llvm::DenseSet<uint64_t> SeenGlobals;
  321. llvm::DenseSet<uint64_t> SeenSegments;
  322. if (FunctionTypes.size() && !SeenCodeSection) {
  323. return make_error<GenericBinaryError>("names must come after code section",
  324. object_error::parse_failed);
  325. }
  326. while (Ctx.Ptr < Ctx.End) {
  327. uint8_t Type = readUint8(Ctx);
  328. uint32_t Size = readVaruint32(Ctx);
  329. const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
  330. switch (Type) {
  331. case wasm::WASM_NAMES_FUNCTION:
  332. case wasm::WASM_NAMES_GLOBAL:
  333. case wasm::WASM_NAMES_DATA_SEGMENT: {
  334. uint32_t Count = readVaruint32(Ctx);
  335. while (Count--) {
  336. uint32_t Index = readVaruint32(Ctx);
  337. StringRef Name = readString(Ctx);
  338. wasm::NameType nameType = wasm::NameType::FUNCTION;
  339. if (Type == wasm::WASM_NAMES_FUNCTION) {
  340. if (!SeenFunctions.insert(Index).second)
  341. return make_error<GenericBinaryError>(
  342. "function named more than once", object_error::parse_failed);
  343. if (!isValidFunctionIndex(Index) || Name.empty())
  344. return make_error<GenericBinaryError>("invalid name entry",
  345. object_error::parse_failed);
  346. if (isDefinedFunctionIndex(Index))
  347. getDefinedFunction(Index).DebugName = Name;
  348. } else if (Type == wasm::WASM_NAMES_GLOBAL) {
  349. nameType = wasm::NameType::GLOBAL;
  350. if (!SeenGlobals.insert(Index).second)
  351. return make_error<GenericBinaryError>("global named more than once",
  352. object_error::parse_failed);
  353. if (!isValidGlobalIndex(Index) || Name.empty())
  354. return make_error<GenericBinaryError>("invalid name entry",
  355. object_error::parse_failed);
  356. } else {
  357. nameType = wasm::NameType::DATA_SEGMENT;
  358. if (!SeenSegments.insert(Index).second)
  359. return make_error<GenericBinaryError>(
  360. "segment named more than once", object_error::parse_failed);
  361. if (Index > DataSegments.size())
  362. return make_error<GenericBinaryError>("invalid named data segment",
  363. object_error::parse_failed);
  364. }
  365. DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name});
  366. }
  367. break;
  368. }
  369. // Ignore local names for now
  370. case wasm::WASM_NAMES_LOCAL:
  371. default:
  372. Ctx.Ptr += Size;
  373. break;
  374. }
  375. if (Ctx.Ptr != SubSectionEnd)
  376. return make_error<GenericBinaryError>(
  377. "name sub-section ended prematurely", object_error::parse_failed);
  378. }
  379. if (Ctx.Ptr != Ctx.End)
  380. return make_error<GenericBinaryError>("name section ended prematurely",
  381. object_error::parse_failed);
  382. return Error::success();
  383. }
  384. Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
  385. HasLinkingSection = true;
  386. if (FunctionTypes.size() && !SeenCodeSection) {
  387. return make_error<GenericBinaryError>(
  388. "linking data must come after code section",
  389. object_error::parse_failed);
  390. }
  391. LinkingData.Version = readVaruint32(Ctx);
  392. if (LinkingData.Version != wasm::WasmMetadataVersion) {
  393. return make_error<GenericBinaryError>(
  394. "unexpected metadata version: " + Twine(LinkingData.Version) +
  395. " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
  396. object_error::parse_failed);
  397. }
  398. const uint8_t *OrigEnd = Ctx.End;
  399. while (Ctx.Ptr < OrigEnd) {
  400. Ctx.End = OrigEnd;
  401. uint8_t Type = readUint8(Ctx);
  402. uint32_t Size = readVaruint32(Ctx);
  403. LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
  404. << "\n");
  405. Ctx.End = Ctx.Ptr + Size;
  406. switch (Type) {
  407. case wasm::WASM_SYMBOL_TABLE:
  408. if (Error Err = parseLinkingSectionSymtab(Ctx))
  409. return Err;
  410. break;
  411. case wasm::WASM_SEGMENT_INFO: {
  412. uint32_t Count = readVaruint32(Ctx);
  413. if (Count > DataSegments.size())
  414. return make_error<GenericBinaryError>("too many segment names",
  415. object_error::parse_failed);
  416. for (uint32_t I = 0; I < Count; I++) {
  417. DataSegments[I].Data.Name = readString(Ctx);
  418. DataSegments[I].Data.Alignment = readVaruint32(Ctx);
  419. DataSegments[I].Data.LinkerFlags = readVaruint32(Ctx);
  420. }
  421. break;
  422. }
  423. case wasm::WASM_INIT_FUNCS: {
  424. uint32_t Count = readVaruint32(Ctx);
  425. LinkingData.InitFunctions.reserve(Count);
  426. for (uint32_t I = 0; I < Count; I++) {
  427. wasm::WasmInitFunc Init;
  428. Init.Priority = readVaruint32(Ctx);
  429. Init.Symbol = readVaruint32(Ctx);
  430. if (!isValidFunctionSymbol(Init.Symbol))
  431. return make_error<GenericBinaryError>("invalid function symbol: " +
  432. Twine(Init.Symbol),
  433. object_error::parse_failed);
  434. LinkingData.InitFunctions.emplace_back(Init);
  435. }
  436. break;
  437. }
  438. case wasm::WASM_COMDAT_INFO:
  439. if (Error Err = parseLinkingSectionComdat(Ctx))
  440. return Err;
  441. break;
  442. default:
  443. Ctx.Ptr += Size;
  444. break;
  445. }
  446. if (Ctx.Ptr != Ctx.End)
  447. return make_error<GenericBinaryError>(
  448. "linking sub-section ended prematurely", object_error::parse_failed);
  449. }
  450. if (Ctx.Ptr != OrigEnd)
  451. return make_error<GenericBinaryError>("linking section ended prematurely",
  452. object_error::parse_failed);
  453. return Error::success();
  454. }
  455. Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
  456. uint32_t Count = readVaruint32(Ctx);
  457. LinkingData.SymbolTable.reserve(Count);
  458. Symbols.reserve(Count);
  459. StringSet<> SymbolNames;
  460. std::vector<wasm::WasmImport *> ImportedGlobals;
  461. std::vector<wasm::WasmImport *> ImportedFunctions;
  462. std::vector<wasm::WasmImport *> ImportedEvents;
  463. std::vector<wasm::WasmImport *> ImportedTables;
  464. ImportedGlobals.reserve(Imports.size());
  465. ImportedFunctions.reserve(Imports.size());
  466. ImportedEvents.reserve(Imports.size());
  467. ImportedTables.reserve(Imports.size());
  468. for (auto &I : Imports) {
  469. if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
  470. ImportedFunctions.emplace_back(&I);
  471. else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
  472. ImportedGlobals.emplace_back(&I);
  473. else if (I.Kind == wasm::WASM_EXTERNAL_EVENT)
  474. ImportedEvents.emplace_back(&I);
  475. else if (I.Kind == wasm::WASM_EXTERNAL_TABLE)
  476. ImportedTables.emplace_back(&I);
  477. }
  478. while (Count--) {
  479. wasm::WasmSymbolInfo Info;
  480. const wasm::WasmSignature *Signature = nullptr;
  481. const wasm::WasmGlobalType *GlobalType = nullptr;
  482. const wasm::WasmTableType *TableType = nullptr;
  483. const wasm::WasmEventType *EventType = nullptr;
  484. Info.Kind = readUint8(Ctx);
  485. Info.Flags = readVaruint32(Ctx);
  486. bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
  487. switch (Info.Kind) {
  488. case wasm::WASM_SYMBOL_TYPE_FUNCTION:
  489. Info.ElementIndex = readVaruint32(Ctx);
  490. if (!isValidFunctionIndex(Info.ElementIndex) ||
  491. IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
  492. return make_error<GenericBinaryError>("invalid function symbol index",
  493. object_error::parse_failed);
  494. if (IsDefined) {
  495. Info.Name = readString(Ctx);
  496. unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
  497. Signature = &Signatures[FunctionTypes[FuncIndex]];
  498. wasm::WasmFunction &Function = Functions[FuncIndex];
  499. if (Function.SymbolName.empty())
  500. Function.SymbolName = Info.Name;
  501. } else {
  502. wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
  503. if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
  504. Info.Name = readString(Ctx);
  505. Info.ImportName = Import.Field;
  506. } else {
  507. Info.Name = Import.Field;
  508. }
  509. Signature = &Signatures[Import.SigIndex];
  510. if (!Import.Module.empty()) {
  511. Info.ImportModule = Import.Module;
  512. }
  513. }
  514. break;
  515. case wasm::WASM_SYMBOL_TYPE_GLOBAL:
  516. Info.ElementIndex = readVaruint32(Ctx);
  517. if (!isValidGlobalIndex(Info.ElementIndex) ||
  518. IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
  519. return make_error<GenericBinaryError>("invalid global symbol index",
  520. object_error::parse_failed);
  521. if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
  522. wasm::WASM_SYMBOL_BINDING_WEAK)
  523. return make_error<GenericBinaryError>("undefined weak global symbol",
  524. object_error::parse_failed);
  525. if (IsDefined) {
  526. Info.Name = readString(Ctx);
  527. unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
  528. wasm::WasmGlobal &Global = Globals[GlobalIndex];
  529. GlobalType = &Global.Type;
  530. if (Global.SymbolName.empty())
  531. Global.SymbolName = Info.Name;
  532. } else {
  533. wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
  534. if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
  535. Info.Name = readString(Ctx);
  536. Info.ImportName = Import.Field;
  537. } else {
  538. Info.Name = Import.Field;
  539. }
  540. GlobalType = &Import.Global;
  541. if (!Import.Module.empty()) {
  542. Info.ImportModule = Import.Module;
  543. }
  544. }
  545. break;
  546. case wasm::WASM_SYMBOL_TYPE_TABLE:
  547. Info.ElementIndex = readVaruint32(Ctx);
  548. if (!isValidTableIndex(Info.ElementIndex) ||
  549. IsDefined != isDefinedTableIndex(Info.ElementIndex))
  550. return make_error<GenericBinaryError>("invalid table symbol index",
  551. object_error::parse_failed);
  552. if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
  553. wasm::WASM_SYMBOL_BINDING_WEAK)
  554. return make_error<GenericBinaryError>("undefined weak table symbol",
  555. object_error::parse_failed);
  556. if (IsDefined) {
  557. Info.Name = readString(Ctx);
  558. unsigned TableIndex = Info.ElementIndex - NumImportedTables;
  559. wasm::WasmTable &Table = Tables[TableIndex];
  560. TableType = &Table.Type;
  561. if (Table.SymbolName.empty())
  562. Table.SymbolName = Info.Name;
  563. } else {
  564. wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex];
  565. if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
  566. Info.Name = readString(Ctx);
  567. Info.ImportName = Import.Field;
  568. } else {
  569. Info.Name = Import.Field;
  570. }
  571. TableType = &Import.Table;
  572. if (!Import.Module.empty()) {
  573. Info.ImportModule = Import.Module;
  574. }
  575. }
  576. break;
  577. case wasm::WASM_SYMBOL_TYPE_DATA:
  578. Info.Name = readString(Ctx);
  579. if (IsDefined) {
  580. auto Index = readVaruint32(Ctx);
  581. if (Index >= DataSegments.size())
  582. return make_error<GenericBinaryError>("invalid data symbol index",
  583. object_error::parse_failed);
  584. auto Offset = readVaruint64(Ctx);
  585. auto Size = readVaruint64(Ctx);
  586. if (Offset + Size > DataSegments[Index].Data.Content.size())
  587. return make_error<GenericBinaryError>("invalid data symbol offset",
  588. object_error::parse_failed);
  589. Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
  590. }
  591. break;
  592. case wasm::WASM_SYMBOL_TYPE_SECTION: {
  593. if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
  594. wasm::WASM_SYMBOL_BINDING_LOCAL)
  595. return make_error<GenericBinaryError>(
  596. "section symbols must have local binding",
  597. object_error::parse_failed);
  598. Info.ElementIndex = readVaruint32(Ctx);
  599. // Use somewhat unique section name as symbol name.
  600. StringRef SectionName = Sections[Info.ElementIndex].Name;
  601. Info.Name = SectionName;
  602. break;
  603. }
  604. case wasm::WASM_SYMBOL_TYPE_EVENT: {
  605. Info.ElementIndex = readVaruint32(Ctx);
  606. if (!isValidEventIndex(Info.ElementIndex) ||
  607. IsDefined != isDefinedEventIndex(Info.ElementIndex))
  608. return make_error<GenericBinaryError>("invalid event symbol index",
  609. object_error::parse_failed);
  610. if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
  611. wasm::WASM_SYMBOL_BINDING_WEAK)
  612. return make_error<GenericBinaryError>("undefined weak global symbol",
  613. object_error::parse_failed);
  614. if (IsDefined) {
  615. Info.Name = readString(Ctx);
  616. unsigned EventIndex = Info.ElementIndex - NumImportedEvents;
  617. wasm::WasmEvent &Event = Events[EventIndex];
  618. Signature = &Signatures[Event.Type.SigIndex];
  619. EventType = &Event.Type;
  620. if (Event.SymbolName.empty())
  621. Event.SymbolName = Info.Name;
  622. } else {
  623. wasm::WasmImport &Import = *ImportedEvents[Info.ElementIndex];
  624. if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
  625. Info.Name = readString(Ctx);
  626. Info.ImportName = Import.Field;
  627. } else {
  628. Info.Name = Import.Field;
  629. }
  630. EventType = &Import.Event;
  631. Signature = &Signatures[EventType->SigIndex];
  632. if (!Import.Module.empty()) {
  633. Info.ImportModule = Import.Module;
  634. }
  635. }
  636. break;
  637. }
  638. default:
  639. return make_error<GenericBinaryError>("invalid symbol type: " +
  640. Twine(unsigned(Info.Kind)),
  641. object_error::parse_failed);
  642. }
  643. if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
  644. wasm::WASM_SYMBOL_BINDING_LOCAL &&
  645. !SymbolNames.insert(Info.Name).second)
  646. return make_error<GenericBinaryError>("duplicate symbol name " +
  647. Twine(Info.Name),
  648. object_error::parse_failed);
  649. LinkingData.SymbolTable.emplace_back(Info);
  650. Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType,
  651. EventType, Signature);
  652. LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
  653. }
  654. return Error::success();
  655. }
  656. Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
  657. uint32_t ComdatCount = readVaruint32(Ctx);
  658. StringSet<> ComdatSet;
  659. for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
  660. StringRef Name = readString(Ctx);
  661. if (Name.empty() || !ComdatSet.insert(Name).second)
  662. return make_error<GenericBinaryError>("bad/duplicate COMDAT name " +
  663. Twine(Name),
  664. object_error::parse_failed);
  665. LinkingData.Comdats.emplace_back(Name);
  666. uint32_t Flags = readVaruint32(Ctx);
  667. if (Flags != 0)
  668. return make_error<GenericBinaryError>("unsupported COMDAT flags",
  669. object_error::parse_failed);
  670. uint32_t EntryCount = readVaruint32(Ctx);
  671. while (EntryCount--) {
  672. unsigned Kind = readVaruint32(Ctx);
  673. unsigned Index = readVaruint32(Ctx);
  674. switch (Kind) {
  675. default:
  676. return make_error<GenericBinaryError>("invalid COMDAT entry type",
  677. object_error::parse_failed);
  678. case wasm::WASM_COMDAT_DATA:
  679. if (Index >= DataSegments.size())
  680. return make_error<GenericBinaryError>(
  681. "COMDAT data index out of range", object_error::parse_failed);
  682. if (DataSegments[Index].Data.Comdat != UINT32_MAX)
  683. return make_error<GenericBinaryError>("data segment in two COMDATs",
  684. object_error::parse_failed);
  685. DataSegments[Index].Data.Comdat = ComdatIndex;
  686. break;
  687. case wasm::WASM_COMDAT_FUNCTION:
  688. if (!isDefinedFunctionIndex(Index))
  689. return make_error<GenericBinaryError>(
  690. "COMDAT function index out of range", object_error::parse_failed);
  691. if (getDefinedFunction(Index).Comdat != UINT32_MAX)
  692. return make_error<GenericBinaryError>("function in two COMDATs",
  693. object_error::parse_failed);
  694. getDefinedFunction(Index).Comdat = ComdatIndex;
  695. break;
  696. case wasm::WASM_COMDAT_SECTION:
  697. if (Index >= Sections.size())
  698. return make_error<GenericBinaryError>(
  699. "COMDAT section index out of range", object_error::parse_failed);
  700. if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM)
  701. return make_error<GenericBinaryError>(
  702. "non-custom section in a COMDAT", object_error::parse_failed);
  703. Sections[Index].Comdat = ComdatIndex;
  704. break;
  705. }
  706. }
  707. }
  708. return Error::success();
  709. }
  710. Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {
  711. llvm::SmallSet<StringRef, 3> FieldsSeen;
  712. uint32_t Fields = readVaruint32(Ctx);
  713. for (size_t I = 0; I < Fields; ++I) {
  714. StringRef FieldName = readString(Ctx);
  715. if (!FieldsSeen.insert(FieldName).second)
  716. return make_error<GenericBinaryError>(
  717. "producers section does not have unique fields",
  718. object_error::parse_failed);
  719. std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;
  720. if (FieldName == "language") {
  721. ProducerVec = &ProducerInfo.Languages;
  722. } else if (FieldName == "processed-by") {
  723. ProducerVec = &ProducerInfo.Tools;
  724. } else if (FieldName == "sdk") {
  725. ProducerVec = &ProducerInfo.SDKs;
  726. } else {
  727. return make_error<GenericBinaryError>(
  728. "producers section field is not named one of language, processed-by, "
  729. "or sdk",
  730. object_error::parse_failed);
  731. }
  732. uint32_t ValueCount = readVaruint32(Ctx);
  733. llvm::SmallSet<StringRef, 8> ProducersSeen;
  734. for (size_t J = 0; J < ValueCount; ++J) {
  735. StringRef Name = readString(Ctx);
  736. StringRef Version = readString(Ctx);
  737. if (!ProducersSeen.insert(Name).second) {
  738. return make_error<GenericBinaryError>(
  739. "producers section contains repeated producer",
  740. object_error::parse_failed);
  741. }
  742. ProducerVec->emplace_back(std::string(Name), std::string(Version));
  743. }
  744. }
  745. if (Ctx.Ptr != Ctx.End)
  746. return make_error<GenericBinaryError>("producers section ended prematurely",
  747. object_error::parse_failed);
  748. return Error::success();
  749. }
  750. Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {
  751. llvm::SmallSet<std::string, 8> FeaturesSeen;
  752. uint32_t FeatureCount = readVaruint32(Ctx);
  753. for (size_t I = 0; I < FeatureCount; ++I) {
  754. wasm::WasmFeatureEntry Feature;
  755. Feature.Prefix = readUint8(Ctx);
  756. switch (Feature.Prefix) {
  757. case wasm::WASM_FEATURE_PREFIX_USED:
  758. case wasm::WASM_FEATURE_PREFIX_REQUIRED:
  759. case wasm::WASM_FEATURE_PREFIX_DISALLOWED:
  760. break;
  761. default:
  762. return make_error<GenericBinaryError>("unknown feature policy prefix",
  763. object_error::parse_failed);
  764. }
  765. Feature.Name = std::string(readString(Ctx));
  766. if (!FeaturesSeen.insert(Feature.Name).second)
  767. return make_error<GenericBinaryError>(
  768. "target features section contains repeated feature \"" +
  769. Feature.Name + "\"",
  770. object_error::parse_failed);
  771. TargetFeatures.push_back(Feature);
  772. }
  773. if (Ctx.Ptr != Ctx.End)
  774. return make_error<GenericBinaryError>(
  775. "target features section ended prematurely",
  776. object_error::parse_failed);
  777. return Error::success();
  778. }
  779. Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
  780. uint32_t SectionIndex = readVaruint32(Ctx);
  781. if (SectionIndex >= Sections.size())
  782. return make_error<GenericBinaryError>("invalid section index",
  783. object_error::parse_failed);
  784. WasmSection &Section = Sections[SectionIndex];
  785. uint32_t RelocCount = readVaruint32(Ctx);
  786. uint32_t EndOffset = Section.Content.size();
  787. uint32_t PreviousOffset = 0;
  788. while (RelocCount--) {
  789. wasm::WasmRelocation Reloc = {};
  790. uint32_t type = readVaruint32(Ctx);
  791. Reloc.Type = type;
  792. Reloc.Offset = readVaruint32(Ctx);
  793. if (Reloc.Offset < PreviousOffset)
  794. return make_error<GenericBinaryError>("relocations not in offset order",
  795. object_error::parse_failed);
  796. PreviousOffset = Reloc.Offset;
  797. Reloc.Index = readVaruint32(Ctx);
  798. switch (type) {
  799. case wasm::R_WASM_FUNCTION_INDEX_LEB:
  800. case wasm::R_WASM_TABLE_INDEX_SLEB:
  801. case wasm::R_WASM_TABLE_INDEX_SLEB64:
  802. case wasm::R_WASM_TABLE_INDEX_I32:
  803. case wasm::R_WASM_TABLE_INDEX_I64:
  804. case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
  805. if (!isValidFunctionSymbol(Reloc.Index))
  806. return make_error<GenericBinaryError>(
  807. "invalid relocation function index", object_error::parse_failed);
  808. break;
  809. case wasm::R_WASM_TABLE_NUMBER_LEB:
  810. if (!isValidTableSymbol(Reloc.Index))
  811. return make_error<GenericBinaryError>("invalid relocation table index",
  812. object_error::parse_failed);
  813. break;
  814. case wasm::R_WASM_TYPE_INDEX_LEB:
  815. if (Reloc.Index >= Signatures.size())
  816. return make_error<GenericBinaryError>("invalid relocation type index",
  817. object_error::parse_failed);
  818. break;
  819. case wasm::R_WASM_GLOBAL_INDEX_LEB:
  820. // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
  821. // symbols to refer to their GOT entries.
  822. if (!isValidGlobalSymbol(Reloc.Index) &&
  823. !isValidDataSymbol(Reloc.Index) &&
  824. !isValidFunctionSymbol(Reloc.Index))
  825. return make_error<GenericBinaryError>("invalid relocation global index",
  826. object_error::parse_failed);
  827. break;
  828. case wasm::R_WASM_GLOBAL_INDEX_I32:
  829. if (!isValidGlobalSymbol(Reloc.Index))
  830. return make_error<GenericBinaryError>("invalid relocation global index",
  831. object_error::parse_failed);
  832. break;
  833. case wasm::R_WASM_EVENT_INDEX_LEB:
  834. if (!isValidEventSymbol(Reloc.Index))
  835. return make_error<GenericBinaryError>("invalid relocation event index",
  836. object_error::parse_failed);
  837. break;
  838. case wasm::R_WASM_MEMORY_ADDR_LEB:
  839. case wasm::R_WASM_MEMORY_ADDR_SLEB:
  840. case wasm::R_WASM_MEMORY_ADDR_I32:
  841. case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
  842. case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
  843. if (!isValidDataSymbol(Reloc.Index))
  844. return make_error<GenericBinaryError>("invalid relocation data index",
  845. object_error::parse_failed);
  846. Reloc.Addend = readVarint32(Ctx);
  847. break;
  848. case wasm::R_WASM_MEMORY_ADDR_LEB64:
  849. case wasm::R_WASM_MEMORY_ADDR_SLEB64:
  850. case wasm::R_WASM_MEMORY_ADDR_I64:
  851. case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
  852. if (!isValidDataSymbol(Reloc.Index))
  853. return make_error<GenericBinaryError>("invalid relocation data index",
  854. object_error::parse_failed);
  855. Reloc.Addend = readVarint64(Ctx);
  856. break;
  857. case wasm::R_WASM_FUNCTION_OFFSET_I32:
  858. if (!isValidFunctionSymbol(Reloc.Index))
  859. return make_error<GenericBinaryError>(
  860. "invalid relocation function index", object_error::parse_failed);
  861. Reloc.Addend = readVarint32(Ctx);
  862. break;
  863. case wasm::R_WASM_FUNCTION_OFFSET_I64:
  864. if (!isValidFunctionSymbol(Reloc.Index))
  865. return make_error<GenericBinaryError>(
  866. "invalid relocation function index", object_error::parse_failed);
  867. Reloc.Addend = readVarint64(Ctx);
  868. break;
  869. case wasm::R_WASM_SECTION_OFFSET_I32:
  870. if (!isValidSectionSymbol(Reloc.Index))
  871. return make_error<GenericBinaryError>(
  872. "invalid relocation section index", object_error::parse_failed);
  873. Reloc.Addend = readVarint32(Ctx);
  874. break;
  875. default:
  876. return make_error<GenericBinaryError>("invalid relocation type: " +
  877. Twine(type),
  878. object_error::parse_failed);
  879. }
  880. // Relocations must fit inside the section, and must appear in order. They
  881. // also shouldn't overlap a function/element boundary, but we don't bother
  882. // to check that.
  883. uint64_t Size = 5;
  884. if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||
  885. Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||
  886. Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)
  887. Size = 10;
  888. if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||
  889. Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||
  890. Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||
  891. Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
  892. Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)
  893. Size = 4;
  894. if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||
  895. Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||
  896. Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)
  897. Size = 8;
  898. if (Reloc.Offset + Size > EndOffset)
  899. return make_error<GenericBinaryError>("invalid relocation offset",
  900. object_error::parse_failed);
  901. Section.Relocations.push_back(Reloc);
  902. }
  903. if (Ctx.Ptr != Ctx.End)
  904. return make_error<GenericBinaryError>("reloc section ended prematurely",
  905. object_error::parse_failed);
  906. return Error::success();
  907. }
  908. Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
  909. if (Sec.Name == "dylink") {
  910. if (Error Err = parseDylinkSection(Ctx))
  911. return Err;
  912. } else if (Sec.Name == "name") {
  913. if (Error Err = parseNameSection(Ctx))
  914. return Err;
  915. } else if (Sec.Name == "linking") {
  916. if (Error Err = parseLinkingSection(Ctx))
  917. return Err;
  918. } else if (Sec.Name == "producers") {
  919. if (Error Err = parseProducersSection(Ctx))
  920. return Err;
  921. } else if (Sec.Name == "target_features") {
  922. if (Error Err = parseTargetFeaturesSection(Ctx))
  923. return Err;
  924. } else if (Sec.Name.startswith("reloc.")) {
  925. if (Error Err = parseRelocSection(Sec.Name, Ctx))
  926. return Err;
  927. }
  928. return Error::success();
  929. }
  930. Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
  931. uint32_t Count = readVaruint32(Ctx);
  932. Signatures.reserve(Count);
  933. while (Count--) {
  934. wasm::WasmSignature Sig;
  935. uint8_t Form = readUint8(Ctx);
  936. if (Form != wasm::WASM_TYPE_FUNC) {
  937. return make_error<GenericBinaryError>("invalid signature type",
  938. object_error::parse_failed);
  939. }
  940. uint32_t ParamCount = readVaruint32(Ctx);
  941. Sig.Params.reserve(ParamCount);
  942. while (ParamCount--) {
  943. uint32_t ParamType = readUint8(Ctx);
  944. Sig.Params.push_back(wasm::ValType(ParamType));
  945. }
  946. uint32_t ReturnCount = readVaruint32(Ctx);
  947. while (ReturnCount--) {
  948. uint32_t ReturnType = readUint8(Ctx);
  949. Sig.Returns.push_back(wasm::ValType(ReturnType));
  950. }
  951. Signatures.push_back(std::move(Sig));
  952. }
  953. if (Ctx.Ptr != Ctx.End)
  954. return make_error<GenericBinaryError>("type section ended prematurely",
  955. object_error::parse_failed);
  956. return Error::success();
  957. }
  958. Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
  959. uint32_t Count = readVaruint32(Ctx);
  960. Imports.reserve(Count);
  961. for (uint32_t I = 0; I < Count; I++) {
  962. wasm::WasmImport Im;
  963. Im.Module = readString(Ctx);
  964. Im.Field = readString(Ctx);
  965. Im.Kind = readUint8(Ctx);
  966. switch (Im.Kind) {
  967. case wasm::WASM_EXTERNAL_FUNCTION:
  968. NumImportedFunctions++;
  969. Im.SigIndex = readVaruint32(Ctx);
  970. break;
  971. case wasm::WASM_EXTERNAL_GLOBAL:
  972. NumImportedGlobals++;
  973. Im.Global.Type = readUint8(Ctx);
  974. Im.Global.Mutable = readVaruint1(Ctx);
  975. break;
  976. case wasm::WASM_EXTERNAL_MEMORY:
  977. Im.Memory = readLimits(Ctx);
  978. if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
  979. HasMemory64 = true;
  980. break;
  981. case wasm::WASM_EXTERNAL_TABLE: {
  982. Im.Table = readTableType(Ctx);
  983. NumImportedTables++;
  984. auto ElemType = Im.Table.ElemType;
  985. if (ElemType != wasm::WASM_TYPE_FUNCREF &&
  986. ElemType != wasm::WASM_TYPE_EXTERNREF)
  987. return make_error<GenericBinaryError>("invalid table element type",
  988. object_error::parse_failed);
  989. break;
  990. }
  991. case wasm::WASM_EXTERNAL_EVENT:
  992. NumImportedEvents++;
  993. Im.Event.Attribute = readVarint32(Ctx);
  994. Im.Event.SigIndex = readVarint32(Ctx);
  995. break;
  996. default:
  997. return make_error<GenericBinaryError>("unexpected import kind",
  998. object_error::parse_failed);
  999. }
  1000. Imports.push_back(Im);
  1001. }
  1002. if (Ctx.Ptr != Ctx.End)
  1003. return make_error<GenericBinaryError>("import section ended prematurely",
  1004. object_error::parse_failed);
  1005. return Error::success();
  1006. }
  1007. Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
  1008. uint32_t Count = readVaruint32(Ctx);
  1009. FunctionTypes.reserve(Count);
  1010. Functions.resize(Count);
  1011. uint32_t NumTypes = Signatures.size();
  1012. while (Count--) {
  1013. uint32_t Type = readVaruint32(Ctx);
  1014. if (Type >= NumTypes)
  1015. return make_error<GenericBinaryError>("invalid function type",
  1016. object_error::parse_failed);
  1017. FunctionTypes.push_back(Type);
  1018. }
  1019. if (Ctx.Ptr != Ctx.End)
  1020. return make_error<GenericBinaryError>("function section ended prematurely",
  1021. object_error::parse_failed);
  1022. return Error::success();
  1023. }
  1024. Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
  1025. TableSection = Sections.size();
  1026. uint32_t Count = readVaruint32(Ctx);
  1027. Tables.reserve(Count);
  1028. while (Count--) {
  1029. wasm::WasmTable T;
  1030. T.Type = readTableType(Ctx);
  1031. T.Index = NumImportedTables + Tables.size();
  1032. Tables.push_back(T);
  1033. auto ElemType = Tables.back().Type.ElemType;
  1034. if (ElemType != wasm::WASM_TYPE_FUNCREF &&
  1035. ElemType != wasm::WASM_TYPE_EXTERNREF) {
  1036. return make_error<GenericBinaryError>("invalid table element type",
  1037. object_error::parse_failed);
  1038. }
  1039. }
  1040. if (Ctx.Ptr != Ctx.End)
  1041. return make_error<GenericBinaryError>("table section ended prematurely",
  1042. object_error::parse_failed);
  1043. return Error::success();
  1044. }
  1045. Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
  1046. uint32_t Count = readVaruint32(Ctx);
  1047. Memories.reserve(Count);
  1048. while (Count--) {
  1049. auto Limits = readLimits(Ctx);
  1050. if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
  1051. HasMemory64 = true;
  1052. Memories.push_back(Limits);
  1053. }
  1054. if (Ctx.Ptr != Ctx.End)
  1055. return make_error<GenericBinaryError>("memory section ended prematurely",
  1056. object_error::parse_failed);
  1057. return Error::success();
  1058. }
  1059. Error WasmObjectFile::parseEventSection(ReadContext &Ctx) {
  1060. EventSection = Sections.size();
  1061. uint32_t Count = readVarint32(Ctx);
  1062. Events.reserve(Count);
  1063. while (Count--) {
  1064. wasm::WasmEvent Event;
  1065. Event.Index = NumImportedEvents + Events.size();
  1066. Event.Type.Attribute = readVaruint32(Ctx);
  1067. Event.Type.SigIndex = readVarint32(Ctx);
  1068. Events.push_back(Event);
  1069. }
  1070. if (Ctx.Ptr != Ctx.End)
  1071. return make_error<GenericBinaryError>("event section ended prematurely",
  1072. object_error::parse_failed);
  1073. return Error::success();
  1074. }
  1075. Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
  1076. GlobalSection = Sections.size();
  1077. uint32_t Count = readVaruint32(Ctx);
  1078. Globals.reserve(Count);
  1079. while (Count--) {
  1080. wasm::WasmGlobal Global;
  1081. Global.Index = NumImportedGlobals + Globals.size();
  1082. Global.Type.Type = readUint8(Ctx);
  1083. Global.Type.Mutable = readVaruint1(Ctx);
  1084. if (Error Err = readInitExpr(Global.InitExpr, Ctx))
  1085. return Err;
  1086. Globals.push_back(Global);
  1087. }
  1088. if (Ctx.Ptr != Ctx.End)
  1089. return make_error<GenericBinaryError>("global section ended prematurely",
  1090. object_error::parse_failed);
  1091. return Error::success();
  1092. }
  1093. Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
  1094. uint32_t Count = readVaruint32(Ctx);
  1095. Exports.reserve(Count);
  1096. for (uint32_t I = 0; I < Count; I++) {
  1097. wasm::WasmExport Ex;
  1098. Ex.Name = readString(Ctx);
  1099. Ex.Kind = readUint8(Ctx);
  1100. Ex.Index = readVaruint32(Ctx);
  1101. switch (Ex.Kind) {
  1102. case wasm::WASM_EXTERNAL_FUNCTION:
  1103. if (!isDefinedFunctionIndex(Ex.Index))
  1104. return make_error<GenericBinaryError>("invalid function export",
  1105. object_error::parse_failed);
  1106. getDefinedFunction(Ex.Index).ExportName = Ex.Name;
  1107. break;
  1108. case wasm::WASM_EXTERNAL_GLOBAL:
  1109. if (!isValidGlobalIndex(Ex.Index))
  1110. return make_error<GenericBinaryError>("invalid global export",
  1111. object_error::parse_failed);
  1112. break;
  1113. case wasm::WASM_EXTERNAL_EVENT:
  1114. if (!isValidEventIndex(Ex.Index))
  1115. return make_error<GenericBinaryError>("invalid event export",
  1116. object_error::parse_failed);
  1117. break;
  1118. case wasm::WASM_EXTERNAL_MEMORY:
  1119. case wasm::WASM_EXTERNAL_TABLE:
  1120. break;
  1121. default:
  1122. return make_error<GenericBinaryError>("unexpected export kind",
  1123. object_error::parse_failed);
  1124. }
  1125. Exports.push_back(Ex);
  1126. }
  1127. if (Ctx.Ptr != Ctx.End)
  1128. return make_error<GenericBinaryError>("export section ended prematurely",
  1129. object_error::parse_failed);
  1130. return Error::success();
  1131. }
  1132. bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
  1133. return Index < NumImportedFunctions + FunctionTypes.size();
  1134. }
  1135. bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
  1136. return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
  1137. }
  1138. bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
  1139. return Index < NumImportedGlobals + Globals.size();
  1140. }
  1141. bool WasmObjectFile::isValidTableIndex(uint32_t Index) const {
  1142. return Index < NumImportedTables + Tables.size();
  1143. }
  1144. bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
  1145. return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
  1146. }
  1147. bool WasmObjectFile::isDefinedTableIndex(uint32_t Index) const {
  1148. return Index >= NumImportedTables && isValidTableIndex(Index);
  1149. }
  1150. bool WasmObjectFile::isValidEventIndex(uint32_t Index) const {
  1151. return Index < NumImportedEvents + Events.size();
  1152. }
  1153. bool WasmObjectFile::isDefinedEventIndex(uint32_t Index) const {
  1154. return Index >= NumImportedEvents && isValidEventIndex(Index);
  1155. }
  1156. bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
  1157. return Index < Symbols.size() && Symbols[Index].isTypeFunction();
  1158. }
  1159. bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {
  1160. return Index < Symbols.size() && Symbols[Index].isTypeTable();
  1161. }
  1162. bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
  1163. return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
  1164. }
  1165. bool WasmObjectFile::isValidEventSymbol(uint32_t Index) const {
  1166. return Index < Symbols.size() && Symbols[Index].isTypeEvent();
  1167. }
  1168. bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
  1169. return Index < Symbols.size() && Symbols[Index].isTypeData();
  1170. }
  1171. bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
  1172. return Index < Symbols.size() && Symbols[Index].isTypeSection();
  1173. }
  1174. wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
  1175. assert(isDefinedFunctionIndex(Index));
  1176. return Functions[Index - NumImportedFunctions];
  1177. }
  1178. const wasm::WasmFunction &
  1179. WasmObjectFile::getDefinedFunction(uint32_t Index) const {
  1180. assert(isDefinedFunctionIndex(Index));
  1181. return Functions[Index - NumImportedFunctions];
  1182. }
  1183. wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
  1184. assert(isDefinedGlobalIndex(Index));
  1185. return Globals[Index - NumImportedGlobals];
  1186. }
  1187. wasm::WasmEvent &WasmObjectFile::getDefinedEvent(uint32_t Index) {
  1188. assert(isDefinedEventIndex(Index));
  1189. return Events[Index - NumImportedEvents];
  1190. }
  1191. Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
  1192. StartFunction = readVaruint32(Ctx);
  1193. if (!isValidFunctionIndex(StartFunction))
  1194. return make_error<GenericBinaryError>("invalid start function",
  1195. object_error::parse_failed);
  1196. return Error::success();
  1197. }
  1198. Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
  1199. SeenCodeSection = true;
  1200. CodeSection = Sections.size();
  1201. uint32_t FunctionCount = readVaruint32(Ctx);
  1202. if (FunctionCount != FunctionTypes.size()) {
  1203. return make_error<GenericBinaryError>("invalid function count",
  1204. object_error::parse_failed);
  1205. }
  1206. for (uint32_t i = 0; i < FunctionCount; i++) {
  1207. wasm::WasmFunction& Function = Functions[i];
  1208. const uint8_t *FunctionStart = Ctx.Ptr;
  1209. uint32_t Size = readVaruint32(Ctx);
  1210. const uint8_t *FunctionEnd = Ctx.Ptr + Size;
  1211. Function.CodeOffset = Ctx.Ptr - FunctionStart;
  1212. Function.Index = NumImportedFunctions + i;
  1213. Function.CodeSectionOffset = FunctionStart - Ctx.Start;
  1214. Function.Size = FunctionEnd - FunctionStart;
  1215. uint32_t NumLocalDecls = readVaruint32(Ctx);
  1216. Function.Locals.reserve(NumLocalDecls);
  1217. while (NumLocalDecls--) {
  1218. wasm::WasmLocalDecl Decl;
  1219. Decl.Count = readVaruint32(Ctx);
  1220. Decl.Type = readUint8(Ctx);
  1221. Function.Locals.push_back(Decl);
  1222. }
  1223. uint32_t BodySize = FunctionEnd - Ctx.Ptr;
  1224. Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
  1225. // This will be set later when reading in the linking metadata section.
  1226. Function.Comdat = UINT32_MAX;
  1227. Ctx.Ptr += BodySize;
  1228. assert(Ctx.Ptr == FunctionEnd);
  1229. }
  1230. if (Ctx.Ptr != Ctx.End)
  1231. return make_error<GenericBinaryError>("code section ended prematurely",
  1232. object_error::parse_failed);
  1233. return Error::success();
  1234. }
  1235. Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
  1236. uint32_t Count = readVaruint32(Ctx);
  1237. ElemSegments.reserve(Count);
  1238. while (Count--) {
  1239. wasm::WasmElemSegment Segment;
  1240. Segment.TableIndex = readVaruint32(Ctx);
  1241. if (Segment.TableIndex != 0) {
  1242. return make_error<GenericBinaryError>("invalid TableIndex",
  1243. object_error::parse_failed);
  1244. }
  1245. if (Error Err = readInitExpr(Segment.Offset, Ctx))
  1246. return Err;
  1247. uint32_t NumElems = readVaruint32(Ctx);
  1248. while (NumElems--) {
  1249. Segment.Functions.push_back(readVaruint32(Ctx));
  1250. }
  1251. ElemSegments.push_back(Segment);
  1252. }
  1253. if (Ctx.Ptr != Ctx.End)
  1254. return make_error<GenericBinaryError>("elem section ended prematurely",
  1255. object_error::parse_failed);
  1256. return Error::success();
  1257. }
  1258. Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
  1259. DataSection = Sections.size();
  1260. uint32_t Count = readVaruint32(Ctx);
  1261. if (DataCount && Count != DataCount.getValue())
  1262. return make_error<GenericBinaryError>(
  1263. "number of data segments does not match DataCount section");
  1264. DataSegments.reserve(Count);
  1265. while (Count--) {
  1266. WasmSegment Segment;
  1267. Segment.Data.InitFlags = readVaruint32(Ctx);
  1268. Segment.Data.MemoryIndex =
  1269. (Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
  1270. ? readVaruint32(Ctx)
  1271. : 0;
  1272. if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
  1273. if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
  1274. return Err;
  1275. } else {
  1276. Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST;
  1277. Segment.Data.Offset.Value.Int32 = 0;
  1278. }
  1279. uint32_t Size = readVaruint32(Ctx);
  1280. if (Size > (size_t)(Ctx.End - Ctx.Ptr))
  1281. return make_error<GenericBinaryError>("invalid segment size",
  1282. object_error::parse_failed);
  1283. Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
  1284. // The rest of these Data fields are set later, when reading in the linking
  1285. // metadata section.
  1286. Segment.Data.Alignment = 0;
  1287. Segment.Data.LinkerFlags = 0;
  1288. Segment.Data.Comdat = UINT32_MAX;
  1289. Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
  1290. Ctx.Ptr += Size;
  1291. DataSegments.push_back(Segment);
  1292. }
  1293. if (Ctx.Ptr != Ctx.End)
  1294. return make_error<GenericBinaryError>("data section ended prematurely",
  1295. object_error::parse_failed);
  1296. return Error::success();
  1297. }
  1298. Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {
  1299. DataCount = readVaruint32(Ctx);
  1300. return Error::success();
  1301. }
  1302. const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
  1303. return Header;
  1304. }
  1305. void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }
  1306. Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
  1307. uint32_t Result = SymbolRef::SF_None;
  1308. const WasmSymbol &Sym = getWasmSymbol(Symb);
  1309. LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
  1310. if (Sym.isBindingWeak())
  1311. Result |= SymbolRef::SF_Weak;
  1312. if (!Sym.isBindingLocal())
  1313. Result |= SymbolRef::SF_Global;
  1314. if (Sym.isHidden())
  1315. Result |= SymbolRef::SF_Hidden;
  1316. if (!Sym.isDefined())
  1317. Result |= SymbolRef::SF_Undefined;
  1318. if (Sym.isTypeFunction())
  1319. Result |= SymbolRef::SF_Executable;
  1320. return Result;
  1321. }
  1322. basic_symbol_iterator WasmObjectFile::symbol_begin() const {
  1323. DataRefImpl Ref;
  1324. Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
  1325. Ref.d.b = 0; // Symbol index
  1326. return BasicSymbolRef(Ref, this);
  1327. }
  1328. basic_symbol_iterator WasmObjectFile::symbol_end() const {
  1329. DataRefImpl Ref;
  1330. Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
  1331. Ref.d.b = Symbols.size(); // Symbol index
  1332. return BasicSymbolRef(Ref, this);
  1333. }
  1334. const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
  1335. return Symbols[Symb.d.b];
  1336. }
  1337. const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
  1338. return getWasmSymbol(Symb.getRawDataRefImpl());
  1339. }
  1340. Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
  1341. return getWasmSymbol(Symb).Info.Name;
  1342. }
  1343. Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
  1344. auto &Sym = getWasmSymbol(Symb);
  1345. if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&
  1346. isDefinedFunctionIndex(Sym.Info.ElementIndex))
  1347. return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset;
  1348. else
  1349. return getSymbolValue(Symb);
  1350. }
  1351. uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {
  1352. switch (Sym.Info.Kind) {
  1353. case wasm::WASM_SYMBOL_TYPE_FUNCTION:
  1354. case wasm::WASM_SYMBOL_TYPE_GLOBAL:
  1355. case wasm::WASM_SYMBOL_TYPE_EVENT:
  1356. case wasm::WASM_SYMBOL_TYPE_TABLE:
  1357. return Sym.Info.ElementIndex;
  1358. case wasm::WASM_SYMBOL_TYPE_DATA: {
  1359. // The value of a data symbol is the segment offset, plus the symbol
  1360. // offset within the segment.
  1361. uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
  1362. const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
  1363. if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) {
  1364. return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
  1365. } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) {
  1366. return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset;
  1367. } else {
  1368. llvm_unreachable("unknown init expr opcode");
  1369. }
  1370. }
  1371. case wasm::WASM_SYMBOL_TYPE_SECTION:
  1372. return 0;
  1373. }
  1374. llvm_unreachable("invalid symbol type");
  1375. }
  1376. uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
  1377. return getWasmSymbolValue(getWasmSymbol(Symb));
  1378. }
  1379. uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
  1380. llvm_unreachable("not yet implemented");
  1381. return 0;
  1382. }
  1383. uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
  1384. llvm_unreachable("not yet implemented");
  1385. return 0;
  1386. }
  1387. Expected<SymbolRef::Type>
  1388. WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
  1389. const WasmSymbol &Sym = getWasmSymbol(Symb);
  1390. switch (Sym.Info.Kind) {
  1391. case wasm::WASM_SYMBOL_TYPE_FUNCTION:
  1392. return SymbolRef::ST_Function;
  1393. case wasm::WASM_SYMBOL_TYPE_GLOBAL:
  1394. return SymbolRef::ST_Other;
  1395. case wasm::WASM_SYMBOL_TYPE_DATA:
  1396. return SymbolRef::ST_Data;
  1397. case wasm::WASM_SYMBOL_TYPE_SECTION:
  1398. return SymbolRef::ST_Debug;
  1399. case wasm::WASM_SYMBOL_TYPE_EVENT:
  1400. return SymbolRef::ST_Other;
  1401. case wasm::WASM_SYMBOL_TYPE_TABLE:
  1402. return SymbolRef::ST_Other;
  1403. }
  1404. llvm_unreachable("unknown WasmSymbol::SymbolType");
  1405. return SymbolRef::ST_Other;
  1406. }
  1407. Expected<section_iterator>
  1408. WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
  1409. const WasmSymbol &Sym = getWasmSymbol(Symb);
  1410. if (Sym.isUndefined())
  1411. return section_end();
  1412. DataRefImpl Ref;
  1413. Ref.d.a = getSymbolSectionIdImpl(Sym);
  1414. return section_iterator(SectionRef(Ref, this));
  1415. }
  1416. uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {
  1417. const WasmSymbol &Sym = getWasmSymbol(Symb);
  1418. return getSymbolSectionIdImpl(Sym);
  1419. }
  1420. uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {
  1421. switch (Sym.Info.Kind) {
  1422. case wasm::WASM_SYMBOL_TYPE_FUNCTION:
  1423. return CodeSection;
  1424. case wasm::WASM_SYMBOL_TYPE_GLOBAL:
  1425. return GlobalSection;
  1426. case wasm::WASM_SYMBOL_TYPE_DATA:
  1427. return DataSection;
  1428. case wasm::WASM_SYMBOL_TYPE_SECTION:
  1429. return Sym.Info.ElementIndex;
  1430. case wasm::WASM_SYMBOL_TYPE_EVENT:
  1431. return EventSection;
  1432. case wasm::WASM_SYMBOL_TYPE_TABLE:
  1433. return TableSection;
  1434. default:
  1435. llvm_unreachable("unknown WasmSymbol::SymbolType");
  1436. }
  1437. }
  1438. void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
  1439. Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {
  1440. const WasmSection &S = Sections[Sec.d.a];
  1441. #define ECase(X) \
  1442. case wasm::WASM_SEC_##X: \
  1443. return #X;
  1444. switch (S.Type) {
  1445. ECase(TYPE);
  1446. ECase(IMPORT);
  1447. ECase(FUNCTION);
  1448. ECase(TABLE);
  1449. ECase(MEMORY);
  1450. ECase(GLOBAL);
  1451. ECase(EVENT);
  1452. ECase(EXPORT);
  1453. ECase(START);
  1454. ECase(ELEM);
  1455. ECase(CODE);
  1456. ECase(DATA);
  1457. ECase(DATACOUNT);
  1458. case wasm::WASM_SEC_CUSTOM:
  1459. return S.Name;
  1460. default:
  1461. return createStringError(object_error::invalid_section_index, "");
  1462. }
  1463. #undef ECase
  1464. }
  1465. uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
  1466. uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
  1467. return Sec.d.a;
  1468. }
  1469. uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
  1470. const WasmSection &S = Sections[Sec.d.a];
  1471. return S.Content.size();
  1472. }
  1473. Expected<ArrayRef<uint8_t>>
  1474. WasmObjectFile::getSectionContents(DataRefImpl Sec) const {
  1475. const WasmSection &S = Sections[Sec.d.a];
  1476. // This will never fail since wasm sections can never be empty (user-sections
  1477. // must have a name and non-user sections each have a defined structure).
  1478. return S.Content;
  1479. }
  1480. uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
  1481. return 1;
  1482. }
  1483. bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  1484. return false;
  1485. }
  1486. bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
  1487. return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
  1488. }
  1489. bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
  1490. return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
  1491. }
  1492. bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
  1493. bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
  1494. relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
  1495. DataRefImpl RelocRef;
  1496. RelocRef.d.a = Ref.d.a;
  1497. RelocRef.d.b = 0;
  1498. return relocation_iterator(RelocationRef(RelocRef, this));
  1499. }
  1500. relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
  1501. const WasmSection &Sec = getWasmSection(Ref);
  1502. DataRefImpl RelocRef;
  1503. RelocRef.d.a = Ref.d.a;
  1504. RelocRef.d.b = Sec.Relocations.size();
  1505. return relocation_iterator(RelocationRef(RelocRef, this));
  1506. }
  1507. void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }
  1508. uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
  1509. const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
  1510. return Rel.Offset;
  1511. }
  1512. symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
  1513. const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
  1514. if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)
  1515. return symbol_end();
  1516. DataRefImpl Sym;
  1517. Sym.d.a = 1;
  1518. Sym.d.b = Rel.Index;
  1519. return symbol_iterator(SymbolRef(Sym, this));
  1520. }
  1521. uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
  1522. const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
  1523. return Rel.Type;
  1524. }
  1525. void WasmObjectFile::getRelocationTypeName(
  1526. DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
  1527. const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
  1528. StringRef Res = "Unknown";
  1529. #define WASM_RELOC(name, value) \
  1530. case wasm::name: \
  1531. Res = #name; \
  1532. break;
  1533. switch (Rel.Type) {
  1534. #include "llvm/BinaryFormat/WasmRelocs.def"
  1535. }
  1536. #undef WASM_RELOC
  1537. Result.append(Res.begin(), Res.end());
  1538. }
  1539. section_iterator WasmObjectFile::section_begin() const {
  1540. DataRefImpl Ref;
  1541. Ref.d.a = 0;
  1542. return section_iterator(SectionRef(Ref, this));
  1543. }
  1544. section_iterator WasmObjectFile::section_end() const {
  1545. DataRefImpl Ref;
  1546. Ref.d.a = Sections.size();
  1547. return section_iterator(SectionRef(Ref, this));
  1548. }
  1549. uint8_t WasmObjectFile::getBytesInAddress() const {
  1550. return HasMemory64 ? 8 : 4;
  1551. }
  1552. StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
  1553. Triple::ArchType WasmObjectFile::getArch() const {
  1554. return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
  1555. }
  1556. SubtargetFeatures WasmObjectFile::getFeatures() const {
  1557. return SubtargetFeatures();
  1558. }
  1559. bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }
  1560. bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }
  1561. const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
  1562. assert(Ref.d.a < Sections.size());
  1563. return Sections[Ref.d.a];
  1564. }
  1565. const WasmSection &
  1566. WasmObjectFile::getWasmSection(const SectionRef &Section) const {
  1567. return getWasmSection(Section.getRawDataRefImpl());
  1568. }
  1569. const wasm::WasmRelocation &
  1570. WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
  1571. return getWasmRelocation(Ref.getRawDataRefImpl());
  1572. }
  1573. const wasm::WasmRelocation &
  1574. WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
  1575. assert(Ref.d.a < Sections.size());
  1576. const WasmSection &Sec = Sections[Ref.d.a];
  1577. assert(Ref.d.b < Sec.Relocations.size());
  1578. return Sec.Relocations[Ref.d.b];
  1579. }
  1580. int WasmSectionOrderChecker::getSectionOrder(unsigned ID,
  1581. StringRef CustomSectionName) {
  1582. switch (ID) {
  1583. case wasm::WASM_SEC_CUSTOM:
  1584. return StringSwitch<unsigned>(CustomSectionName)
  1585. .Case("dylink", WASM_SEC_ORDER_DYLINK)
  1586. .Case("linking", WASM_SEC_ORDER_LINKING)
  1587. .StartsWith("reloc.", WASM_SEC_ORDER_RELOC)
  1588. .Case("name", WASM_SEC_ORDER_NAME)
  1589. .Case("producers", WASM_SEC_ORDER_PRODUCERS)
  1590. .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)
  1591. .Default(WASM_SEC_ORDER_NONE);
  1592. case wasm::WASM_SEC_TYPE:
  1593. return WASM_SEC_ORDER_TYPE;
  1594. case wasm::WASM_SEC_IMPORT:
  1595. return WASM_SEC_ORDER_IMPORT;
  1596. case wasm::WASM_SEC_FUNCTION:
  1597. return WASM_SEC_ORDER_FUNCTION;
  1598. case wasm::WASM_SEC_TABLE:
  1599. return WASM_SEC_ORDER_TABLE;
  1600. case wasm::WASM_SEC_MEMORY:
  1601. return WASM_SEC_ORDER_MEMORY;
  1602. case wasm::WASM_SEC_GLOBAL:
  1603. return WASM_SEC_ORDER_GLOBAL;
  1604. case wasm::WASM_SEC_EXPORT:
  1605. return WASM_SEC_ORDER_EXPORT;
  1606. case wasm::WASM_SEC_START:
  1607. return WASM_SEC_ORDER_START;
  1608. case wasm::WASM_SEC_ELEM:
  1609. return WASM_SEC_ORDER_ELEM;
  1610. case wasm::WASM_SEC_CODE:
  1611. return WASM_SEC_ORDER_CODE;
  1612. case wasm::WASM_SEC_DATA:
  1613. return WASM_SEC_ORDER_DATA;
  1614. case wasm::WASM_SEC_DATACOUNT:
  1615. return WASM_SEC_ORDER_DATACOUNT;
  1616. case wasm::WASM_SEC_EVENT:
  1617. return WASM_SEC_ORDER_EVENT;
  1618. default:
  1619. return WASM_SEC_ORDER_NONE;
  1620. }
  1621. }
  1622. // Represents the edges in a directed graph where any node B reachable from node
  1623. // A is not allowed to appear before A in the section ordering, but may appear
  1624. // afterward.
  1625. int WasmSectionOrderChecker::DisallowedPredecessors
  1626. [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {
  1627. // WASM_SEC_ORDER_NONE
  1628. {},
  1629. // WASM_SEC_ORDER_TYPE
  1630. {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},
  1631. // WASM_SEC_ORDER_IMPORT
  1632. {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},
  1633. // WASM_SEC_ORDER_FUNCTION
  1634. {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},
  1635. // WASM_SEC_ORDER_TABLE
  1636. {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},
  1637. // WASM_SEC_ORDER_MEMORY
  1638. {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_EVENT},
  1639. // WASM_SEC_ORDER_EVENT
  1640. {WASM_SEC_ORDER_EVENT, WASM_SEC_ORDER_GLOBAL},
  1641. // WASM_SEC_ORDER_GLOBAL
  1642. {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},
  1643. // WASM_SEC_ORDER_EXPORT
  1644. {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},
  1645. // WASM_SEC_ORDER_START
  1646. {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},
  1647. // WASM_SEC_ORDER_ELEM
  1648. {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},
  1649. // WASM_SEC_ORDER_DATACOUNT
  1650. {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},
  1651. // WASM_SEC_ORDER_CODE
  1652. {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},
  1653. // WASM_SEC_ORDER_DATA
  1654. {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},
  1655. // Custom Sections
  1656. // WASM_SEC_ORDER_DYLINK
  1657. {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},
  1658. // WASM_SEC_ORDER_LINKING
  1659. {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},
  1660. // WASM_SEC_ORDER_RELOC (can be repeated)
  1661. {},
  1662. // WASM_SEC_ORDER_NAME
  1663. {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},
  1664. // WASM_SEC_ORDER_PRODUCERS
  1665. {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},
  1666. // WASM_SEC_ORDER_TARGET_FEATURES
  1667. {WASM_SEC_ORDER_TARGET_FEATURES}};
  1668. bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,
  1669. StringRef CustomSectionName) {
  1670. int Order = getSectionOrder(ID, CustomSectionName);
  1671. if (Order == WASM_SEC_ORDER_NONE)
  1672. return true;
  1673. // Disallowed predecessors we need to check for
  1674. SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;
  1675. // Keep track of completed checks to avoid repeating work
  1676. bool Checked[WASM_NUM_SEC_ORDERS] = {};
  1677. int Curr = Order;
  1678. while (true) {
  1679. // Add new disallowed predecessors to work list
  1680. for (size_t I = 0;; ++I) {
  1681. int Next = DisallowedPredecessors[Curr][I];
  1682. if (Next == WASM_SEC_ORDER_NONE)
  1683. break;
  1684. if (Checked[Next])
  1685. continue;
  1686. WorkList.push_back(Next);
  1687. Checked[Next] = true;
  1688. }
  1689. if (WorkList.empty())
  1690. break;
  1691. // Consider next disallowed predecessor
  1692. Curr = WorkList.pop_back_val();
  1693. if (Seen[Curr])
  1694. return false;
  1695. }
  1696. // Have not seen any disallowed predecessors
  1697. Seen[Order] = true;
  1698. return true;
  1699. }