xref: /aosp_15_r20/external/libchrome/base/i18n/build_utf8_validator_tables.cc (revision 635a864187cb8b6c713ff48b7e790a6b21769273)
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Create a state machine for validating UTF-8. The algorithm in brief:
6 // 1. Convert the complete unicode range of code points, except for the
7 //    surrogate code points, to an ordered array of sequences of bytes in
8 //    UTF-8.
9 // 2. Convert individual bytes to ranges, starting from the right of each byte
10 //    sequence. For each range, ensure the bytes on the left and the ranges
11 //    on the right are the identical.
12 // 3. Convert the resulting list of ranges into a state machine, collapsing
13 //    identical states.
14 // 4. Convert the state machine to an array of bytes.
15 // 5. Output as a C++ file.
16 //
17 // To use:
18 //  $ ninja -C out/Release build_utf8_validator_tables
19 //  $ out/Release/build_utf8_validator_tables
20 //                                   --output=base/i18n/utf8_validator_tables.cc
21 //  $ git add base/i18n/utf8_validator_tables.cc
22 //
23 // Because the table is not expected to ever change, it is checked into the
24 // repository rather than being regenerated at build time.
25 //
26 // This code uses type uint8_t throughout to represent bytes, to avoid
27 // signed/unsigned char confusion.
28 
29 #include <stddef.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include <algorithm>
36 #include <map>
37 #include <string>
38 #include <vector>
39 
40 #include "base/command_line.h"
41 #include "base/files/file_path.h"
42 #include "base/files/file_util.h"
43 #include "base/logging.h"
44 #include "base/macros.h"
45 #include "base/numerics/safe_conversions.h"
46 #include "base/strings/stringprintf.h"
47 #include "third_party/icu/source/common/unicode/utf8.h"
48 
49 namespace {
50 
51 const char kHelpText[] =
52     "Usage: build_utf8_validator_tables [ --help ] [ --output=<file> ]\n";
53 
54 const char kProlog[] =
55     "// Copyright 2013 The Chromium Authors. All rights reserved.\n"
56     "// Use of this source code is governed by a BSD-style license that can "
57     "be\n"
58     "// found in the LICENSE file.\n"
59     "\n"
60     "// This file is auto-generated by build_utf8_validator_tables.\n"
61     "// DO NOT EDIT.\n"
62     "\n"
63     "#include \"base/i18n/utf8_validator_tables.h\"\n"
64     "\n"
65     "namespace base {\n"
66     "namespace internal {\n"
67     "\n"
68     "const uint8_t kUtf8ValidatorTables[] = {\n";
69 
70 const char kEpilog[] =
71     "};\n"
72     "\n"
73     "const size_t kUtf8ValidatorTablesSize = arraysize(kUtf8ValidatorTables);\n"
74     "\n"
75     "}  // namespace internal\n"
76     "}  // namespace base\n";
77 
78 // Ranges are inclusive at both ends--they represent [from, to]
79 class Range {
80  public:
81   // Ranges always start with just one byte.
Range(uint8_t value)82   explicit Range(uint8_t value) : from_(value), to_(value) {}
83 
84   // Range objects are copyable and assignable to be used in STL
85   // containers. Since they only contain non-pointer POD types, the default copy
86   // constructor, assignment operator and destructor will work.
87 
88   // Add a byte to the range. We intentionally only support adding a byte at the
89   // end, since that is the only operation the code needs.
AddByte(uint8_t to)90   void AddByte(uint8_t to) {
91     CHECK(to == to_ + 1);
92     to_ = to;
93   }
94 
from() const95   uint8_t from() const { return from_; }
to() const96   uint8_t to() const { return to_; }
97 
operator <(const Range & rhs) const98   bool operator<(const Range& rhs) const {
99     return (from() < rhs.from() || (from() == rhs.from() && to() < rhs.to()));
100   }
101 
operator ==(const Range & rhs) const102   bool operator==(const Range& rhs) const {
103     return from() == rhs.from() && to() == rhs.to();
104   }
105 
106  private:
107   uint8_t from_;
108   uint8_t to_;
109 };
110 
111 // A vector of Ranges is like a simple regular expression--it corresponds to
112 // a set of strings of the same length that have bytes in each position in
113 // the appropriate range.
114 typedef std::vector<Range> StringSet;
115 
116 // A UTF-8 "character" is represented by a sequence of bytes.
117 typedef std::vector<uint8_t> Character;
118 
119 // In the second stage of the algorithm, we want to convert a large list of
120 // Characters into a small list of StringSets.
121 struct Pair {
122   Character character;
123   StringSet set;
124 };
125 
126 typedef std::vector<Pair> PairVector;
127 
128 // A class to print a table of numbers in the same style as clang-format.
129 class TablePrinter {
130  public:
TablePrinter(FILE * stream)131   explicit TablePrinter(FILE* stream)
132       : stream_(stream), values_on_this_line_(0), current_offset_(0) {}
133 
PrintValue(uint8_t value)134   void PrintValue(uint8_t value) {
135     if (values_on_this_line_ == 0) {
136       fputs("   ", stream_);
137     } else if (values_on_this_line_ == kMaxValuesPerLine) {
138       fprintf(stream_, "  // 0x%02x\n   ", current_offset_);
139       values_on_this_line_ = 0;
140     }
141     fprintf(stream_, " 0x%02x,", static_cast<int>(value));
142     ++values_on_this_line_;
143     ++current_offset_;
144   }
145 
NewLine()146   void NewLine() {
147     while (values_on_this_line_ < kMaxValuesPerLine) {
148       fputs("      ", stream_);
149       ++values_on_this_line_;
150     }
151     fprintf(stream_, "  // 0x%02x\n", current_offset_);
152     values_on_this_line_ = 0;
153   }
154 
155  private:
156   // stdio stream. Not owned.
157   FILE* stream_;
158 
159   // Number of values so far printed on this line.
160   int values_on_this_line_;
161 
162   // Total values printed so far.
163   int current_offset_;
164 
165   static const int kMaxValuesPerLine = 8;
166 
167   DISALLOW_COPY_AND_ASSIGN(TablePrinter);
168 };
169 
170 // Start by filling a PairVector with characters. The resulting vector goes from
171 // "\x00" to "\xf4\x8f\xbf\xbf".
InitializeCharacters()172 PairVector InitializeCharacters() {
173   PairVector vector;
174   for (int i = 0; i <= 0x10FFFF; ++i) {
175     if (i >= 0xD800 && i < 0xE000) {
176       // Surrogate codepoints are not permitted. Non-character code points are
177       // explicitly permitted.
178       continue;
179     }
180     uint8_t bytes[4];
181     unsigned int offset = 0;
182     UBool is_error = false;
183     U8_APPEND(bytes, offset, arraysize(bytes), i, is_error);
184     DCHECK(!is_error);
185     DCHECK_GT(offset, 0u);
186     DCHECK_LE(offset, arraysize(bytes));
187     Pair pair = {Character(bytes, bytes + offset), StringSet()};
188     vector.push_back(pair);
189   }
190   return vector;
191 }
192 
193 // Construct a new Pair from |character| and the concatenation of |new_range|
194 // and |existing_set|, and append it to |pairs|.
ConstructPairAndAppend(const Character & character,const Range & new_range,const StringSet & existing_set,PairVector * pairs)195 void ConstructPairAndAppend(const Character& character,
196                             const Range& new_range,
197                             const StringSet& existing_set,
198                             PairVector* pairs) {
199   Pair new_pair = {character, StringSet(1, new_range)};
200   new_pair.set.insert(
201       new_pair.set.end(), existing_set.begin(), existing_set.end());
202   pairs->push_back(new_pair);
203 }
204 
205 // Each pass over the PairVector strips one byte off the right-hand-side of the
206 // characters and adds a range to the set on the right. For example, the first
207 // pass converts the range from "\xe0\xa0\x80" to "\xe0\xa0\xbf" to ("\xe0\xa0",
208 // [\x80-\xbf]), then the second pass converts the range from ("\xe0\xa0",
209 // [\x80-\xbf]) to ("\xe0\xbf", [\x80-\xbf]) to ("\xe0",
210 // [\xa0-\xbf][\x80-\xbf]).
MoveRightMostCharToSet(PairVector * pairs)211 void MoveRightMostCharToSet(PairVector* pairs) {
212   PairVector new_pairs;
213   PairVector::const_iterator it = pairs->begin();
214   while (it != pairs->end() && it->character.empty()) {
215     new_pairs.push_back(*it);
216     ++it;
217   }
218   CHECK(it != pairs->end());
219   Character unconverted_bytes(it->character.begin(), it->character.end() - 1);
220   Range new_range(it->character.back());
221   StringSet converted = it->set;
222   ++it;
223   while (it != pairs->end()) {
224     const Pair& current_pair = *it++;
225     if (current_pair.character.size() == unconverted_bytes.size() + 1 &&
226         std::equal(unconverted_bytes.begin(),
227                    unconverted_bytes.end(),
228                    current_pair.character.begin()) &&
229         converted == current_pair.set) {
230       // The particular set of UTF-8 codepoints we are validating guarantees
231       // that each byte range will be contiguous. This would not necessarily be
232       // true for an arbitrary set of UTF-8 codepoints.
233       DCHECK_EQ(new_range.to() + 1, current_pair.character.back());
234       new_range.AddByte(current_pair.character.back());
235       continue;
236     }
237     ConstructPairAndAppend(unconverted_bytes, new_range, converted, &new_pairs);
238     unconverted_bytes = Character(current_pair.character.begin(),
239                                   current_pair.character.end() - 1);
240     new_range = Range(current_pair.character.back());
241     converted = current_pair.set;
242   }
243   ConstructPairAndAppend(unconverted_bytes, new_range, converted, &new_pairs);
244   new_pairs.swap(*pairs);
245 }
246 
MoveAllCharsToSets(PairVector * pairs)247 void MoveAllCharsToSets(PairVector* pairs) {
248   // Since each pass of the function moves one character, and UTF-8 sequences
249   // are at most 4 characters long, this simply runs the algorithm four times.
250   for (int i = 0; i < 4; ++i) {
251     MoveRightMostCharToSet(pairs);
252   }
253 #if DCHECK_IS_ON()
254   for (PairVector::const_iterator it = pairs->begin(); it != pairs->end();
255        ++it) {
256     DCHECK(it->character.empty());
257   }
258 #endif
259 }
260 
261 // Logs the generated string sets in regular-expression style, ie. [\x00-\x7f],
262 // [\xc2-\xdf][\x80-\xbf], etc. This can be a useful sanity-check that the
263 // algorithm is working. Use the command-line option
264 // --vmodule=build_utf8_validator_tables=1 to see this output.
LogStringSets(const PairVector & pairs)265 void LogStringSets(const PairVector& pairs) {
266   for (PairVector::const_iterator pair_it = pairs.begin();
267        pair_it != pairs.end();
268        ++pair_it) {
269     std::string set_as_string;
270     for (StringSet::const_iterator set_it = pair_it->set.begin();
271          set_it != pair_it->set.end();
272          ++set_it) {
273       set_as_string += base::StringPrintf("[\\x%02x-\\x%02x]",
274                                           static_cast<int>(set_it->from()),
275                                           static_cast<int>(set_it->to()));
276     }
277     VLOG(1) << set_as_string;
278   }
279 }
280 
281 // A single state in the state machine is represented by a sorted vector of
282 // start bytes and target states. All input bytes in the range between the start
283 // byte and the next entry in the vector (or 0xFF) result in a transition to the
284 // target state.
285 struct StateRange {
286   uint8_t from;
287   uint8_t target_state;
288 };
289 
290 typedef std::vector<StateRange> State;
291 
292 // Generates a state where all bytes go to state 1 (invalid). This is also used
293 // as an initialiser for other states (since bytes from outside the desired
294 // range are invalid).
GenerateInvalidState()295 State GenerateInvalidState() {
296   const StateRange range = {0, 1};
297   return State(1, range);
298 }
299 
300 // A map from a state (ie. a set of strings which will match from this state) to
301 // a number (which is an index into the array of states).
302 typedef std::map<StringSet, uint8_t> StateMap;
303 
304 // Create a new state corresponding to |set|, add it |states| and |state_map|
305 // and return the index it was given in |states|.
MakeState(const StringSet & set,std::vector<State> * states,StateMap * state_map)306 uint8_t MakeState(const StringSet& set,
307                   std::vector<State>* states,
308                   StateMap* state_map) {
309   DCHECK(!set.empty());
310   const Range& range = set.front();
311   const StringSet rest(set.begin() + 1, set.end());
312   const StateMap::const_iterator where = state_map->find(rest);
313   const uint8_t target_state = where == state_map->end()
314                                    ? MakeState(rest, states, state_map)
315                                    : where->second;
316   DCHECK_LT(0, range.from());
317   DCHECK_LT(range.to(), 0xFF);
318   const StateRange new_state_initializer[] = {
319       {0, 1},
320       {range.from(), target_state},
321       {static_cast<uint8_t>(range.to() + 1), 1}};
322   states->push_back(
323       State(new_state_initializer,
324             new_state_initializer + arraysize(new_state_initializer)));
325   const uint8_t new_state_number =
326       base::checked_cast<uint8_t>(states->size() - 1);
327   CHECK(state_map->insert(std::make_pair(set, new_state_number)).second);
328   return new_state_number;
329 }
330 
GenerateStates(const PairVector & pairs)331 std::vector<State> GenerateStates(const PairVector& pairs) {
332   // States 0 and 1 are the initial/valid state and invalid state, respectively.
333   std::vector<State> states(2, GenerateInvalidState());
334   StateMap state_map;
335   state_map.insert(std::make_pair(StringSet(), 0));
336   for (PairVector::const_iterator it = pairs.begin(); it != pairs.end(); ++it) {
337     DCHECK(it->character.empty());
338     DCHECK(!it->set.empty());
339     const Range& range = it->set.front();
340     const StringSet rest(it->set.begin() + 1, it->set.end());
341     const StateMap::const_iterator where = state_map.find(rest);
342     const uint8_t target_state = where == state_map.end()
343                                      ? MakeState(rest, &states, &state_map)
344                                      : where->second;
345     if (states[0].back().from == range.from()) {
346       DCHECK_EQ(1, states[0].back().target_state);
347       states[0].back().target_state = target_state;
348       DCHECK_LT(range.to(), 0xFF);
349       const StateRange new_range = {static_cast<uint8_t>(range.to() + 1), 1};
350       states[0].push_back(new_range);
351     } else {
352       DCHECK_LT(range.to(), 0xFF);
353       const StateRange new_range_initializer[] = {
354           {range.from(), target_state},
355           {static_cast<uint8_t>(range.to() + 1), 1}};
356       states[0]
357           .insert(states[0].end(),
358                   new_range_initializer,
359                   new_range_initializer + arraysize(new_range_initializer));
360     }
361   }
362   return states;
363 }
364 
365 // Output the generated states as a C++ table. Two tricks are used to compact
366 // the table: each state in the table starts with a shift value which indicates
367 // how many bits we can discard from the right-hand-side of the byte before
368 // doing the table lookup. Secondly, only the state-transitions for bytes
369 // with the top-bit set are included in the table; bytes without the top-bit set
370 // are just ASCII and are handled directly by the code.
PrintStates(const std::vector<State> & states,FILE * stream)371 void PrintStates(const std::vector<State>& states, FILE* stream) {
372   // First calculate the start-offset of each state. This allows the state
373   // machine to jump directly to the correct offset, avoiding an extra
374   // indirection. State 0 starts at offset 0.
375   std::vector<uint8_t> state_offset(1, 0);
376   std::vector<uint8_t> shifts;
377   uint8_t pos = 0;
378 
379   for (std::vector<State>::const_iterator state_it = states.begin();
380        state_it != states.end();
381        ++state_it) {
382     // We want to set |shift| to the (0-based) index of the least-significant
383     // set bit in any of the ranges for this state, since this tells us how many
384     // bits we can discard and still determine what range a byte lies in. Sadly
385     // it appears that ffs() is not portable, so we do it clumsily.
386     uint8_t shift = 7;
387     for (State::const_iterator range_it = state_it->begin();
388          range_it != state_it->end();
389          ++range_it) {
390       while (shift > 0 && range_it->from % (1 << shift) != 0) {
391         --shift;
392       }
393     }
394     shifts.push_back(shift);
395     pos += 1 + (1 << (7 - shift));
396     state_offset.push_back(pos);
397   }
398 
399   DCHECK_EQ(129, state_offset[1]);
400 
401   fputs(kProlog, stream);
402   TablePrinter table_printer(stream);
403 
404   for (uint8_t state_index = 0; state_index < states.size(); ++state_index) {
405     const uint8_t shift = shifts[state_index];
406     uint8_t next_range = 0;
407     uint8_t target_state = 1;
408     fprintf(stream,
409             "    // State %d, offset 0x%02x\n",
410             static_cast<int>(state_index),
411             static_cast<int>(state_offset[state_index]));
412     table_printer.PrintValue(shift);
413     for (int i = 0; i < 0x100; i += (1 << shift)) {
414       if (next_range < states[state_index].size() &&
415           states[state_index][next_range].from == i) {
416         target_state = states[state_index][next_range].target_state;
417         ++next_range;
418       }
419       if (i >= 0x80) {
420         table_printer.PrintValue(state_offset[target_state]);
421       }
422     }
423     table_printer.NewLine();
424   }
425 
426   fputs(kEpilog, stream);
427 }
428 
429 }  // namespace
430 
main(int argc,char * argv[])431 int main(int argc, char* argv[]) {
432   base::CommandLine::Init(argc, argv);
433   logging::LoggingSettings settings;
434   settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
435   logging::InitLogging(settings);
436   if (base::CommandLine::ForCurrentProcess()->HasSwitch("help")) {
437     fwrite(kHelpText, 1, arraysize(kHelpText), stdout);
438     exit(EXIT_SUCCESS);
439   }
440   base::FilePath filename =
441       base::CommandLine::ForCurrentProcess()->GetSwitchValuePath("output");
442 
443   FILE* output = stdout;
444   if (!filename.empty()) {
445     output = base::OpenFile(filename, "wb");
446     if (!output)
447       PLOG(FATAL) << "Couldn't open '" << filename.AsUTF8Unsafe()
448                   << "' for writing";
449   }
450 
451   // Step 1: Enumerate the characters
452   PairVector pairs = InitializeCharacters();
453   // Step 2: Convert to sets.
454   MoveAllCharsToSets(&pairs);
455   if (VLOG_IS_ON(1)) {
456     LogStringSets(pairs);
457   }
458   // Step 3: Generate states.
459   std::vector<State> states = GenerateStates(pairs);
460   // Step 4/5: Print output
461   PrintStates(states, output);
462 
463   if (!filename.empty()) {
464     if (!base::CloseFile(output))
465       PLOG(FATAL) << "Couldn't finish writing '" << filename.AsUTF8Unsafe()
466                   << "'";
467   }
468 
469   return EXIT_SUCCESS;
470 }
471