//===- WasmAsmParser.cpp - Wasm Assembly Parser -----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // -- // // Note, this is for wasm, the binary format (analogous to ELF), not wasm, // the instruction set (analogous to x86), for which parsing code lives in // WebAssemblyAsmParser. // // This file contains processing for generic directives implemented using // MCTargetStreamer, the ones that depend on WebAssemblyTargetStreamer are in // WebAssemblyAsmParser. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringExtras.h" #include "llvm/BinaryFormat/Wasm.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/AsmLexer.h" #include "llvm/MC/MCParser/MCAsmParser.h" #include "llvm/MC/MCParser/MCAsmParserExtension.h" #include "llvm/MC/MCSectionWasm.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCSymbolWasm.h" #include using namespace llvm; namespace { class WasmAsmParser : public MCAsmParserExtension { MCAsmParser *Parser = nullptr; AsmLexer *Lexer = nullptr; template void addDirectiveHandler(StringRef Directive) { MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair( this, HandleDirective); getParser().addDirectiveHandler(Directive, Handler); } public: WasmAsmParser() { BracketExpressionsSupported = true; } void Initialize(MCAsmParser &P) override { Parser = &P; Lexer = &Parser->getLexer(); // Call the base implementation. this->MCAsmParserExtension::Initialize(*Parser); addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveText>(".text"); addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveData>(".data"); addDirectiveHandler<&WasmAsmParser::parseSectionDirective>(".section"); addDirectiveHandler<&WasmAsmParser::parseDirectivePrevious>(".previous"); addDirectiveHandler<&WasmAsmParser::parseDirectiveSize>(".size"); addDirectiveHandler<&WasmAsmParser::parseDirectiveType>(".type"); addDirectiveHandler<&WasmAsmParser::ParseDirectiveIdent>(".ident"); addDirectiveHandler< &WasmAsmParser::ParseDirectiveSymbolAttribute>(".weak"); addDirectiveHandler< &WasmAsmParser::ParseDirectiveSymbolAttribute>(".local"); addDirectiveHandler< &WasmAsmParser::ParseDirectiveSymbolAttribute>(".internal"); addDirectiveHandler< &WasmAsmParser::ParseDirectiveSymbolAttribute>(".hidden"); addDirectiveHandler<&WasmAsmParser::parseDirectiveSymver>(".symver"); } bool error(const StringRef &Msg, const AsmToken &Tok) { return Parser->Error(Tok.getLoc(), Msg + Tok.getString()); } bool isNext(AsmToken::TokenKind Kind) { auto Ok = Lexer->is(Kind); if (Ok) Lex(); return Ok; } bool expect(AsmToken::TokenKind Kind, const char *KindName) { if (!isNext(Kind)) return error(std::string("Expected ") + KindName + ", instead got: ", Lexer->getTok()); return false; } bool parseSectionDirectiveText(StringRef, SMLoc) { // FIXME: .text currently no-op. return false; } bool parseSectionDirectiveData(StringRef, SMLoc) { auto *S = getContext().getObjectFileInfo()->getDataSection(); getStreamer().switchSection(S); return false; } uint32_t parseSectionFlags(StringRef FlagStr, bool &Passive, bool &Group) { uint32_t flags = 0; for (char C : FlagStr) { switch (C) { case 'p': Passive = true; break; case 'G': Group = true; break; case 'T': flags |= wasm::WASM_SEG_FLAG_TLS; break; case 'S': flags |= wasm::WASM_SEG_FLAG_STRINGS; break; case 'R': flags |= wasm::WASM_SEG_FLAG_RETAIN; break; default: return -1U; } } return flags; } bool parseGroup(StringRef &GroupName) { if (Lexer->isNot(AsmToken::Comma)) return TokError("expected group name"); Lex(); if (Lexer->is(AsmToken::Integer)) { GroupName = getTok().getString(); Lex(); } else if (Parser->parseIdentifier(GroupName)) { return TokError("invalid group name"); } if (Lexer->is(AsmToken::Comma)) { Lex(); StringRef Linkage; if (Parser->parseIdentifier(Linkage)) return TokError("invalid linkage"); if (Linkage != "comdat") return TokError("Linkage must be 'comdat'"); } return false; } // A section name can contain '-' (e.g. glibc's .gnu.glibc-stub.* markers) and // other characters that are not part of a single lexer identifier token, so // -- exactly like ELFAsmParser::parseSectionName -- we cannot just use // parseIdentifier. Build the name from adjacent tokens up to the comma / end // of statement. bool parseSectionName(StringRef &SectionName) { SMLoc FirstLoc = Lexer->getLoc(); unsigned Size = 0; if (Lexer->is(AsmToken::String)) { SectionName = getTok().getIdentifier(); Lex(); return false; } while (!Parser->hasPendingError()) { SMLoc PrevLoc = Lexer->getLoc(); if (Lexer->is(AsmToken::Comma) || Lexer->is(AsmToken::EndOfStatement)) break; unsigned CurSize; if (Lexer->is(AsmToken::String)) { CurSize = getTok().getIdentifier().size() + 2; Lex(); } else if (Lexer->is(AsmToken::Identifier)) { CurSize = getTok().getIdentifier().size(); Lex(); } else { CurSize = getTok().getString().size(); Lex(); } Size += CurSize; SectionName = StringRef(FirstLoc.getPointer(), Size); // Make sure the following token is adjacent. if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer()) break; } if (Size == 0) return true; return false; } bool parseSectionDirective(StringRef, SMLoc loc) { StringRef Name; if (parseSectionName(Name)) return TokError("expected identifier in directive"); auto Kind = StringSwitch>(Name) .StartsWith(".data", SectionKind::getData()) .StartsWith(".tdata", SectionKind::getThreadData()) .StartsWith(".tbss", SectionKind::getThreadBSS()) .StartsWith(".rodata", SectionKind::getReadOnly()) .StartsWith(".text", SectionKind::getText()) .StartsWith(".custom_section", SectionKind::getMetadata()) .StartsWith(".bss", SectionKind::getBSS()) // See use of .init_array in WasmObjectWriter and // TargetLoweringObjectFileWasm .StartsWith(".init_array", SectionKind::getData()) .StartsWith(".debug_", SectionKind::getMetadata()) .Default(SectionKind::getData()); // GNU single-operand form: `.section ` with no flags/type operand. // GNU as accepts this bare spelling; glibc emits it (via the // link_warning / stub_warning machinery in include/libc-symbols.h) for // unallocated diagnostic marker sections such as `.gnu.warning.` and // `.gnu.glibc-stub.`, each immediately followed by `.previous`. wasm // (the object format) and wasm-ld have no ELF-style .gnu.warning / // .gnu.glibc-stub linker-warning feature, so these markers are purely // diagnostic and carry no allocated content. Accept the form and switch to // the (empty, unallocated) section so that a following `.previous` returns // to the prior section via the normal section stack; the marker itself // contributes nothing to the output. This never errors on a representable // construct and never drops real content: anything subsequently emitted // here still has a home in this section, exactly as on ELF. if (Lexer->is(AsmToken::EndOfStatement)) { MCSectionWasm *WS = getContext().getWasmSection(Name, *Kind); getStreamer().switchSection(WS); return false; } if (expect(AsmToken::Comma, ",")) return true; if (Lexer->isNot(AsmToken::String)) return error("expected string in directive, instead got: ", Lexer->getTok()); // Update section flags if present in this .section directive bool Passive = false; bool Group = false; uint32_t Flags = parseSectionFlags(getTok().getStringContents(), Passive, Group); if (Flags == -1U) return TokError("unknown flag"); Lex(); if (expect(AsmToken::Comma, ",") || expect(AsmToken::At, "@")) return true; StringRef GroupName; if (Group && parseGroup(GroupName)) return true; if (expect(AsmToken::EndOfStatement, "eol")) return true; // TODO: Parse UniqueID MCSectionWasm *WS = getContext().getWasmSection( Name, *Kind, Flags, GroupName, MCSection::NonUniqueID); if (WS->getSegmentFlags() != Flags) Parser->Error(loc, "changed section flags for " + Name + ", expected: 0x" + utohexstr(WS->getSegmentFlags())); if (Passive) { if (!WS->isWasmData()) return Parser->Error(loc, "Only data sections can be passive"); WS->setPassive(); } getStreamer().switchSection(WS); return false; } /// parseDirectivePrevious /// ::= .previous /// /// Switch back to the section that was active before the most recent /// `.section` / section switch, using the streamer's section stack -- the /// same semantics as ELFAsmParser::parseDirectivePrevious. glibc pairs every /// `.section .gnu.warning.*` / `.section .gnu.glibc-stub.*` marker with a /// `.previous` to restore the prior section; this was previously rejected on /// wasm as an "unknown directive". Mirror ELF exactly so the round-trip /// (`.section A` ... `.previous` -> back in A's predecessor) is preserved. bool parseDirectivePrevious(StringRef, SMLoc) { MCSectionSubPair PreviousSection = getStreamer().getPreviousSection(); if (PreviousSection.first == nullptr) return TokError(".previous without corresponding .section"); getStreamer().switchSection(PreviousSection.first, PreviousSection.second); return false; } // TODO: This function is almost the same as ELFAsmParser::ParseDirectiveSize // so maybe could be shared somehow. bool parseDirectiveSize(StringRef, SMLoc Loc) { MCSymbol *Sym; if (Parser->parseSymbol(Sym)) return TokError("expected identifier in directive"); if (expect(AsmToken::Comma, ",")) return true; const MCExpr *Expr; if (Parser->parseExpression(Expr)) return true; if (expect(AsmToken::EndOfStatement, "eol")) return true; auto WasmSym = static_cast(Sym); if (WasmSym->isFunction()) { // Ignore .size directives for function symbols. They get their size // set automatically based on their content. Warning(Loc, ".size directive ignored for function symbols"); } else { getStreamer().emitELFSize(Sym, Expr); } return false; } bool parseDirectiveType(StringRef, SMLoc) { // This could be the start of a function, check if followed by // "label,@function" if (!Lexer->is(AsmToken::Identifier)) return error("Expected label after .type directive, got: ", Lexer->getTok()); auto *WasmSym = static_cast( getStreamer().getContext().parseSymbol(Lexer->getTok().getString())); Lex(); // GNU `as` accepts both spellings of the symbol-type prefix: `@type` and // `%type` (e.g. `%object`, `%function`, `%gnu_indirect_function`). Stock // glibc's include/libc-symbols.h hardcodes the `%` form (e.g. // declare_object_symbol_alias_1 emits `.type sym, %object`), which the wasm // MC parser previously rejected, accepting only `@`. Accept `%` as an exact // synonym for `@` here -- mirroring ELFAsmParser, which accepts the `@`, // `#`, and `%` prefixes interchangeably. The prefix only selects the // spelling; the type name that follows is interpreted by the identical // switch below, so `%X` produces exactly the same wasm symbol type as `@X` // (and remains rejected for any name the `@` form would also reject). This // never errors on a representable construct and does not change `@`-form // behavior. if (!(isNext(AsmToken::Comma) && (isNext(AsmToken::At) || isNext(AsmToken::Percent)) && Lexer->is(AsmToken::Identifier))) return error("Expected label,@type declaration, got: ", Lexer->getTok()); auto TypeName = Lexer->getTok().getString(); if (TypeName == "function") { WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); auto *Current = static_cast(getStreamer().getCurrentSectionOnly()); if (Current->getGroup()) WasmSym->setComdat(true); } else if (TypeName == "global") WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); else if (TypeName == "object") WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA); else return error("Unknown WASM symbol type: ", Lexer->getTok()); Lex(); return expect(AsmToken::EndOfStatement, "EOL"); } // FIXME: Shared with ELF. /// ParseDirectiveIdent /// ::= .ident string bool ParseDirectiveIdent(StringRef, SMLoc) { if (getLexer().isNot(AsmToken::String)) return TokError("unexpected token in '.ident' directive"); StringRef Data = getTok().getIdentifier(); Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.ident' directive"); Lex(); getStreamer().emitIdent(Data); return false; } // FIXME: Shared with ELF. /// ParseDirectiveSymbolAttribute /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ] bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) { MCSymbolAttr Attr = StringSwitch(Directive) .Case(".weak", MCSA_Weak) .Case(".local", MCSA_Local) .Case(".hidden", MCSA_Hidden) .Case(".internal", MCSA_Internal) .Case(".protected", MCSA_Protected) .Default(MCSA_Invalid); assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!"); if (getLexer().isNot(AsmToken::EndOfStatement)) { while (true) { MCSymbol *Sym; if (getParser().parseSymbol(Sym)) return TokError("expected identifier in directive"); getStreamer().emitSymbolAttribute(Sym, Attr); if (getLexer().is(AsmToken::EndOfStatement)) break; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); } } Lex(); return false; } /// parseDirectiveSymver /// ::= .symver foo, bar@@@ver /// /// wasm (the object format) has no ELF-style symbol versioning, and this is a /// fresh ABI with no legacy binaries, so version selection collapses to "the /// default version only". We map the directive onto the existing assembler /// alias machinery (the same representation extended by the prior /// alias-to-undefined-target fix in WasmObjectWriter): /// /// - default version (`bar@@ver`): make `bar` a public alias of `foo`, /// dropping the version tag. `bar` then resolves to `foo` at link, exactly /// like `.set bar, foo` followed by `.globl bar`. /// - non-default / compat version (`bar@ver`, single `@`): a compat symbol /// for OLD binaries, which do not exist on this fresh ABI. Emitting a /// second public `bar` here would collide with the default `bar`, so the /// compat alias is dropped. `foo` itself is left untouched (it remains a /// defined symbol in its own right). /// /// This never errors with "unknown directive" and never mis-resolves: the /// default binding is always materialized correctly, and we never emit two /// conflicting public definitions of the base name. bool parseDirectiveSymver(StringRef, SMLoc Loc) { MCSymbol *OriginalSym; if (getParser().parseSymbol(OriginalSym)) return TokError("expected identifier in .symver directive"); if (getLexer().isNot(AsmToken::Comma)) return TokError("expected a comma in .symver directive"); // '@' is a comment in some assembly dialects, but is required inside the // versioned name here. Allow it for the next identifier only, mirroring // ELFAsmParser::parseDirectiveSymver. const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier(); getLexer().setAllowAtInIdentifier(true); Lex(); getLexer().setAllowAtInIdentifier(AllowAtInIdentifier); StringRef Name; if (getParser().parseIdentifier(Name)) return TokError("expected identifier in .symver directive"); size_t Pos = Name.find('@'); if (Pos == StringRef::npos) return Error(Loc, "expected a '@' in the .symver versioned name"); // Accept (and ignore) the optional ", remove" tail and the end of line, so // every well-formed ELF `.symver` spelling is parsed rather than rejected. if (parseOptionalToken(AsmToken::Comma)) { StringRef Action; if (getParser().parseIdentifier(Action) || Action != "remove") return TokError("expected 'remove'"); } (void)parseOptionalToken(AsmToken::EndOfStatement); StringRef BareName = Name.substr(0, Pos); StringRef Rest = Name.substr(Pos); // one or more leading '@' // "@@" (and "@@@") select the default version; a single "@" is a // non-default / compat version. bool IsDefault = Rest.starts_with("@@"); if (!IsDefault) { // Compat version: drop it. No legacy binaries exist on this ABI, so // nothing consumes the compat alias, and creating a second public // `BareName` would collide with the default. Never-silent: we deliberately // omit a consumer-less compat alias rather than mis-resolve or duplicate. return false; } // Default version: BareName becomes a public alias of OriginalSym with the // version tag dropped. Reuse the assembler-alias representation so the // WasmObjectWriter resolves BareName to its base symbol at link time. MCSymbol *AliasSym = getContext().getOrCreateSymbol(BareName); const MCExpr *Value = MCSymbolRefExpr::create(OriginalSym, getContext()); getStreamer().emitAssignment(AliasSym, Value); // The default version is the public/exported binding of the base name. getStreamer().emitSymbolAttribute(AliasSym, MCSA_Global); return false; } }; } // end anonymous namespace MCAsmParserExtension *llvm::createWasmAsmParser() { return new WasmAsmParser; }