Debian Codegraph @

storage/innobase/ut/ut0ut.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1994, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file ut/ut0ut.cc
29 Various utilities for Innobase.
30
31 Created 5/11/1994 Heikki Tuuri
32 ********************************************************************/
33
34 #include "my_config.h"
35
36 #include <errno.h>
37 #include <time.h>
38 #include <string>
39
40 #include "ha_prototypes.h"
41
42 #ifdef HAVE_SYS_TIME_H
43 #include <sys/time.h>
44 #endif
45
46 #ifndef UNIV_HOTBACKUP
47 #include <mysql_com.h>
48 #endif /* !UNIV_HOTBACKUP */
49
50 #include "my_compiler.h"
51 #include "mysql_com.h"
52 #include "os0thread.h"
53 #include "ut0ut.h"
54
55 #ifndef UNIV_HOTBACKUP
56 #include "sql/log.h"
57 #include "trx0trx.h"
58 #endif /* !UNIV_HOTBACKUP */
59
60 #include "clone0api.h"
61 #include "mysql/components/services/log_builtins.h"
62 #include "sql/derror.h"
63
64 namespace ut {
65 ulong spin_wait_pause_multiplier = 50;
66 }
67
68 #ifdef UNIV_HOTBACKUP
69 /** Sprintfs a timestamp to a buffer with no spaces and with ':' characters
70 replaced by '_'.
71 @param[in] buf buffer where to sprintf */
72 void meb_sprintf_timestamp_without_extra_chars(
73 char *buf) /*!< in: buffer where to sprintf */
74 {
75 #ifdef _WIN32
76 SYSTEMTIME cal_tm;
77
78 GetLocalTime(&cal_tm);
79
80 sprintf(buf, "%02d%02d%02d_%2d_%02d_%02d", (int)cal_tm.wYear % 100,
81 (int)cal_tm.wMonth, (int)cal_tm.wDay, (int)cal_tm.wHour,
82 (int)cal_tm.wMinute, (int)cal_tm.wSecond);
83 #else
84 struct tm *cal_tm_ptr;
85 time_t tm;
86
87 struct tm cal_tm;
88 time(&tm);
89 localtime_r(&tm, &cal_tm);
90 cal_tm_ptr = &cal_tm;
91 sprintf(buf, "%02d%02d%02d_%2d_%02d_%02d", cal_tm_ptr->tm_year % 100,
92 cal_tm_ptr->tm_mon + 1, cal_tm_ptr->tm_mday, cal_tm_ptr->tm_hour,
93 cal_tm_ptr->tm_min, cal_tm_ptr->tm_sec);
94 #endif
95 }
96
97 #else /* UNIV_HOTBACKUP */
98
99 ulint ut_delay(ulint delay) {
100 ulint i, j;
101 /* We don't expect overflow here, as ut::spin_wait_pause_multiplier is limited
102 to 100, and values of delay are not larger than @@innodb_spin_wait_delay
103 which is limited by 1 000. Anyway, in case an overflow happened, the program
104 would still work (as iterations is unsigned). */
105 const ulint iterations = delay * ut::spin_wait_pause_multiplier;
106 UT_LOW_PRIORITY_CPU();
107
108 j = 0;
109
110 for (i = 0; i < iterations; i++) {
111 j += i;
112 UT_RELAX_CPU();
113 }
114
115 UT_RESUME_PRIORITY_CPU();
116
117 return (j);
118 }
119 #endif /* UNIV_HOTBACKUP */
120
121 /** Calculates fast the number rounded up to the nearest power of 2.
122 @return first power of 2 which is >= n */
123 ulint ut_2_power_up(ulint n) /*!< in: number != 0 */
124 {
125 ulint res;
126
127 res = 1;
128
129 ut_ad(n > 0);
130
131 while (res < n) {
132 res = res * 2;
133 }
134
135 return (res);
136 }
137
138 #ifndef UNIV_HOTBACKUP
139 /** Get a fixed-length string, quoted as an SQL identifier.
140 If the string contains a slash '/', the string will be
141 output as two identifiers separated by a period (.),
142 as in SQL database_name.identifier.
143 @param [in] trx transaction (NULL=no quotes).
144 @param [in] name table name.
145 @retval String quoted as an SQL identifier.
146 */
147 std::string ut_get_name(const trx_t *trx, const char *name) {
148 /* 2 * NAME_LEN for database and table name,
149 and some slack for the #mysql50# prefix and quotes */
150 char buf[3 * NAME_LEN];
151 const char *bufend;
152
153 bufend = innobase_convert_name(buf, sizeof buf, name, strlen(name),
154 trx ? trx->mysql_thd : nullptr);
155 buf[bufend - buf] = '\0';
156 return (std::string(buf, 0, bufend - buf));
157 }
158
159 /** Outputs a fixed-length string, quoted as an SQL identifier.
160 If the string contains a slash '/', the string will be
161 output as two identifiers separated by a period (.),
162 as in SQL database_name.identifier. */
163 void ut_print_name(FILE *f, /*!< in: output stream */
164 const trx_t *trx, /*!< in: transaction */
165 const char *name) /*!< in: name to print */
166 {
167 /* 2 * NAME_LEN for database and table name,
168 and some slack for the #mysql50# prefix and quotes */
169 char buf[3 * NAME_LEN];
170 const char *bufend;
171
172 bufend = innobase_convert_name(buf, sizeof buf, name, strlen(name),
173 trx ? trx->mysql_thd : nullptr);
174
175 if (fwrite(buf, 1, bufend - buf, f) != (size_t)(bufend - buf)) {
176 perror("fwrite");
177 }
178 }
179
180 /** Format a table name, quoted as an SQL identifier.
181 If the name contains a slash '/', the result will contain two
182 identifiers separated by a period (.), as in SQL
183 database_name.table_name.
184 @see table_name_t
185 @param[in] name table or index name
186 @param[out] formatted formatted result, will be NUL-terminated
187 @param[in] formatted_size size of the buffer in bytes
188 @return pointer to 'formatted' */
189 char *ut_format_name(const char *name, char *formatted, ulint formatted_size) {
190 switch (formatted_size) {
191 case 1:
192 formatted[0] = '\0';
193 [[fallthrough]];
194 case 0:
195 return (formatted);
196 }
197
198 char *end;
199
200 end = innobase_convert_name(formatted, formatted_size, name, strlen(name),
201 nullptr);
202
203 /* If the space in 'formatted' was completely used, then sacrifice
204 the last character in order to write '\0' at the end. */
205 if ((ulint)(end - formatted) == formatted_size) {
206 end--;
207 }
208
209 ut_a((ulint)(end - formatted) < formatted_size);
210
211 *end = '\0';
212
213 return (formatted);
214 }
215
216 /** Catenate files.
217 @param[in] dest Output file
218 @param[in] src Input file to be appended to output */
219 void ut_copy_file(FILE *dest, FILE *src) {
220 long len = ftell(src);
221 char buf[4096];
222
223 rewind(src);
224 do {
225 size_t maxs = len < (long)sizeof buf ? (size_t)len : sizeof buf;
226 size_t size = fread(buf, 1, maxs, src);
227 if (fwrite(buf, 1, size, dest) != size) {
228 perror("fwrite");
229 }
230 len -= (long)size;
231 if (size < maxs) {
232 break;
233 }
234 } while (len > 0);
235 }
236
237 void ut_format_byte_value(uint64_t data_bytes, std::string &data_str) {
238 int unit_sz = 1024;
239 auto exp = static_cast<int>(
240 (data_bytes == 0) ? 0 : std::log(data_bytes) / std::log(unit_sz));
241 auto data_value = data_bytes / std::pow(unit_sz, exp);
242
243 char unit[] = " KMGTPE";
244 auto index = static_cast<size_t>(exp > 0 ? exp : 0);
245
246 /* 64 BIT number should never go beyond Exabyte. */
247 auto max_index = sizeof(unit) - 2;
248 if (index > max_index) {
249 ut_d(ut_error);
250 ut_o(index = max_index);
251 }
252
253 std::stringstream data_strm;
254 if (index == 0) {
255 data_strm << std::setprecision(2) << std::fixed << data_value << " "
256 << "Bytes";
257 } else {
258 data_strm << std::setprecision(2) << std::fixed << data_value << " "
259 << unit[index] << "iB";
260 }
261 data_str = data_strm.str();
262 }
263
264 #endif /* !UNIV_HOTBACKUP */
265
266 #ifdef _WIN32
267 #include <stdarg.h>
268
269 /** A substitute for vsnprintf(3), formatted output conversion into
270 a limited buffer. Note: this function DOES NOT return the number of
271 characters that would have been printed if the buffer was unlimited because
272 VC's _vsnprintf() returns -1 in this case and we would need to call
273 _vscprintf() in addition to estimate that but we would need another copy
274 of "ap" for that and VC does not provide va_copy(). */
275 void ut_vsnprintf(char *str, /*!< out: string */
276 size_t size, /*!< in: str size */
277 const char *fmt, /*!< in: format */
278 va_list ap) /*!< in: format values */
279 {
280 _vsnprintf(str, size, fmt, ap);
281 str[size - 1] = '\0';
282 }
283
284 #endif /* _WIN32 */
285
286 /** Convert an error number to a human readable text message.
287 The returned string is static and should not be freed or modified.
288 @param[in] num InnoDB internal error number
289 @return string, describing the error */
290 const char *ut_strerr(dberr_t num) {
291 switch (num) {
292 case DB_SUCCESS:
293 return ("Success");
294 case DB_SUCCESS_LOCKED_REC:
295 return ("Success, record lock created");
296 case DB_SKIP_LOCKED:
297 return ("Skip locked records");
298 case DB_LOCK_NOWAIT:
299 return ("Don't wait for locks");
300 case DB_ERROR:
301 return ("Generic error");
302 case DB_READ_ONLY:
303 return ("Read only transaction");
304 case DB_INTERRUPTED:
305 return ("Operation interrupted");
306 case DB_OUT_OF_MEMORY:
307 return ("Cannot allocate memory");
308 case DB_OUT_OF_FILE_SPACE:
309 case DB_OUT_OF_DISK_SPACE:
310 return ("Out of disk space");
311 case DB_LOCK_WAIT:
312 return ("Lock wait");
313 case DB_DEADLOCK:
314 return ("Deadlock");
315 case DB_ROLLBACK:
316 return ("Rollback");
317 case DB_DUPLICATE_KEY:
318 return ("Duplicate key");
319 case DB_MISSING_HISTORY:
320 return ("Required history data has been deleted");
321 case DB_CLUSTER_NOT_FOUND:
322 return ("Cluster not found");
323 case DB_TABLE_NOT_FOUND:
324 return ("Table not found");
325 case DB_MUST_GET_MORE_FILE_SPACE:
326 return ("More file space needed");
327 case DB_TABLE_IS_BEING_USED:
328 return ("Table is being used");
329 case DB_TOO_BIG_RECORD:
330 return ("Record too big");
331 case DB_TOO_BIG_INDEX_COL:
332 return ("Index columns size too big");
333 case DB_LOCK_WAIT_TIMEOUT:
334 return ("Lock wait timeout");
335 case DB_NO_REFERENCED_ROW:
336 return ("Referenced key value not found");
337 case DB_ROW_IS_REFERENCED:
338 return ("Row is referenced");
339 case DB_CANNOT_ADD_CONSTRAINT:
340 return ("Cannot add constraint");
341 case DB_CORRUPTION:
342 return ("Data structure corruption");
343 case DB_CANNOT_DROP_CONSTRAINT:
344 return ("Cannot drop constraint");
345 case DB_NO_SAVEPOINT:
346 return ("No such savepoint");
347 case DB_TABLESPACE_EXISTS:
348 return ("Tablespace already exists");
349 case DB_TABLESPACE_DELETED:
350 return ("Tablespace deleted or being deleted");
351 case DB_TABLESPACE_NOT_FOUND:
352 return ("Tablespace not found");
353 case DB_LOCK_TABLE_FULL:
354 return ("Lock structs have exhausted the buffer pool");
355 case DB_FOREIGN_DUPLICATE_KEY:
356 return ("Foreign key activated with duplicate keys");
357 case DB_FOREIGN_EXCEED_MAX_CASCADE:
358 return ("Foreign key cascade delete/update exceeds max depth");
359 case DB_TOO_MANY_CONCURRENT_TRXS:
360 return ("Too many concurrent transactions");
361 case DB_UNSUPPORTED:
362 return ("Unsupported");
363 case DB_INVALID_NULL:
364 return ("NULL value encountered in NOT NULL column");
365 case DB_STATS_DO_NOT_EXIST:
366 return ("Persistent statistics do not exist");
367 case DB_FAIL:
368 return ("Failed, retry may succeed");
369 case DB_OVERFLOW:
370 return ("Overflow");
371 case DB_UNDERFLOW:
372 return ("Underflow");
373 case DB_STRONG_FAIL:
374 return ("Failed, retry will not succeed");
375 case DB_ZIP_OVERFLOW:
376 return ("Zip overflow");
377 case DB_RECORD_NOT_FOUND:
378 return ("Record not found");
379 case DB_CHILD_NO_INDEX:
380 return ("No index on referencing keys in referencing table");
381 case DB_PARENT_NO_INDEX:
382 return ("No index on referenced keys in referenced table");
383 case DB_FTS_INVALID_DOCID:
384 return ("FTS Doc ID cannot be zero");
385 case DB_INDEX_CORRUPT:
386 return ("Index corrupted");
387 case DB_UNDO_RECORD_TOO_BIG:
388 return ("Undo record too big");
389 case DB_END_OF_INDEX:
390 return ("End of index");
391 case DB_END_OF_BLOCK:
392 return ("End of block");
393 case DB_IO_ERROR:
394 return ("I/O error");
395 case DB_TABLE_IN_FK_CHECK:
396 return ("Table is being used in foreign key check");
397 case DB_DATA_MISMATCH:
398 return ("data mismatch");
399 case DB_SCHEMA_MISMATCH:
400 return ("schema mismatch");
401 case DB_NOT_FOUND:
402 return ("not found");
403 case DB_ONLINE_LOG_TOO_BIG:
404 return ("Log size exceeded during online index creation");
405 case DB_IDENTIFIER_TOO_LONG:
406 return ("Identifier name is too long");
407 case DB_FTS_EXCEED_RESULT_CACHE_LIMIT:
408 return ("FTS query exceeds result cache limit");
409 case DB_TEMP_FILE_WRITE_FAIL:
410 return ("Temp file write failure");
411 case DB_CANT_CREATE_GEOMETRY_OBJECT:
412 return ("Can't create specificed geometry data object");
413 case DB_CANNOT_OPEN_FILE:
414 return ("Cannot open a file");
415 case DB_TABLE_CORRUPT:
416 return ("Table is corrupted");
417 case DB_FTS_TOO_MANY_WORDS_IN_PHRASE:
418 return ("Too many words in a FTS phrase or proximity search");
419 case DB_IO_DECOMPRESS_FAIL:
420 return ("Page decompress failed after reading from disk");
421 case DB_IO_NO_PUNCH_HOLE:
422 return ("No punch hole support");
423 case DB_IO_NO_PUNCH_HOLE_FS:
424 return ("Punch hole not supported by the file system");
425 case DB_IO_NO_PUNCH_HOLE_TABLESPACE:
426 return ("Punch hole not supported by the tablespace");
427 case DB_IO_NO_ENCRYPT_TABLESPACE:
428 return ("Page encryption not supported by the tablespace");
429 case DB_IO_DECRYPT_FAIL:
430 return ("Page decryption failed after reading from disk");
431 case DB_IO_PARTIAL_FAILED:
432 return ("Partial IO failed");
433 case DB_FORCED_ABORT:
434 return (
435 "Transaction aborted by another higher priority "
436 "transaction");
437 case DB_WRONG_FILE_NAME:
438 return ("Invalid Filename");
439 case DB_NO_FK_ON_S_BASE_COL:
440 return (
441 "Cannot add foreign key on the base column "
442 "of stored column");
443 case DB_COMPUTE_VALUE_FAILED:
444 return ("Compute generated column failed");
445 case DB_V1_DBLWR_INIT_FAILED:
446 return (
447 "Failed to initialize the doublewrite extents "
448 "in the system tablespace");
449 case DB_V1_DBLWR_CREATE_FAILED:
450 return (
451 "Failed to create the doublewrite extents "
452 "in the system tablespace");
453 case DB_DBLWR_INIT_FAILED:
454 return ("Failed to create a doublewrite instance");
455 case DB_DBLWR_NOT_EXISTS:
456 return (
457 "Failed to find a doublewrite buffer "
458 "in the system tablespace");
459 case DB_INVALID_ENCRYPTION_META:
460 return ("Invalid encryption meta-data information");
461 case DB_ABORT_INCOMPLETE_CLONE:
462 return ("Incomplete cloned data directory");
463 case DB_SERVER_VERSION_LOW:
464 return (
465 "Cannot boot server with lower version than that built the "
466 "tablespace");
467 case DB_NO_SESSION_TEMP:
468 return ("No session temporary tablespace allocated");
469 case DB_TOO_LONG_PATH:
470 return (
471 "Cannot create tablespace since the filepath is too long for this "
472 "OS");
473 case DB_BTREE_LEVEL_LIMIT_EXCEEDED:
474 return ("Btree level limit exceeded");
475 case DB_END_SAMPLE_READ:
476 return ("Sample reader has been requested to stop sampling");
477 case DB_OUT_OF_RESOURCES:
478 return ("System has run out of resources");
479 case DB_FTS_TOO_MANY_NESTED_EXP:
480 return ("Too many nested sub-expressions in a full-text search");
481 case DB_PAGE_IS_STALE:
482 return "Page was discarded, was not written to storage.";
483 case DB_AUTOINC_READ_ERROR:
484 return "Auto-increment read failed";
485 case DB_FILE_READ_BEYOND_SIZE:
486 return "File read failure because of the read being beyond file size.";
487 case DB_ERROR_UNSET:;
488 /* Fall through. */
489
490 /* do not add default: in order to produce a warning if new code
491 is added to the enum but not added here */
492 }
493
494 /* we abort here because if unknown error code is given, this could
495 mean that memory corruption has happened and someone's error-code
496 variable has been overwritten with bogus data */
497 ut_error;
498 }
499
500 namespace ib {
501
502 #if !defined(UNIV_HOTBACKUP) && !defined(UNIV_NO_ERR_MSGS)
503
504 void logger::log_event(std::string msg) {
505 LogEvent()
506 .type(LOG_TYPE_ERROR)
507 .prio(m_level)
508 .errcode(m_err)
509 .subsys("InnoDB")
510 .verbatim(msg.c_str());
511 }
512 logger::~logger() { log_event(m_oss.str()); }
513
514 /*
515 MSVS complains: Warning C4722: destructor never returns, potential memory leak.
516 But, the whole point of using ib::fatal temporary object is to cause an abort.
517 */
518 MY_COMPILER_DIAGNOSTIC_PUSH()
519 MY_COMPILER_MSVC_DIAGNOSTIC_IGNORE(4722)
520
521 fatal::~fatal() {
522 log_event("[FATAL] " + m_oss.str());
523 ut_dbg_assertion_failed("ib::fatal triggered", m_location.filename,
524 m_location.line);
525 }
526 // Restore the MSVS checks for Warning C4722, silenced for ib::fatal::~fatal().
527 MY_COMPILER_DIAGNOSTIC_POP()
528
529 fatal_or_error::~fatal_or_error() {
530 if (m_fatal) {
531 log_event("[FATAL] " + m_oss.str());
532 ut_dbg_assertion_failed("ib::fatal_or_error triggered", m_location.filename,
533 m_location.line);
534 }
535 }
536
537 #endif /* !UNIV_NO_ERR_MSGS */
538
539 } // namespace ib