forked from facebook/buck
/
HeaderMap.java
460 lines (386 loc) · 12.9 KB
/
HeaderMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.apple.clang;
import static java.lang.Math.max;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Add support for reading and generating clang header maps
*
* Header maps are essentially hash maps from strings to paths (coded as two strings: a prefix and
* a suffix).
*
* No spec is available but we conform to the reader class here:
* http://clang.llvm.org/doxygen/HeaderMap_8h_source.html
*
* Note: currently we don't support offsets greater than MAX_SIGNED_INT
*/
public class HeaderMap {
// Hashtable buckets
// Note: This notion of bucket is slightly more abstract than the one on disk
// (string offsets being already swapped/shifted)
private static class Bucket {
final int key; // Offset of the key string into stringBytes.
final int prefix; // Offset of the value prefix into stringBytes.
final int suffix; // Offset of the value suffix into stringBytes.
Bucket(int key, int prefix, int suffix) {
this.key = key;
this.prefix = prefix;
this.suffix = suffix;
}
}
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private int numEntries; // Number of entries in the string table.
private int numBuckets; // Number of buckets (always a power of 2).
private int maxValueLength; // Length of longest result path (excluding nul).
// data containers
private Bucket[] buckets;
private byte[] stringBytes; // actually chars to make debugging easier
private int stringBytesActualLength;
// map to help share strings
private Map<String, Integer> addedStrings;
private HeaderMap(int numBuckets, int stringBytesLength) {
Preconditions.checkState(numBuckets > 0, "The number of buckets must be greater than 0");
Preconditions.checkState(stringBytesLength > 0,
"The size of the string array must be greater than 0");
Preconditions.checkState((numBuckets & (numBuckets - 1)) == 0,
"The number of buckets must be a power of 2");
this.numEntries = 0;
this.numBuckets = numBuckets;
this.maxValueLength = 0;
this.buckets = new Bucket[numBuckets];
this.stringBytes = new byte[stringBytesLength];
this.stringBytesActualLength = 0;
this.addedStrings = new HashMap<String, Integer>();
}
public int getNumEntries() {
return numEntries;
}
public int getNumBuckets() {
return numBuckets;
}
public int getMaxValueLength() {
return maxValueLength;
}
public interface HeaderMapVisitor {
void apply(String str, String prefix, String suffix);
}
public void visit(HeaderMapVisitor visitor) {
for (int i = 0; i < numBuckets; i++) {
Bucket bucket = buckets[i];
if (bucket != null) {
visitor.apply(
getString(bucket.key),
getString(bucket.prefix),
getString(bucket.suffix)
);
}
}
}
@Override
public String toString() {
final StringBuffer buffer = new StringBuffer();
visit(new HeaderMapVisitor() {
@Override
public void apply(String str, String prefix, String suffix) {
buffer.append("\"");
buffer.append(str);
buffer.append("\" -> \"");
buffer.append(prefix);
buffer.append(suffix);
buffer.append("\"\n");
}
});
return buffer.toString();
}
public void print(final PrintStream stream) {
visit(new HeaderMapVisitor() {
@Override
public void apply(String str, String prefix, String suffix) {
stream.print("\"");
stream.print(str);
stream.print("\" -> \"");
stream.print(prefix);
stream.print(suffix);
stream.print("\"\n");
}
});
}
@Nullable
public String lookup(String str) {
int hash0 = hashKey(str) & (numBuckets - 1);
int hash = hash0;
while (true) {
Bucket bucket = buckets[hash];
if (bucket == null) {
return null;
}
if (str.equalsIgnoreCase(getString(bucket.key))) {
return getString(bucket.prefix) + getString(bucket.suffix);
}
hash = (hash + 1) & (numBuckets - 1);
if (hash == hash0) {
return null;
}
}
}
// --------- I/O methods ----------
private static final int HEADER_MAGIC = ('h' << 24) | ('m' << 16) | ('a' << 8) | 'p';
private static final short HEADER_VERSION = 1;
private static final short HEADER_RESERVED = 0;
private static final int EMPTY_BUCKET_KEY = 0;
private static final int HEADER_SIZE = 24;
private static final int BUCKET_SIZE = 12;
@Nullable
public static HeaderMap deserialize(byte[] bytes) {
HeaderMap hmap = new HeaderMap(1, 1);
if (hmap.processBytes(bytes)) {
return hmap;
} else {
return null;
}
}
@Nullable
public static HeaderMap deserialize(ByteBuffer buffer) {
HeaderMap hmap = new HeaderMap(1, 1);
if (hmap.processBuffer(buffer)) {
return hmap;
} else {
return null;
}
}
private boolean processBytes(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
return processBuffer(buffer);
}
private boolean processBuffer(ByteBuffer buffer) {
buffer.order(ByteOrder.BIG_ENDIAN);
if (buffer.getInt(0) != HEADER_MAGIC) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
int magic = buffer.getInt();
short version = buffer.getShort();
if (magic != HEADER_MAGIC || version != HEADER_VERSION) {
return false;
}
/* reserved */ buffer.getShort();
int stringOffset = buffer.getInt();
numEntries = buffer.getInt();
numBuckets = buffer.getInt();
maxValueLength = buffer.getInt();
// strings can be anywhere after the end of the buckets
stringBytesActualLength = buffer.capacity() - HEADER_SIZE - numBuckets * BUCKET_SIZE;
buckets = new Bucket[numBuckets];
int actualOffset = HEADER_SIZE + numBuckets * BUCKET_SIZE - stringOffset;
// actualOffset should always be positive since the index EMPTY_BUCKET_KEY=0 is reserved
for (int i = 0; i < numBuckets; i++) {
int keyRawOffset = buffer.getInt();
int prefixRawOffset = buffer.getInt();
int suffixRawOffset = buffer.getInt();
if (keyRawOffset == EMPTY_BUCKET_KEY) {
buckets[i] = null;
} else {
// we can subtract 1 value because index 0 is EMPTY_BUCKET_KEY
buckets[i] = new Bucket(
keyRawOffset - actualOffset,
prefixRawOffset - actualOffset,
suffixRawOffset - actualOffset
);
}
}
// anything else is string
stringBytes = new byte[stringBytesActualLength];
buffer.get(stringBytes);
return true;
}
public int getRequiredBufferCapacity() {
return HEADER_SIZE + numBuckets * BUCKET_SIZE + stringBytesActualLength;
}
public byte[] getBytes() {
return getBytes(ByteOrder.BIG_ENDIAN);
}
public byte[] getBytes(ByteOrder bo) {
byte[] bytes = new byte[getRequiredBufferCapacity()];
ByteBuffer buffer = ByteBuffer.wrap(bytes).order(bo);
serialize(buffer);
return bytes;
}
public void serialize(ByteBuffer buffer) {
int actualOffset = 1; // must be greater than EMPTY_BUCKET_KEY
buffer.putInt(HEADER_MAGIC);
buffer.putShort(HEADER_VERSION);
buffer.putShort(HEADER_RESERVED);
buffer.putInt(HEADER_SIZE + numBuckets * BUCKET_SIZE - actualOffset);
buffer.putInt(numEntries);
buffer.putInt(numBuckets);
buffer.putInt(maxValueLength);
for (int i = 0; i < numBuckets; i++) {
Bucket bucket = buckets[i];
if (bucket == null) {
buffer.putInt(EMPTY_BUCKET_KEY);
buffer.putInt(0);
buffer.putInt(0);
} else {
buffer.putInt(bucket.key + actualOffset);
buffer.putInt(bucket.prefix + actualOffset);
buffer.putInt(bucket.suffix + actualOffset);
}
}
buffer.put(stringBytes, 0, stringBytesActualLength);
}
// -------------- Builder class ----------------
public static Builder builder() {
return new Builder();
}
public static class Builder {
static final int DEFAULT_NUM_BUCKETS = 256;
static final int DEFAULT_STRING_BYTES_LENGTH = 256;
HeaderMap headerMap;
public Builder() {
this.headerMap = new HeaderMap(DEFAULT_NUM_BUCKETS, DEFAULT_STRING_BYTES_LENGTH);
}
public synchronized boolean add(String key, String prefix, String suffix) {
AddResult result = headerMap.add(key, prefix, suffix);
while (result == AddResult.FAILURE_FULL) {
// the table is full, let's start all over again with a doubled number of bucket
// and (optimization) the same size of string bytes
final HeaderMap newHeaderMap = new HeaderMap(
headerMap.numBuckets * 2,
headerMap.stringBytes.length
);
headerMap.visit(
new HeaderMapVisitor() {
@Override
public void apply(String str, String prefix, String suffix) {
AddResult copying = newHeaderMap.add(str, prefix, suffix);
assert (copying == AddResult.OK);
}
});
headerMap = newHeaderMap;
result = headerMap.add(key, prefix, suffix);
}
return (result == AddResult.OK);
}
public static String[] splitPath(Path path) {
String[] result = new String[2];
if (path.getNameCount() < 2) {
result[0] = "";
result[1] = path.toString();
} else {
result[0] = path.getParent().toString() + "/";
result[1] = path.getFileName().toString();
}
return result;
}
public boolean add(String key, Path path) {
String[] s = splitPath(path);
return add(key, s[0], s[1]);
}
public synchronized HeaderMap build() {
return headerMap;
}
}
// ------------- Internals -----------
private static int hashKey(String str) {
// ASCII lowercase is part of the format
// UTF8 is the standard filesystem charset
return hashKey(Ascii.toLowerCase(str).getBytes(DEFAULT_CHARSET));
}
private static int hashKey(byte[] str) {
int key = 0;
for (byte c : str) {
key += c * 13;
}
return key;
}
private enum AddResult {
OK,
FAILURE_FULL,
FAILURE_ALREADY_PRESENT
};
@SuppressWarnings("unused")
private AddResult add(String str, String prefix, String suffix) {
int hash0 = hashKey(str) & (numBuckets - 1);
int hash = hash0;
while (true) {
Bucket bucket = buckets[hash];
if (bucket == null) {
bucket = new Bucket(
addString(str),
addString(prefix),
addString(suffix)
);
buckets[hash] = bucket;
numEntries++;
maxValueLength = max(maxValueLength, prefix.length() + suffix.length());
return AddResult.OK;
}
if (str.equalsIgnoreCase(getString(bucket.key))) {
return AddResult.FAILURE_ALREADY_PRESENT;
}
hash = (hash + 1) & (numBuckets - 1);
if (hash == hash0) {
return AddResult.FAILURE_FULL;
}
}
}
@Nullable
private String getString(int offset) {
Preconditions.checkState(offset >= 0 && offset <= stringBytesActualLength);
StringBuffer buffer = new StringBuffer();
byte b = 0;
while ((offset < stringBytesActualLength) && ((b = stringBytes[offset]) != 0)) {
buffer.append((char) b);
offset++;
}
if (offset == stringBytesActualLength) {
// we reached the end of the array without finding a 0
return null;
}
return buffer.toString();
}
private void putStringByte(byte b) {
if (stringBytesActualLength == stringBytes.length) {
byte[] newBytes = new byte[stringBytes.length * 2];
System.arraycopy(stringBytes, 0, newBytes, 0, stringBytesActualLength);
stringBytes = newBytes;
}
stringBytes[stringBytesActualLength] = b;
stringBytesActualLength++;
}
private int addString(String str) {
Integer existingOffset = addedStrings.get(str);
if (existingOffset != null) {
return existingOffset.intValue();
}
int offset = stringBytesActualLength;
for (byte b : str.getBytes(DEFAULT_CHARSET)) {
putStringByte(b);
}
putStringByte((byte) 0);
addedStrings.put(str, offset);
return offset;
}
}