File: range_check_err.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (315 lines) | stat: -rw-r--r-- 11,191 bytes parent folder | download
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
/* Copyright (c) 2019, 2025, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License, version 2.0,
   as published by the Free Software Foundation.

   This program is designed to work with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have either included with
   the program or referenced in the documentation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License, version 2.0, for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

/**
  A naive tool to help find code that tries to send messages intended
  for sending to the client to the error log. (The fix for such a
  situation is to find the corresponding message in the server-range
  (index >= 10,000) if it exists, or to create a new message in that
  range if it doesn't.)


  Messages to the client (via diagnostics area: my_error() etc.)

  When new or changed code sends a message to the client, there should
  be a .test case for that code path; if the message is in the wrong
  range (i.e. if it has an index >= 10,000 and therefore is in the range
  allocated to messages to the error log), our asserts should then catch
  it.


  Messages to error-log (LogErr(), LogEvent(), etc.)

  The issues that are intended to be error-logged are sometimes hard
  to raise artificially, and therefore 100 % test coverage of these
  cases can be hard to achieve. This tool is intended to help find
  some of these cases; to that end, it looks for calls to LogErr()
  and LogEvent(), parses out the ER_ symbol, and looks it up in an
  array derived from errmgs-utf8.txt to see whether its index is in
  the server (that is to say, "messages intended for the error-log")
  range, i.e. >= 10,0000. If it's not in the correct range, we print
  a message saying so. Likewise, if an undefined symbol is used, we
  print a message saying so.


  Use

  The tool can accept the path-and-name of a source file on the command
  line, like so: range_check_err sql/mysqld.cc
  If no source file is given on the command line, the tool will instead
  read paths from stdin, one per line:

    find  . -iname "*.cc" -or -iname "*.h"|
      ./runtime_output_directory/range_check_err


  Caveats

  The tool is specific to the tree and version it was built for,
  that is to say, it knows exactly those error-symbols and messages
  which are defined in that tree's share/messages_to_*.txt.  Using
  one build's tool on a different checkout is likely to render
  nonsensical results.

  The tool is in its proof-of-concept stage. Lookups can be sped up.
  The tool will disregard preprocessor directives, and thereby find
  issues in code-paths that do not get built often, which is a feature;
  it will also currently parse calls contained in comments, which is
  likely to be regarded a feature by some, and a bug by others.
  Calls contained in quoted string however are ignored by design.

  The tool currently checks the calls LogErr() and LogEvent().
*/

#include <algorithm>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>

#include "my_inttypes.h"

struct {
  const char *name;        ///< MySQL error symbol ("ER_STARTUP")
  uint mysql_errno;        ///< MySQL error code (consecutive within sections)
  const char *text;        ///< MySQL error message
  const char *odbc_state;  ///< SQL state
  const char *jdbc_state;  ///< JBDC state
  uint error_index;        ///< consecutive. 0 for obsolete.
} typedef server_error;

extern "C" {

server_error errors[] = {
#ifndef IN_DOXYGEN
#include <mysqld_ername.h>

    {nullptr, 0, nullptr, nullptr, nullptr, 0}  // DUMMY ROW
#endif                                          /* IN_DOXYGEN */
};
}

/**
  Find an error-record by it's symbol (e.g. "ER_BAD_TABLE_ERROR")

  @param   symbol     The symbol to look for as a C-string

  @retval  nullptr    No matching record found
  @retval  !=nullptr  The server_error record for the given symbol
*/
server_error *find_error_record_by_symbol(const char *symbol) {
  // naive lookup. optimize later.
  size_t error_record_count = sizeof(errors) / sizeof(server_error) - 1;

  for (size_t index = 0; index < error_record_count; index++) {
    if (0 == strcmp(symbol, errors[index].name)) return &errors[index];
  }

  return nullptr;
}

/**
  Determine whether an error-code is in a reserved range
  (in which case the tool shall not pass judgment on it).

  @param   errcode  Error-code

  @retval  true     The error-code is in a reserved range
  @retval  false    The error-code is not in a reserved range
*/
bool is_reserved_errcode(uint errcode) {
  // x plugin
  if ((errcode >= 5000) && (errcode <= 5999)) return true;
  // reserved (3rd party)
  if ((errcode >= 50000) && (errcode <= 51999)) return true;
  return false;
}

/**
  Determine whether an error-code is valid for use in error-logging.

  @param   errcode  Error-code

  @retval  true     use is legit
  @retval  false    use is a likely to be a bug
*/
bool is_valid_errlog_errcode(uint errcode) {
  return (is_reserved_errcode(errcode) || (errcode >= 10000));
}

