Coverage Report

Created: 2018-01-17 17:22

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/ScriptLexer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ScriptLexer.cpp ----------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file defines a lexer for the linker script.
11
//
12
// The linker script's grammar is not complex but ambiguous due to the
13
// lack of the formal specification of the language. What we are trying to
14
// do in this and other files in LLD is to make a "reasonable" linker
15
// script processor.
16
//
17
// Among simplicity, compatibility and efficiency, we put the most
18
// emphasis on simplicity when we wrote this lexer. Compatibility with the
19
// GNU linkers is important, but we did not try to clone every tiny corner
20
// case of their lexers, as even ld.bfd and ld.gold are subtly different
21
// in various corner cases. We do not care much about efficiency because
22
// the time spent in parsing linker scripts is usually negligible.
23
//
24
// Our grammar of the linker script is LL(2), meaning that it needs at
25
// most two-token lookahead to parse. The only place we need two-token
26
// lookahead is labels in version scripts, where we need to parse "local :"
27
// as if "local:".
28
//
29
// Overall, this lexer works fine for most linker scripts. There might
30
// be room for improving compatibility, but that's probably not at the
31
// top of our todo list.
32
//
33
//===----------------------------------------------------------------------===//
34
35
#include "ScriptLexer.h"
36
#include "lld/Common/ErrorHandler.h"
37
#include "llvm/ADT/Twine.h"
38
39
using namespace llvm;
40
using namespace lld;
41
using namespace lld::elf;
42
43
// Returns a whole line containing the current token.
44
100
StringRef ScriptLexer::getLine() {
45
100
  StringRef S = getCurrentMB().getBuffer();
46
100
  StringRef Tok = Tokens[Pos - 1];
47
100
48
100
  size_t Pos = S.rfind('\n', Tok.data() - S.data());
49
100
  if (Pos != StringRef::npos)
50
20
    S = S.substr(Pos + 1);
51
100
  return S.substr(0, S.find_first_of("\r\n"));
52
100
}
53
54
// Returns 1-based line number of the current token.
55
2.39k
size_t ScriptLexer::getLineNumber() {
56
2.39k
  StringRef S = getCurrentMB().getBuffer();
57
2.39k
  StringRef Tok = Tokens[Pos - 1];
58
2.39k
  return S.substr(0, Tok.data() - S.data()).count('\n') + 1;
59
2.39k
}
60
61
// Returns 0-based column number of the current token.
62
50
size_t ScriptLexer::getColumnNumber() {
63
50
  StringRef Tok = Tokens[Pos - 1];
64
50
  return Tok.data() - getLine().data();
65
50
}
66
67
2.39k
std::string ScriptLexer::getCurrentLocation() {
68
2.39k
  std::string Filename = getCurrentMB().getBufferIdentifier();
69
2.39k
  if (!Pos)
70
0
    return Filename;
71
2.39k
  return (Filename + ":" + Twine(getLineNumber())).str();
72
2.39k
}
73
74
566
ScriptLexer::ScriptLexer(MemoryBufferRef MB) { tokenize(MB); }
75
76
// We don't want to record cascading errors. Keep only the first one.
77
64
void ScriptLexer::setError(const Twine &Msg) {
78
64
  if (errorCount())
79
14
    return;
80
50
81
50
  std::string S = (getCurrentLocation() + ": " + Msg).str();
82
50
  if (Pos)
83
50
    S += "\n>>> " + getLine().str() + "\n>>> " +
84
50
         std::string(getColumnNumber(), ' ') + "^";
85
50
  error(S);
86
50
}
87
88
// Split S into linker script tokens.
89
580
void ScriptLexer::tokenize(MemoryBufferRef MB) {
90
580
  std::vector<StringRef> Vec;
91
580
  MBs.push_back(MB);
92
580
  StringRef S = MB.getBuffer();
93
580
  StringRef Begin = S;
94
580
95
11.6k
  for (;;) {
96
11.6k
    S = skipSpace(S);
97
11.6k
    if (S.empty())
98
576
      break;
99
11.0k
100
11.0k
    // Quoted token. Note that double-quote characters are parts of a token
101
11.0k
    // because, in a glob match context, only unquoted tokens are interpreted
102
11.0k
    // as glob patterns. Double-quoted tokens are literal patterns in that
103
11.0k
    // context.
104
11.0k
    if (S.startswith("\"")) {
105
102
      size_t E = S.find("\"", 1);
106
102
      if (E == StringRef::npos) {
107
4
        StringRef Filename = MB.getBufferIdentifier();
108
4
        size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
109
4
        error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
110
4
        return;
111
4
      }
112
98
113
98
      Vec.push_back(S.take_front(E + 1));
114
98
      S = S.substr(E + 1);
115
98
      continue;
116
98
    }
117
10.9k
118
10.9k
    // ">foo" is parsed to ">" and "foo", but ">>" is parsed to ">>".
119
10.9k
    if (S.startswith("<<") || 
S.startswith("<=")10.9k
||
S.startswith(">>")10.9k
||
120
10.9k
        
S.startswith(">=")10.9k
) {
121
4
      Vec.push_back(S.substr(0, 2));
122
4
      S = S.substr(2);
123
4
      continue;
124
4
    }
125
10.9k
126
10.9k
    // Unquoted token. This is more relaxed than tokens in C-like language,
127
10.9k
    // so that you can write "file-name.cpp" as one bare token, for example.
128
10.9k
    size_t Pos = S.find_first_not_of(
129
10.9k
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
130
10.9k
        "0123456789_.$/\\~=+[]*?-!^:");
131
10.9k
132
10.9k
    // A character that cannot start a word (which is usually a
133
10.9k
    // punctuation) forms a single character token.
134
10.9k
    if (Pos == 0)
135
5.19k
      Pos = 1;
136
10.9k
    Vec.push_back(S.substr(0, Pos));
137
10.9k
    S = S.substr(Pos);
138
10.9k
  }
139
580
140
580
  Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
141
576
}
142
143
// Skip leading whitespace characters or comments.
144
11.6k
StringRef ScriptLexer::skipSpace(StringRef S) {
145
18.6k
  for (;;) {
146
18.6k
    if (S.startswith("/*")) {
147
9
      size_t E = S.find("*/", 2);
148
9
      if (E == StringRef::npos) {
149
1
        error("unclosed comment in a linker script");
150
1
        return "";
151
1
      }
152
8
      S = S.substr(E + 2);
153
8
      continue;
154
8
    }
155
18.6k
    if (S.startswith("#")) {
156
3
      size_t E = S.find('\n', 1);
157
3
      if (E == StringRef::npos)
158
1
        E = S.size() - 1;
159
3
      S = S.substr(E + 1);
160
3
      continue;
161
3
    }
162
18.6k
    size_t Size = S.size();
163
18.6k
    S = S.ltrim();
164
18.6k
    if (S.size() == Size)
165
11.6k
      return S;
166
18.6k
  }
167
11.6k
}
168
169
// An erroneous token is handled as if it were the last token before EOF.
170
46.7k
bool ScriptLexer::atEOF() { return errorCount() || 
Tokens.size() == Pos46.6k
; }
171
172
// Split a given string as an expression.
173
// This function returns "3", "*" and "5" for "3*5" for example.
174
6.39k
static std::vector<StringRef> tokenizeExpr(StringRef S) {
175
6.39k
  StringRef Ops = "+-*/:!~"; // List of operators
176
6.39k
177
6.39k
  // Quoted strings are literal strings, so we don't want to split it.
178
6.39k
  if (S.startswith("\""))
179
5
    return {S};
180
6.38k
181
6.38k
  // Split S with operators as separators.
182
6.38k
  std::vector<StringRef> Ret;
183
6.89k
  while (!S.empty()) {
184
6.39k
    size_t E = S.find_first_of(Ops);
185
6.39k
186
6.39k
    // No need to split if there is no operator.
187
6.39k
    if (E == StringRef::npos) {
188
5.88k
      Ret.push_back(S);
189
5.88k
      break;
190
5.88k
    }
191
512
192
512
    // Get a token before the opreator.
193
512
    if (E != 0)
194
7
      Ret.push_back(S.substr(0, E));
195
512
196
512
    // Get the operator as a token. Keep != as one token.
197
512
    if (S.substr(E).startswith("!=")) {
198
7
      Ret.push_back(S.substr(E, 2));
199
7
      S = S.substr(E + 2);
200
505
    } else {
201
505
      Ret.push_back(S.substr(E, 1));
202
505
      S = S.substr(E + 1);
203
505
    }
204
512
  }
205
6.38k
  return Ret;
206
6.38k
}
207
208
// In contexts where expressions are expected, the lexer should apply
209
// different tokenization rules than the default one. By default,
210
// arithmetic operator characters are regular characters, but in the
211
// expression context, they should be independent tokens.
212
//
213
// For example, "foo*3" should be tokenized to "foo", "*" and "3" only
214
// in the expression context.
215
//
216
// This function may split the current token into multiple tokens.
217
38.2k
void ScriptLexer::maybeSplitExpr() {
218
38.2k
  if (!InExpr || 
errorCount()6.40k
||
atEOF()6.39k
)
219
31.8k
    return;
220
6.39k
221
6.39k
  std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
222
6.39k
  if (V.size() == 1)
223
6.38k
    return;
224
11
  Tokens.erase(Tokens.begin() + Pos);
225
11
  Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
226
11
}
227
228
38.2k
StringRef ScriptLexer::next() {
229
38.2k
  maybeSplitExpr();
230
38.2k
231
38.2k
  if (errorCount())
232
119
    return "";
233
38.1k
  if (atEOF()) {
234
7
    setError("unexpected EOF");
235
7
    return "";
236
7
  }
237
38.1k
  return Tokens[Pos++];
238
38.1k
}
239
240
27.4k
StringRef ScriptLexer::peek() {
241
27.4k
  StringRef Tok = next();
242
27.4k
  if (errorCount())
243
115
    return "";
244
27.3k
  Pos = Pos - 1;
245
27.3k
  return Tok;
246
27.3k
}
247
248
17.3k
bool ScriptLexer::consume(StringRef Tok) {
249
17.3k
  if (peek() == Tok) {
250
2.15k
    skip();
251
2.15k
    return true;
252
2.15k
  }
253
15.2k
  return false;
254
15.2k
}
255
256
// Consumes Tok followed by ":". Space is allowed between Tok and ":".
257
473
bool ScriptLexer::consumeLabel(StringRef Tok) {
258
473
  if (consume((Tok + ":").str()))
259
110
    return true;
260
363
  if (Tokens.size() >= Pos + 2 && 
Tokens[Pos] == Tok361
&&
261
363
      
Tokens[Pos + 1] == ":"6
) {
262
5
    Pos += 2;
263
5
    return true;
264
5
  }
265
358
  return false;
266
358
}
267
268
2.29k
void ScriptLexer::skip() { (void)next(); }
269
270
3.88k
void ScriptLexer::expect(StringRef Expect) {
271
3.88k
  if (errorCount())
272
39
    return;
273
3.84k
  StringRef Tok = next();
274
3.84k
  if (Tok != Expect)
275
13
    setError(Expect + " expected, but got " + Tok);
276
3.84k
}
277
278
// Returns true if S encloses T.
279
4.94k
static bool encloses(StringRef S, StringRef T) {
280
4.94k
  return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
281
4.94k
}
282
283
4.89k
MemoryBufferRef ScriptLexer::getCurrentMB() {
284
4.89k
  // Find input buffer containing the current token.
285
4.89k
  assert(!MBs.empty());
286
4.89k
  if (!Pos)
287
0
    return MBs[0];
288
4.89k
289
4.89k
  for (MemoryBufferRef MB : MBs)
290
4.94k
    if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
291
4.89k
      return MB;
292
4.89k
  
llvm_unreachable0
("getCurrentMB: failed to find a token");
293
}