/**
  Check a source file.

  @param   file_name  The path-and-name of a source file to verify (C-string)

  @retval  number of detected issues
*/
int check_source(const char *file_name) {
  // read the entirety of the input file (that is, a C++ source file)
  std::ifstream source_file(file_name);
  std::stringstream file_contents;
  file_contents << source_file.rdbuf();
  std::string buff = file_contents.str();

  const char *buff_start = buff.c_str();  ///< start of our text buffer
  const char *curr = buff_start;          ///< current read position

  std::string stmt;        ///< string containing the LogE*() statement
  const char *stmt_start;  ///< start of LogE*() statement in text buffer

  int is_err;     ///< set t if LogErr() (rather than LogEvent())
  int count = 0;  ///< number of detected issues ("wrong" ER_* symbols)

  /*
    Look for LogErr() and LogEvent() statements in the buffer
    containing the source file.
  */
  while ((curr = strstr(curr, "LogE")) != nullptr) {
    if (((0 == (is_err = strncmp(curr, "LogErr(", 7))) ||
         (0 == strncmp(curr, "LogEvent(", 9))) &&
        ((curr == buff_start) || (isspace((int)curr[-1])))) {
      stmt_start = curr;  // remember start of the LogE*() statement

      curr = strchr(curr, '(');  // strcmp() told us this won't fail

      // find the end of the LogE*() statement
      do {
        if (*curr == '\"') {  // on opening quote, skip string
          curr++;

          // skip to end of string, handling \"
          while ((*curr != '\0') && (*curr != '\"')) {
            if ((curr[0] == '\\') && (curr[1] == '\"'))  // \" isn't end-quote
              curr++;
            curr++;
          }
          if (*curr != '\0')  // position after string
            curr++;
        } else  // we're not in a quoted string, proceed with next character
          curr++;
      } while ((*curr != '\0') && (*curr != ';'));  // until end of stmt/buffer

      if (*curr != '\0') {
        /*
          We found something that looks like a LogE*() statement.
          Now check whether it's valid!
        */

        std::string symbol;     ///< ER_FOO-type symbol
        const char *sym_start,  ///< symbol start
            *sym_end;           ///< symbol end

        // copy entire statement to variable and remove line-breaks
        stmt.assign(stmt_start, (size_t)(curr - stmt_start + 1L));
        std::replace(stmt.begin(), stmt.end(), '\n', ' ');

        if (is_err == 0) {  // It's LogErr(), symbol is 2nd argument
          if ((sym_start = strchr(stmt_start, ',')) != nullptr) {
            while ((*sym_start == ',') || (isspace((int)*sym_start)))
              sym_start++;
          }
        } else {  // It's LogEvent(), symbol can appear anywhere
          if ((sym_start = strstr(stmt_start, "(ER_")) != nullptr) sym_start++;
        }

        /*
          The symbol we find was behind statement end, so statement
          did not contain a symbol (and therefore was faulty).
        */
        if (sym_start > curr) sym_start = nullptr;

        if (sym_start != nullptr) {
          // We found a symbol. Find its end!
          sym_end = sym_start;
          while (isupper((int)*sym_end) || isdigit((int)*sym_end) ||
                 (*sym_end == '_'))
            sym_end++;

          // Save symbol in variable.
          symbol.assign(sym_start, (size_t)(sym_end - sym_start));

          /*
            We may not have a symbol here
            - if the macro name was referenced in a comment ("LogErr()")
            - if a variable instead of a constant is used
          */
          if (sym_start != sym_end) {
            // look up the symbol
            server_error *err_record;
            err_record = find_error_record_by_symbol(symbol.c_str());

            if (err_record == nullptr) {
              // symbol unknown, complain!
              count++;
              std::cerr << file_name
                        << ": error logging statement using unknown symbol "
                        << symbol << " found: \"" << stmt << "\"\n";
            } else if (!is_valid_errlog_errcode(err_record->mysql_errno)) {
              // symbol known, but in wrong range; complain!
              count++;
              std::cerr << file_name << ": error logging statement using "
                        << symbol << " (" << err_record->mysql_errno
                        << ") found: \"" << stmt << "\"\n";
            }
          }  // potential symbol non-empty?
        }    // found start of potential symbol?
      }      // not end of buffer?
    } else   // found "LogE" is not actually part of LogErr() or LogEvent() call
      curr++;  // skip bogus LogE
  }            // while())

  return count;  // return number of detected issues
}

/**
  Read paths of source files from stdin, one per line, and verify the files.

  @retval  number of detected issues
*/
int check_stdin() {
  int count = 0;

  std::string line;
  while (getline(std::cin, line)) {
    count += check_source(line.c_str());
  }

  return count;
}

int main(int argc, char **argv) {
  if (argc == 1) {
    return check_stdin();
  }
  if (argc == 2) {
    return check_source(argv[1]);
  }

  std::cerr << argv[0] << " [</path/to/source_file.cc>]"
            << "\n\n"
            << "If no source file is given, we will read file names, "
            << "one per line, from stdin."
            << "\n";

  return 0;
}